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/src/net/fred/feedex/activity/EntryActivity.java b/src/net/fred/feedex/activity/EntryActivity.java
index 9addd05..84663e9 100644
--- a/src/net/fred/feedex/activity/EntryActivity.java
+++ b/src/net/fred/feedex/activity/EntryActivity.java
@@ -1,881 +1,881 @@
/**
* FeedEx
*
* Copyright (c) 2012-2013 Frederic Julian
*
* 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/>.
*
*
* Some parts of this software are based on "Sparse rss" under the MIT license (see
* below). Please refers to the original project to identify which parts are under the
* MIT license.
*
* Copyright (c) 2010-2012 Stefan Handschuh
*
* 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.fred.feedex.activity;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateFormat;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.widget.ViewFlipper;
import net.fred.feedex.Constants;
import net.fred.feedex.R;
import net.fred.feedex.provider.FeedData;
import net.fred.feedex.provider.FeedData.EntryColumns;
import net.fred.feedex.provider.FeedData.FeedColumns;
import net.fred.feedex.provider.FeedData.TaskColumns;
import net.fred.feedex.provider.FeedDataContentProvider;
import net.fred.feedex.service.FetcherService;
import net.fred.feedex.utils.PrefUtils;
import net.fred.feedex.utils.ThrottledContentObserver;
import net.fred.feedex.utils.UiUtils;
import java.util.Date;
public class EntryActivity extends ProgressActivity {
private static final String SAVE_INSTANCE_SCROLL_PERCENTAGE = "scrollPercentage";
private static final String SAVE_INSTANCE_ENTRIES_IDS = "entriesIds";
private static final String SAVE_INSTANCE_IS_FULLSCREEN = "isFullscreen";
private static final long ANIM_DURATION = 250;
private static final TranslateAnimation SLIDE_IN_RIGHT = generateAnimation(1, 0);
private static final TranslateAnimation SLIDE_IN_LEFT = generateAnimation(-1, 0);
private static final TranslateAnimation SLIDE_OUT_RIGHT = generateAnimation(0, 1);
private static final TranslateAnimation SLIDE_OUT_LEFT = generateAnimation(0, -1);
private static TranslateAnimation generateAnimation(float fromX, float toX) {
TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, fromX, Animation.RELATIVE_TO_SELF, toX, 0, 0, 0, 0);
anim.setDuration(ANIM_DURATION);
return anim;
}
private static final String TEXT_HTML = "text/html";
private static final String HTML_IMG_REGEX = "(?i)<[/]?[ ]?img(.|\n)*?>";
private static final String BACKGROUND_COLOR = PrefUtils.getBoolean(PrefUtils.LIGHT_THEME, true) ? "#f6f6f6" : "#181b1f";
private static final String TEXT_COLOR = PrefUtils.getBoolean(PrefUtils.LIGHT_THEME, true) ? "#000000" : "#C0C0C0";
private static final String BUTTON_COLOR = PrefUtils.getBoolean(PrefUtils.LIGHT_THEME, true) ? "#D0D0D0" : "#505050";
private static final String CSS = "<head><style type='text/css'>body {background-color:"
+ BACKGROUND_COLOR
+ "; max-width: 100%; font-family: sans-serif-light}\nimg {max-width: 100%; height: auto;}\ndiv[style] {max-width: 100%;}\npre {white-space: pre-wrap;}</style></head>";
private static final String BODY_START = CSS + "<body link='#97ACE5' text='" + TEXT_COLOR + "'>";
private static final String FONTSIZE_START = CSS + BODY_START + "<font size='+";
private static final String FONTSIZE_MIDDLE = "'>";
private static final String BODY_END = "<br/><br/><br/><br/></body>";
private static final String FONTSIZE_END = "</font>" + BODY_END;
private static final String TITLE_START = "<p style='margin-top:1cm; margin-bottom:0.6cm'><font size='+2'><a href='";
private static final String TITLE_MIDDLE = "' style='text-decoration: none; color:inherit'>";
private static final String TITLE_END = "</a></font></p>";
private static final String SUBTITLE_START = "<font size='-1'>";
private static final String SUBTITLE_END = "</font><div style='width:100%; border:0px; height:1px; margin-top:0.1cm; background:#33b5e5'/><br/><div align='justify'>";
private static final String BUTTON_SEPARATION = "</div><br/>";
private static final String BUTTON_START = "<div style='text-align: center'><input type='button' value='";
private static final String BUTTON_MIDDLE = "' onclick='";
private static final String BUTTON_END = "' style='background-color:" + BUTTON_COLOR + "; color:" + TEXT_COLOR
+ "; border: none; border-radius:0.2cm; padding: 0.3cm;'/></div>";
private static final String LINK_BUTTON_START = "<div style='text-align: center; margin-top:0.4cm'><a href='";
private static final String LINK_BUTTON_MIDDLE = "' style='background-color:" + BUTTON_COLOR + "; color:" + TEXT_COLOR
+ "; text-decoration: none; border: none; border-radius:0.2cm; padding: 0.3cm;'>";
private static final String LINK_BUTTON_END = "</a></div>";
private static final String IMAGE_ENCLOSURE = "[@]image/";
private int titlePosition, datePosition, mobilizedHtmlPosition, abstractPosition, linkPosition, feedIdPosition, isFavoritePosition,
isReadPosition, enclosurePosition, authorPosition;
private long _id = -1;
private long _nextId = -1;
private long _previousId = -1;
private long[] mEntriesIds;
private Uri uri;
private Uri parentUri;
private int feedId;
private boolean favorite, preferFullText = true;
private byte[] iconBytes = null;
private WebView webView;
private WebView webView0; // only needed for the animation
private ViewFlipper viewFlipper;
private float mScrollPercentage = 0;
private String link, title, enclosure;
private LayoutParams layoutParams;
private View cancelFullscreenBtn, backBtn, forwardBtn;
private boolean mFromWidget = false;
final private OnKeyListener onKeyEventListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
scrollUp();
return true;
} else if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
scrollDown();
return true;
}
}
return false;
}
};
private GestureDetector gestureDetector;
final private OnTouchListener onTouchListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
private final ThrottledContentObserver mTasksObserver = new ThrottledContentObserver(new Handler(), 2000) {
@Override
public void onChangeThrottled() {
boolean isMobilizing = FetcherService.getMobilizingTaskId(_id) != -1;
if ((getProgressBar().getVisibility() == View.VISIBLE && isMobilizing)
|| (getProgressBar().getVisibility() == View.GONE && !isMobilizing)) {
return; // no change => no update
}
if (isMobilizing) { // We start a mobilization
getProgressBar().setVisibility(View.VISIBLE);
} else { // We finished one
preferFullText = true;
reload(true);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
UiUtils.setPreferenceTheme(this);
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.entry);
gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (Math.abs(velocityY) * 1.5 < Math.abs(velocityX)) {
if (velocityX > 800) {
if (_previousId != -1 && webView.getScrollX() == 0) {
previousEntry();
}
} else if (velocityX < -800) {
if (_nextId != -1) {
nextEntry();
}
}
}
return false;
}
});
uri = getIntent().getData();
parentUri = EntryColumns.PARENT_URI(uri.getPath());
feedId = 0;
Bundle b = getIntent().getExtras();
if (b != null) {
mFromWidget = b.getBoolean(Constants.INTENT_FROM_WIDGET, false);
}
Cursor entryCursor = getContentResolver().query(uri, null, null, null, null);
titlePosition = entryCursor.getColumnIndex(EntryColumns.TITLE);
datePosition = entryCursor.getColumnIndex(EntryColumns.DATE);
abstractPosition = entryCursor.getColumnIndex(EntryColumns.ABSTRACT);
mobilizedHtmlPosition = entryCursor.getColumnIndex(EntryColumns.MOBILIZED_HTML);
linkPosition = entryCursor.getColumnIndex(EntryColumns.LINK);
feedIdPosition = entryCursor.getColumnIndex(EntryColumns.FEED_ID);
isFavoritePosition = entryCursor.getColumnIndex(EntryColumns.IS_FAVORITE);
isReadPosition = entryCursor.getColumnIndex(EntryColumns.IS_READ);
enclosurePosition = entryCursor.getColumnIndex(EntryColumns.ENCLOSURE);
authorPosition = entryCursor.getColumnIndex(EntryColumns.AUTHOR);
entryCursor.close();
cancelFullscreenBtn = findViewById(R.id.cancelFullscreenBtn);
backBtn = findViewById(R.id.backBtn);
forwardBtn = findViewById(R.id.forwardBtn);
viewFlipper = (ViewFlipper) findViewById(R.id.content_flipper);
layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
webView = new WebView(this);
setupWebview(webView);
viewFlipper.addView(webView, layoutParams);
webView0 = new WebView(this);
setupWebview(webView0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
webView.saveState(outState);
outState.putLongArray(SAVE_INSTANCE_ENTRIES_IDS, mEntriesIds);
outState.putBoolean(SAVE_INSTANCE_IS_FULLSCREEN, !getActionBar().isShowing());
float positionTopView = webView.getTop();
float contentHeight = webView.getContentHeight();
float currentScrollPosition = webView.getScrollY();
outState.putFloat(SAVE_INSTANCE_SCROLL_PERCENTAGE, (currentScrollPosition - positionTopView) / contentHeight);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mEntriesIds = savedInstanceState.getLongArray(SAVE_INSTANCE_ENTRIES_IDS);
mScrollPercentage = savedInstanceState.getFloat(SAVE_INSTANCE_SCROLL_PERCENTAGE);
if (savedInstanceState.getBoolean(SAVE_INSTANCE_IS_FULLSCREEN)) {
toggleFullScreen();
}
webView.restoreState(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
if (Constants.NOTIF_MGR != null) {
Constants.NOTIF_MGR.cancel(0);
}
uri = getIntent().getData();
parentUri = EntryColumns.PARENT_URI(uri.getPath());
try {
webView.onResume();
} catch (Exception unused) { // Seems possible to have an NPE here on some phones...
}
reload(false);
}
@Override
protected void onPause() {
super.onPause();
try {
webView.onPause();
} catch (Exception unused) { // Seems possible to have an NPE here on some phones...
}
getContentResolver().unregisterContentObserver(mTasksObserver);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
private void toggleFullScreen() {
if (getActionBar().isShowing()) {
getActionBar().hide();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
cancelFullscreenBtn.setVisibility(View.VISIBLE);
} else {
getActionBar().show();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
cancelFullscreenBtn.setVisibility(View.GONE);
}
}
private void reload(boolean forceUpdate) {
long newId = Long.parseLong(uri.getLastPathSegment());
if (!forceUpdate && _id == newId) {
return;
}
_id = newId;
ContentResolver cr = getContentResolver();
Cursor entryCursor = cr.query(uri, null, null, null, null);
if (entryCursor.moveToFirst()) {
String contentText = entryCursor.getString(mobilizedHtmlPosition);
if (contentText == null || (forceUpdate && !preferFullText)) {
preferFullText = false;
contentText = entryCursor.getString(abstractPosition);
} else {
preferFullText = true;
}
if (contentText == null) {
contentText = "";
}
// Need to be done before the "mark as read" action
setupNavigationButton();
// Mark the article as read
if (entryCursor.getInt(isReadPosition) != 1) {
if (cr.update(uri, FeedData.getReadContentValues(), null, null) > 0) {
FeedDataContentProvider.notifyAllFromEntryUri(uri, false);
}
}
int _feedId = entryCursor.getInt(feedIdPosition);
if (feedId != _feedId) {
if (feedId != 0) {
iconBytes = null; // triggers re-fetch of the icon
}
feedId = _feedId;
}
title = entryCursor.getString(titlePosition);
Cursor cursor = cr.query(FeedColumns.CONTENT_URI(feedId), new String[]{FeedColumns.NAME, FeedColumns.URL}, null, null, null);
if (cursor.moveToFirst()) {
setTitle(cursor.isNull(0) ? cursor.getString(1) : cursor.getString(0));
} else { // fallback, should not be possible
setTitle(title);
}
cursor.close();
if (iconBytes == null || iconBytes.length == 0) {
Cursor iconCursor = cr.query(FeedColumns.CONTENT_URI(Integer.toString(feedId)),
new String[]{FeedColumns._ID, FeedColumns.ICON}, null, null, null);
if (iconCursor.moveToFirst()) {
iconBytes = iconCursor.getBlob(1);
}
iconCursor.close();
}
if (iconBytes != null && iconBytes.length > 0) {
int bitmapSizeInDip = UiUtils.dpToPixel(24);
Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
if (bitmap != null) {
if (bitmap.getHeight() != bitmapSizeInDip) {
bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false);
}
getActionBar().setIcon(new BitmapDrawable(getResources(), bitmap));
} else {
getActionBar().setIcon(R.drawable.icon);
}
} else {
getActionBar().setIcon(R.drawable.icon);
}
favorite = entryCursor.getInt(isFavoritePosition) == 1;
invalidateOptionsMenu();
// loadData does not recognize the encoding without correct html-header
boolean localPictures = contentText.contains(Constants.IMAGEID_REPLACEMENT);
if (localPictures) {
contentText = contentText.replace(Constants.IMAGEID_REPLACEMENT, _id + Constants.IMAGEFILE_IDSEPARATOR);
}
if (PrefUtils.getBoolean(PrefUtils.DISABLE_PICTURES, false)) {
contentText = contentText.replaceAll(HTML_IMG_REGEX, "");
webView.getSettings().setBlockNetworkImage(true);
} else {
if (webView.getSettings().getBlockNetworkImage()) {
// setBlockNetwortImage(false) calls postSync, which takes time, so we clean up the html first and change the value afterwards
webView.loadData("", TEXT_HTML, Constants.UTF8);
webView.getSettings().setBlockNetworkImage(false);
}
}
String author = entryCursor.getString(authorPosition);
long timestamp = entryCursor.getLong(datePosition);
link = entryCursor.getString(linkPosition);
enclosure = entryCursor.getString(enclosurePosition);
// String baseUrl = "";
// try {
// URL url = new URL(link);
// baseUrl = url.getProtocol() + "://" + url.getHost();
// } catch (MalformedURLException ignored) {
// }
- webView.loadDataWithBaseURL(null, generateHtmlContent(title, link, contentText, enclosure, author, timestamp), TEXT_HTML, Constants.UTF8,
- null);
+ webView.loadDataWithBaseURL("", generateHtmlContent(title, link, contentText, enclosure, author, timestamp), TEXT_HTML, Constants.UTF8,
+ null); // do not put 'null' to the base url...
// Listen the mobilizing task
long mobilizingTaskId = FetcherService.getMobilizingTaskId(_id);
if (mobilizingTaskId != -1) {
getProgressBar().setVisibility(View.VISIBLE);
cr.unregisterContentObserver(mTasksObserver);
cr.registerContentObserver(TaskColumns.CONTENT_URI(mobilizingTaskId), false, mTasksObserver);
} else {
getProgressBar().setVisibility(View.GONE);
cr.unregisterContentObserver(mTasksObserver);
}
}
entryCursor.close();
}
private String generateHtmlContent(String title, String link, String abstractText, String enclosure, String author, long timestamp) {
StringBuilder content = new StringBuilder();
int fontSize = Integer.parseInt(PrefUtils.getString(PrefUtils.FONT_SIZE, "0"));
if (fontSize > 0) {
content.append(FONTSIZE_START).append(fontSize).append(FONTSIZE_MIDDLE);
} else {
content.append(BODY_START);
}
if (link == null) {
link = "";
}
content.append(TITLE_START).append(link).append(TITLE_MIDDLE).append(title).append(TITLE_END).append(SUBTITLE_START);
Date date = new Date(timestamp);
StringBuilder dateStringBuilder = new StringBuilder(DateFormat.getDateFormat(this).format(date)).append(' ').append(
DateFormat.getTimeFormat(this).format(date));
if (author != null && !author.isEmpty()) {
dateStringBuilder.append(" — ").append(author);
}
content.append(dateStringBuilder).append(SUBTITLE_END).append(abstractText).append(BUTTON_SEPARATION).append(BUTTON_START);
if (!preferFullText) {
content.append(getString(R.string.get_full_text)).append(BUTTON_MIDDLE).append("injectedJSObject.onClickFullText();");
} else {
content.append(getString(R.string.original_text)).append(BUTTON_MIDDLE).append("injectedJSObject.onClickOriginalText();");
}
content.append(BUTTON_END);
if (enclosure != null && enclosure.length() > 6 && !enclosure.contains(IMAGE_ENCLOSURE)) {
content.append(BUTTON_START).append(getString(R.string.see_enclosure)).append(BUTTON_MIDDLE)
.append("injectedJSObject.onClickEnclosure();").append(BUTTON_END);
}
if (link != null && link.length() > 0) {
content.append(LINK_BUTTON_START).append(link).append(LINK_BUTTON_MIDDLE).append(getString(R.string.see_link)).append(LINK_BUTTON_END);
}
if (fontSize > 0) {
content.append(FONTSIZE_END);
} else {
content.append(BODY_END);
}
return content.toString();
}
@SuppressLint("SetJavaScriptEnabled")
private void setupWebview(final WebView wv) {
// For color
wv.setBackgroundColor(Color.parseColor(BACKGROUND_COLOR));
// For scrolling & gesture
wv.setOnKeyListener(onKeyEventListener);
wv.setOnTouchListener(onTouchListener);
// For javascript
wv.getSettings().setJavaScriptEnabled(true);
wv.addJavascriptInterface(injectedJSObject, "injectedJSObject");
// For HTML5 video
wv.setWebChromeClient(new WebChromeClient());
wv.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (mScrollPercentage != 0) {
view.postDelayed(new Runnable() {
@Override
public void run() {
float webviewsize = wv.getContentHeight() - wv.getTop();
float positionInWV = webviewsize * mScrollPercentage;
int positionY = Math.round(wv.getTop() + positionInWV);
wv.scrollTo(0, positionY);
}
// Delay the scrollTo to make it work
}, 150);
}
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try {
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(EntryActivity.this, R.string.cant_open_link, Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
private void showEnclosure(Uri uri, String enclosure, int position1, int position2) {
try {
startActivityForResult(new Intent(Intent.ACTION_VIEW).setDataAndType(uri, enclosure.substring(position1 + 3, position2)), 0);
} catch (Exception e) {
try {
startActivityForResult(new Intent(Intent.ACTION_VIEW, uri), 0); // fallbackmode - let the browser handle this
} catch (Throwable t) {
Toast.makeText(EntryActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
private void setupNavigationButton() {
_previousId = -1;
backBtn.setVisibility(View.GONE);
_nextId = -1;
forwardBtn.setVisibility(View.GONE);
if (mEntriesIds == null) {
Cursor cursor = getContentResolver().query(parentUri, EntryColumns.PROJECTION_ID,
PrefUtils.getBoolean(PrefUtils.SHOW_READ, true) || EntryColumns.FAVORITES_CONTENT_URI.equals(parentUri) ? null
: EntryColumns.WHERE_UNREAD, null, EntryColumns.DATE + Constants.DB_DESC);
mEntriesIds = new long[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
mEntriesIds[i++] = cursor.getLong(0);
}
cursor.close();
}
for (int i = 0; i < mEntriesIds.length; ++i) {
if (_id == mEntriesIds[i]) {
if (i > 0) {
_previousId = mEntriesIds[i - 1];
backBtn.setVisibility(View.VISIBLE);
}
if (i < mEntriesIds.length - 1) {
_nextId = mEntriesIds[i + 1];
forwardBtn.setVisibility(View.VISIBLE);
}
break;
}
}
}
private void switchEntry(long id, Animation inAnimation, Animation outAnimation) {
uri = parentUri.buildUpon().appendPath(String.valueOf(id)).build();
getIntent().setData(uri);
mScrollPercentage = 0;
WebView tmp = webView; // switch reference
webView = webView0;
webView0 = tmp;
reload(false);
viewFlipper.setInAnimation(inAnimation);
viewFlipper.setOutAnimation(outAnimation);
viewFlipper.addView(webView, layoutParams);
viewFlipper.showNext();
viewFlipper.removeViewAt(0);
// To clear memory and avoid possible glitches
viewFlipper.postDelayed(new Runnable() {
@Override
public void run() {
webView0.loadUrl("about:blank");
}
}, ANIM_DURATION);
}
private void nextEntry() {
switchEntry(_nextId, SLIDE_IN_RIGHT, SLIDE_OUT_LEFT);
}
private void previousEntry() {
switchEntry(_previousId, SLIDE_IN_LEFT, SLIDE_OUT_RIGHT);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.entry, menu);
if (favorite) {
MenuItem item = menu.findItem(R.id.menu_star);
item.setTitle(R.string.menu_unstar).setIcon(R.drawable.rating_important);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mFromWidget) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
finish();
return true;
case R.id.menu_star:
favorite = !favorite;
ContentValues values = new ContentValues();
values.put(EntryColumns.IS_FAVORITE, favorite ? 1 : 0);
ContentResolver cr = getContentResolver();
if (cr.update(uri, values, null, null) > 0) {
FeedDataContentProvider.notifyAllFromEntryUri(uri, true);
}
if (favorite) {
item.setTitle(R.string.menu_unstar).setIcon(R.drawable.rating_important);
} else {
item.setTitle(R.string.menu_star).setIcon(R.drawable.rating_not_important);
}
break;
case R.id.menu_share:
if (link != null) {
startActivity(Intent.createChooser(
new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title).putExtra(Intent.EXTRA_TEXT, link)
.setType(Constants.MIMETYPE_TEXT_PLAIN), getString(R.string.menu_share)));
}
break;
case R.id.menu_full_screen: {
toggleFullScreen();
break;
}
case R.id.menu_copy_clipboard: {
ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = android.content.ClipData.newPlainText("Copied Text", link);
clipboard.setPrimaryClip(clip);
Toast.makeText(this, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
break;
}
case R.id.menu_mark_as_unread:
new Thread() {
@Override
public void run() {
ContentResolver cr = getContentResolver();
if (cr.update(uri, FeedData.getUnreadContentValues(), null, null) > 0) {
FeedDataContentProvider.notifyAllFromEntryUri(uri, false);
}
}
}.start();
finish();
break;
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
scrollUp();
return true;
} else if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
scrollDown();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private void scrollUp() {
if (webView != null) {
webView.pageUp(false);
}
}
private void scrollDown() {
if (webView != null) {
webView.pageDown(false);
}
}
/**
* Works around android issue 6191
*/
@Override
public void unregisterReceiver(BroadcastReceiver receiver) {
try {
super.unregisterReceiver(receiver);
} catch (Exception e) {
// do nothing
}
}
public void onClickBackBtn(View view) {
previousEntry();
}
public void onClickForwardBtn(View view) {
nextEntry();
}
public void onClickCancelFullscreenBtn(View view) {
toggleFullScreen();
}
private class JavaScriptObject {
@Override
@JavascriptInterface
public String toString() {
return "injectedJSObject";
}
@JavascriptInterface
public void onClickOriginalText() {
runOnUiThread(new Runnable() {
@Override
public void run() {
preferFullText = false;
reload(true);
}
});
}
@JavascriptInterface
public void onClickFullText() {
if (getProgressBar().getVisibility() != View.VISIBLE) {
ContentResolver cr = getContentResolver();
Cursor entryCursor = cr.query(uri, null, null, null, null);
final boolean alreadyMobilized = entryCursor.moveToFirst() && !entryCursor.isNull(mobilizedHtmlPosition);
entryCursor.close();
if (alreadyMobilized) {
runOnUiThread(new Runnable() {
@Override
public void run() {
preferFullText = true;
reload(true);
}
});
} else {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
// since we have acquired the networkInfo, we use it for basic checks
if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
FetcherService.addEntriesToMobilize(new long[]{_id});
long mobilizingTaskId = FetcherService.getMobilizingTaskId(_id);
if (mobilizingTaskId != -1) {
cr.unregisterContentObserver(mTasksObserver);
cr.registerContentObserver(TaskColumns.CONTENT_URI(mobilizingTaskId), false, mTasksObserver);
startService(new Intent(EntryActivity.this, FetcherService.class).setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
runOnUiThread(new Runnable() {
@Override
public void run() {
getProgressBar().setVisibility(View.VISIBLE);
}
});
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(EntryActivity.this, R.string.network_error, Toast.LENGTH_LONG).show();
}
});
}
}
}
}
@JavascriptInterface
public void onClickEnclosure() {
runOnUiThread(new Runnable() {
@Override
public void run() {
final int position1 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR);
final int position2 = enclosure.indexOf(Constants.ENCLOSURE_SEPARATOR, position1 + 3);
Uri uri = Uri.parse(enclosure.substring(0, position1));
showEnclosure(uri, enclosure, position1, position2);
}
});
}
}
private final JavaScriptObject injectedJSObject = new JavaScriptObject();
}
| true | true | private void reload(boolean forceUpdate) {
long newId = Long.parseLong(uri.getLastPathSegment());
if (!forceUpdate && _id == newId) {
return;
}
_id = newId;
ContentResolver cr = getContentResolver();
Cursor entryCursor = cr.query(uri, null, null, null, null);
if (entryCursor.moveToFirst()) {
String contentText = entryCursor.getString(mobilizedHtmlPosition);
if (contentText == null || (forceUpdate && !preferFullText)) {
preferFullText = false;
contentText = entryCursor.getString(abstractPosition);
} else {
preferFullText = true;
}
if (contentText == null) {
contentText = "";
}
// Need to be done before the "mark as read" action
setupNavigationButton();
// Mark the article as read
if (entryCursor.getInt(isReadPosition) != 1) {
if (cr.update(uri, FeedData.getReadContentValues(), null, null) > 0) {
FeedDataContentProvider.notifyAllFromEntryUri(uri, false);
}
}
int _feedId = entryCursor.getInt(feedIdPosition);
if (feedId != _feedId) {
if (feedId != 0) {
iconBytes = null; // triggers re-fetch of the icon
}
feedId = _feedId;
}
title = entryCursor.getString(titlePosition);
Cursor cursor = cr.query(FeedColumns.CONTENT_URI(feedId), new String[]{FeedColumns.NAME, FeedColumns.URL}, null, null, null);
if (cursor.moveToFirst()) {
setTitle(cursor.isNull(0) ? cursor.getString(1) : cursor.getString(0));
} else { // fallback, should not be possible
setTitle(title);
}
cursor.close();
if (iconBytes == null || iconBytes.length == 0) {
Cursor iconCursor = cr.query(FeedColumns.CONTENT_URI(Integer.toString(feedId)),
new String[]{FeedColumns._ID, FeedColumns.ICON}, null, null, null);
if (iconCursor.moveToFirst()) {
iconBytes = iconCursor.getBlob(1);
}
iconCursor.close();
}
if (iconBytes != null && iconBytes.length > 0) {
int bitmapSizeInDip = UiUtils.dpToPixel(24);
Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
if (bitmap != null) {
if (bitmap.getHeight() != bitmapSizeInDip) {
bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false);
}
getActionBar().setIcon(new BitmapDrawable(getResources(), bitmap));
} else {
getActionBar().setIcon(R.drawable.icon);
}
} else {
getActionBar().setIcon(R.drawable.icon);
}
favorite = entryCursor.getInt(isFavoritePosition) == 1;
invalidateOptionsMenu();
// loadData does not recognize the encoding without correct html-header
boolean localPictures = contentText.contains(Constants.IMAGEID_REPLACEMENT);
if (localPictures) {
contentText = contentText.replace(Constants.IMAGEID_REPLACEMENT, _id + Constants.IMAGEFILE_IDSEPARATOR);
}
if (PrefUtils.getBoolean(PrefUtils.DISABLE_PICTURES, false)) {
contentText = contentText.replaceAll(HTML_IMG_REGEX, "");
webView.getSettings().setBlockNetworkImage(true);
} else {
if (webView.getSettings().getBlockNetworkImage()) {
// setBlockNetwortImage(false) calls postSync, which takes time, so we clean up the html first and change the value afterwards
webView.loadData("", TEXT_HTML, Constants.UTF8);
webView.getSettings().setBlockNetworkImage(false);
}
}
String author = entryCursor.getString(authorPosition);
long timestamp = entryCursor.getLong(datePosition);
link = entryCursor.getString(linkPosition);
enclosure = entryCursor.getString(enclosurePosition);
// String baseUrl = "";
// try {
// URL url = new URL(link);
// baseUrl = url.getProtocol() + "://" + url.getHost();
// } catch (MalformedURLException ignored) {
// }
webView.loadDataWithBaseURL(null, generateHtmlContent(title, link, contentText, enclosure, author, timestamp), TEXT_HTML, Constants.UTF8,
null);
// Listen the mobilizing task
long mobilizingTaskId = FetcherService.getMobilizingTaskId(_id);
if (mobilizingTaskId != -1) {
getProgressBar().setVisibility(View.VISIBLE);
cr.unregisterContentObserver(mTasksObserver);
cr.registerContentObserver(TaskColumns.CONTENT_URI(mobilizingTaskId), false, mTasksObserver);
} else {
getProgressBar().setVisibility(View.GONE);
cr.unregisterContentObserver(mTasksObserver);
}
}
entryCursor.close();
}
| private void reload(boolean forceUpdate) {
long newId = Long.parseLong(uri.getLastPathSegment());
if (!forceUpdate && _id == newId) {
return;
}
_id = newId;
ContentResolver cr = getContentResolver();
Cursor entryCursor = cr.query(uri, null, null, null, null);
if (entryCursor.moveToFirst()) {
String contentText = entryCursor.getString(mobilizedHtmlPosition);
if (contentText == null || (forceUpdate && !preferFullText)) {
preferFullText = false;
contentText = entryCursor.getString(abstractPosition);
} else {
preferFullText = true;
}
if (contentText == null) {
contentText = "";
}
// Need to be done before the "mark as read" action
setupNavigationButton();
// Mark the article as read
if (entryCursor.getInt(isReadPosition) != 1) {
if (cr.update(uri, FeedData.getReadContentValues(), null, null) > 0) {
FeedDataContentProvider.notifyAllFromEntryUri(uri, false);
}
}
int _feedId = entryCursor.getInt(feedIdPosition);
if (feedId != _feedId) {
if (feedId != 0) {
iconBytes = null; // triggers re-fetch of the icon
}
feedId = _feedId;
}
title = entryCursor.getString(titlePosition);
Cursor cursor = cr.query(FeedColumns.CONTENT_URI(feedId), new String[]{FeedColumns.NAME, FeedColumns.URL}, null, null, null);
if (cursor.moveToFirst()) {
setTitle(cursor.isNull(0) ? cursor.getString(1) : cursor.getString(0));
} else { // fallback, should not be possible
setTitle(title);
}
cursor.close();
if (iconBytes == null || iconBytes.length == 0) {
Cursor iconCursor = cr.query(FeedColumns.CONTENT_URI(Integer.toString(feedId)),
new String[]{FeedColumns._ID, FeedColumns.ICON}, null, null, null);
if (iconCursor.moveToFirst()) {
iconBytes = iconCursor.getBlob(1);
}
iconCursor.close();
}
if (iconBytes != null && iconBytes.length > 0) {
int bitmapSizeInDip = UiUtils.dpToPixel(24);
Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
if (bitmap != null) {
if (bitmap.getHeight() != bitmapSizeInDip) {
bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false);
}
getActionBar().setIcon(new BitmapDrawable(getResources(), bitmap));
} else {
getActionBar().setIcon(R.drawable.icon);
}
} else {
getActionBar().setIcon(R.drawable.icon);
}
favorite = entryCursor.getInt(isFavoritePosition) == 1;
invalidateOptionsMenu();
// loadData does not recognize the encoding without correct html-header
boolean localPictures = contentText.contains(Constants.IMAGEID_REPLACEMENT);
if (localPictures) {
contentText = contentText.replace(Constants.IMAGEID_REPLACEMENT, _id + Constants.IMAGEFILE_IDSEPARATOR);
}
if (PrefUtils.getBoolean(PrefUtils.DISABLE_PICTURES, false)) {
contentText = contentText.replaceAll(HTML_IMG_REGEX, "");
webView.getSettings().setBlockNetworkImage(true);
} else {
if (webView.getSettings().getBlockNetworkImage()) {
// setBlockNetwortImage(false) calls postSync, which takes time, so we clean up the html first and change the value afterwards
webView.loadData("", TEXT_HTML, Constants.UTF8);
webView.getSettings().setBlockNetworkImage(false);
}
}
String author = entryCursor.getString(authorPosition);
long timestamp = entryCursor.getLong(datePosition);
link = entryCursor.getString(linkPosition);
enclosure = entryCursor.getString(enclosurePosition);
// String baseUrl = "";
// try {
// URL url = new URL(link);
// baseUrl = url.getProtocol() + "://" + url.getHost();
// } catch (MalformedURLException ignored) {
// }
webView.loadDataWithBaseURL("", generateHtmlContent(title, link, contentText, enclosure, author, timestamp), TEXT_HTML, Constants.UTF8,
null); // do not put 'null' to the base url...
// Listen the mobilizing task
long mobilizingTaskId = FetcherService.getMobilizingTaskId(_id);
if (mobilizingTaskId != -1) {
getProgressBar().setVisibility(View.VISIBLE);
cr.unregisterContentObserver(mTasksObserver);
cr.registerContentObserver(TaskColumns.CONTENT_URI(mobilizingTaskId), false, mTasksObserver);
} else {
getProgressBar().setVisibility(View.GONE);
cr.unregisterContentObserver(mTasksObserver);
}
}
entryCursor.close();
}
|
diff --git a/src/com/liato/bankdroid/LockableActivity.java b/src/com/liato/bankdroid/LockableActivity.java
index 5facf11..673b928 100644
--- a/src/com/liato/bankdroid/LockableActivity.java
+++ b/src/com/liato/bankdroid/LockableActivity.java
@@ -1,149 +1,153 @@
/*
* Copyright (C) 2010 Nullbyte <http://nullbyte.eu>
*
* 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.liato.bankdroid;
import com.liato.bankdroid.lockpattern.ConfirmLockPattern;
import com.liato.bankdroid.lockpattern.LockPatternUtils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class LockableActivity extends Activity {
private static int PATTERNLOCK_UNLOCK = 42;
private SharedPreferences prefs;
private Editor editor;
private LockPatternUtils mLockPatternUtils;
private LinearLayout mTitlebarButtons;
private LayoutInflater mInflater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
mLockPatternUtils = new LockPatternUtils(this);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
}
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
View titlebar = findViewById(R.id.layTitle);
mTitlebarButtons = (LinearLayout)titlebar.findViewById(R.id.layTitleButtons);
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView homeButton = (ImageView)titlebar.findViewById(R.id.imgTitle);
+ View homeButtonCont = titlebar.findViewById(R.id.layLogoContainer);
OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(LockableActivity.this, MainActivity.class);
startActivity(intent);
}
- };
+ };
homeButton.setOnClickListener(listener);
homeButton.setFocusable(true);
homeButton.setClickable(true);
+ homeButtonCont.setOnClickListener(listener);
+ homeButtonCont.setFocusable(true);
+ homeButtonCont.setClickable(true);
}
protected void addTitleButton(int imageResourceId, String tag, OnClickListener listener) {
View child = mInflater.inflate(R.layout.title_item, mTitlebarButtons, false);
ImageButton button = (ImageButton)child.findViewById(R.id.imgItemIcon);
button.setImageResource(imageResourceId);
button.setTag(tag);
child.setTag("item_"+tag);
button.setOnClickListener(listener);
mTitlebarButtons.addView(child);
}
protected void hideTitleButton(String tag) {
View v = mTitlebarButtons.findViewWithTag("item_"+tag);
if (v != null) {
v.setVisibility(View.GONE);
}
}
protected void showTitleButton(String tag) {
View v = mTitlebarButtons.findViewWithTag("item_"+tag);
if (v != null) {
v.setVisibility(View.VISIBLE);
}
}
@Override
protected void onPause() {
super.onPause();
// Don't do anything if not lock pattern is set
if (!mLockPatternUtils.isLockPatternEnabled()) return;
// Save the current time If a lock pattern has been set
writeLockTime();
}
@Override
protected void onResume() {
super.onResume();
// Don't do anything if not lock pattern is set
if (!mLockPatternUtils.isLockPatternEnabled()) {
return;
}
// If a lock pattern is set we need to check the time for when the last
// activity was open. If it's been more than two seconds the user
// will have to enter the lock pattern to continue.
long currentTime = System.currentTimeMillis();
long lockedAt = prefs.getLong("locked_at", currentTime-10000);
long timedif = currentTime - lockedAt;
if (timedif > 2000) {
launchPatternLock();
}
}
private void launchPatternLock() {
Intent intent = new Intent(this, ConfirmLockPattern.class);
intent.putExtra(ConfirmLockPattern.DISABLE_BACK_KEY, true);
intent.putExtra(ConfirmLockPattern.HEADER_TEXT, getText(R.string.patternlock_header));
startActivityForResult(intent, PATTERNLOCK_UNLOCK);
}
private void writeLockTime() {
editor = prefs.edit();
editor.putLong("locked_at", System.currentTimeMillis());
editor.commit();
}
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == PATTERNLOCK_UNLOCK) {
if (resultCode == RESULT_OK) {
writeLockTime();
}
else {
launchPatternLock();
}
}
}
}
| false | true | public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
View titlebar = findViewById(R.id.layTitle);
mTitlebarButtons = (LinearLayout)titlebar.findViewById(R.id.layTitleButtons);
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView homeButton = (ImageView)titlebar.findViewById(R.id.imgTitle);
OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(LockableActivity.this, MainActivity.class);
startActivity(intent);
}
};
homeButton.setOnClickListener(listener);
homeButton.setFocusable(true);
homeButton.setClickable(true);
}
| public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
View titlebar = findViewById(R.id.layTitle);
mTitlebarButtons = (LinearLayout)titlebar.findViewById(R.id.layTitleButtons);
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView homeButton = (ImageView)titlebar.findViewById(R.id.imgTitle);
View homeButtonCont = titlebar.findViewById(R.id.layLogoContainer);
OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(LockableActivity.this, MainActivity.class);
startActivity(intent);
}
};
homeButton.setOnClickListener(listener);
homeButton.setFocusable(true);
homeButton.setClickable(true);
homeButtonCont.setOnClickListener(listener);
homeButtonCont.setFocusable(true);
homeButtonCont.setClickable(true);
}
|
diff --git a/src/de/lycake/CakeHomePlugin/HomeCommandExecutor.java b/src/de/lycake/CakeHomePlugin/HomeCommandExecutor.java
index 52b8355..4c812fd 100644
--- a/src/de/lycake/CakeHomePlugin/HomeCommandExecutor.java
+++ b/src/de/lycake/CakeHomePlugin/HomeCommandExecutor.java
@@ -1,65 +1,69 @@
package de.lycake.CakeHomePlugin;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class HomeCommandExecutor implements CommandExecutor{
CakeHomePlugin plugin_;
public HashMap<Player, Location> homes_;
public HomeCommandExecutor(CakeHomePlugin plugin){
plugin_ = plugin;
homes_ = plugin.homes_;
}
/**
* Will execute when a player types a command
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
Player player;
+ Location loc;
// Home
if (cmd.getName().equalsIgnoreCase("home") && sender instanceof Player){
if (args.length == 0){
player = (Player) sender;
if (!homes_.containsKey(player)){
player.sendMessage("You have never set your home");
return false;
}
- Location loc = homes_.get(player);
+ loc = homes_.get(player);
+ loc.setY(Math.ceil(loc.getY()));
player.teleport(loc);
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("set")){
player = (Player) sender;
- homes_.put(player, player.getLocation());
+ loc = player.getLocation();
+ loc.setY(Math.ceil(loc.getY()));
+ homes_.put(player, loc);
saveHomes();
}
}
return false;
}
/**
* Saves the homes to file
*/
public void saveHomes(){
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("homes.cak"));
oos.writeObject(homes_);
oos.flush();
oos.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
Player player;
// Home
if (cmd.getName().equalsIgnoreCase("home") && sender instanceof Player){
if (args.length == 0){
player = (Player) sender;
if (!homes_.containsKey(player)){
player.sendMessage("You have never set your home");
return false;
}
Location loc = homes_.get(player);
player.teleport(loc);
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("set")){
player = (Player) sender;
homes_.put(player, player.getLocation());
saveHomes();
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
Player player;
Location loc;
// Home
if (cmd.getName().equalsIgnoreCase("home") && sender instanceof Player){
if (args.length == 0){
player = (Player) sender;
if (!homes_.containsKey(player)){
player.sendMessage("You have never set your home");
return false;
}
loc = homes_.get(player);
loc.setY(Math.ceil(loc.getY()));
player.teleport(loc);
return true;
} else if (args.length > 1 && args[0].equalsIgnoreCase("set")){
player = (Player) sender;
loc = player.getLocation();
loc.setY(Math.ceil(loc.getY()));
homes_.put(player, loc);
saveHomes();
}
}
return false;
}
|
diff --git a/src/com/android/gallery3d/filtershow/filters/ImageFilterRedEye.java b/src/com/android/gallery3d/filtershow/filters/ImageFilterRedEye.java
index c990c1870..00a18091b 100644
--- a/src/com/android/gallery3d/filtershow/filters/ImageFilterRedEye.java
+++ b/src/com/android/gallery3d/filtershow/filters/ImageFilterRedEye.java
@@ -1,42 +1,43 @@
package com.android.gallery3d.filtershow.filters;
import android.graphics.Bitmap;
import android.util.Log;
import java.util.Arrays;
public class ImageFilterRedEye extends ImageFilter {
private static final String TAG = "ImageFilterRedEye";
public ImageFilterRedEye() {
mName = "Redeye";
}
@Override
public ImageFilter clone() throws CloneNotSupportedException {
ImageFilterRedEye filter = (ImageFilterRedEye) super.clone();
return filter;
}
native protected void nativeApplyFilter(Bitmap bitmap, int w, int h, short []matrix);
- public void apply(Bitmap bitmap) {
+ public Bitmap apply(Bitmap bitmap, float scaleFactor, boolean highQuality) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
float p = mParameter;
float value = p;
int box = Math.min(w, h);
int sizex = Math.min((int)((p+100)*box/400),w/2);
int sizey = Math.min((int)((p+100)*box/800),h/2);
short [] rect = new short[]{
(short) (w/2-sizex),(short) (w/2-sizey),
(short) (2*sizex),(short) (2*sizey)};
nativeApplyFilter(bitmap, w, h, rect);
+ return bitmap;
}
}
| false | true | public void apply(Bitmap bitmap) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
float p = mParameter;
float value = p;
int box = Math.min(w, h);
int sizex = Math.min((int)((p+100)*box/400),w/2);
int sizey = Math.min((int)((p+100)*box/800),h/2);
short [] rect = new short[]{
(short) (w/2-sizex),(short) (w/2-sizey),
(short) (2*sizex),(short) (2*sizey)};
nativeApplyFilter(bitmap, w, h, rect);
}
| public Bitmap apply(Bitmap bitmap, float scaleFactor, boolean highQuality) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
float p = mParameter;
float value = p;
int box = Math.min(w, h);
int sizex = Math.min((int)((p+100)*box/400),w/2);
int sizey = Math.min((int)((p+100)*box/800),h/2);
short [] rect = new short[]{
(short) (w/2-sizex),(short) (w/2-sizey),
(short) (2*sizex),(short) (2*sizey)};
nativeApplyFilter(bitmap, w, h, rect);
return bitmap;
}
|
diff --git a/WEB-INF/src/edu/wustl/catissuecore/action/ConfigureSimpleQueryAction.java b/WEB-INF/src/edu/wustl/catissuecore/action/ConfigureSimpleQueryAction.java
index 1f6048f2e..3d4005c51 100644
--- a/WEB-INF/src/edu/wustl/catissuecore/action/ConfigureSimpleQueryAction.java
+++ b/WEB-INF/src/edu/wustl/catissuecore/action/ConfigureSimpleQueryAction.java
@@ -1,119 +1,123 @@
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.common.actionForm.SimpleQueryInterfaceForm;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.common.bizlogic.QueryBizLogic;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.action.BaseAction;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.util.MapDataParser;
import edu.wustl.common.util.logger.Logger;
public class ConfigureSimpleQueryAction extends BaseAction
{
/**
* This is the initialization action class for configuring Simple Search
* @author Poornima Govindrao
*
*/
protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
//Set the tables for the configuration
String pageOf=request.getParameter(Constants.PAGEOF);
if(pageOf.equals(Constants.PAGEOF_SIMPLE_QUERY_INTERFACE))
{
SimpleQueryInterfaceForm simpleQueryInterfaceForm = (SimpleQueryInterfaceForm)form;
HttpSession session =request.getSession();
Map map = simpleQueryInterfaceForm.getValuesMap();
Logger.out.debug("Form map size"+map.size());
Logger.out.debug("Form map"+map);
if(map.size()==0)
{
map=(Map)session.getAttribute(Constants.SIMPLE_QUERY_MAP);
Logger.out.debug("Session map size"+map.size());
Logger.out.debug("Session map"+map);
}
Iterator iterator = map.keySet().iterator();
//Retrieve the size of the condition list to set size of array of tables.
MapDataParser parser = new MapDataParser("edu.wustl.common.query");
Collection simpleConditionNodeCollection = parser.generateData(map, true);
int counter = simpleConditionNodeCollection.size();
String[] selectedTables = new String[counter];
int tableCount=0;
while (iterator.hasNext())
{
String key = (String)iterator.next();
Logger.out.debug("map key"+key);
if(key.endsWith("_table"))
{
String table = (String)map.get(key);
boolean exists = false;
for(int arrayCount=0;arrayCount<selectedTables.length;arrayCount++)
{
if(selectedTables[arrayCount]!=null)
{
if(selectedTables[arrayCount].equals(table))
exists = true;
}
}
if(!exists)
{
selectedTables[tableCount]= table;
tableCount++;
}
}
}
//Set the selected columns for population in the list of ConfigureResultView.jsp
String[] selectedColumns = simpleQueryInterfaceForm.getSelectedColumnNames();
if(selectedColumns==null)
{
selectedColumns = (String[])session.getAttribute(Constants.CONFIGURED_SELECT_COLUMN_LIST);
if(selectedColumns==null)
{
QueryBizLogic bizLogic = (QueryBizLogic) BizLogicFactory
.getBizLogic(Constants.SIMPLE_QUERY_INTERFACE_ID);
List columnNameValueBeans = new ArrayList();
int i;
for(i=0;i<selectedTables.length;i++)
{
columnNameValueBeans.addAll(bizLogic.setColumnNames(selectedTables[i]));
}
selectedColumns = new String[columnNameValueBeans.size()];
Iterator columnNameValueBeansItr = columnNameValueBeans.iterator();
i=0;
while(columnNameValueBeansItr.hasNext())
{
selectedColumns[i]=((NameValueBean)columnNameValueBeansItr.next()).getValue();
i++;
}
}
simpleQueryInterfaceForm.setSelectedColumnNames(selectedColumns);
}
session.setAttribute(Constants.TABLE_ALIAS_NAME,selectedTables);
+ //session.setAttribute(Constants.SIMPLE_QUERY_COUNTER,new String(""+counter));
+ //Logger.out.debug("counter in configure"+(String)session.getAttribute(Constants.SIMPLE_QUERY_COUNTER));
+ //Counter required for redefining the query
+ map.put("counter",new String(""+counter));
session.setAttribute(Constants.SIMPLE_QUERY_MAP,map);
}
request.setAttribute(Constants.PAGEOF,pageOf);
return (mapping.findForward(pageOf));
}
}
| true | true | protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
//Set the tables for the configuration
String pageOf=request.getParameter(Constants.PAGEOF);
if(pageOf.equals(Constants.PAGEOF_SIMPLE_QUERY_INTERFACE))
{
SimpleQueryInterfaceForm simpleQueryInterfaceForm = (SimpleQueryInterfaceForm)form;
HttpSession session =request.getSession();
Map map = simpleQueryInterfaceForm.getValuesMap();
Logger.out.debug("Form map size"+map.size());
Logger.out.debug("Form map"+map);
if(map.size()==0)
{
map=(Map)session.getAttribute(Constants.SIMPLE_QUERY_MAP);
Logger.out.debug("Session map size"+map.size());
Logger.out.debug("Session map"+map);
}
Iterator iterator = map.keySet().iterator();
//Retrieve the size of the condition list to set size of array of tables.
MapDataParser parser = new MapDataParser("edu.wustl.common.query");
Collection simpleConditionNodeCollection = parser.generateData(map, true);
int counter = simpleConditionNodeCollection.size();
String[] selectedTables = new String[counter];
int tableCount=0;
while (iterator.hasNext())
{
String key = (String)iterator.next();
Logger.out.debug("map key"+key);
if(key.endsWith("_table"))
{
String table = (String)map.get(key);
boolean exists = false;
for(int arrayCount=0;arrayCount<selectedTables.length;arrayCount++)
{
if(selectedTables[arrayCount]!=null)
{
if(selectedTables[arrayCount].equals(table))
exists = true;
}
}
if(!exists)
{
selectedTables[tableCount]= table;
tableCount++;
}
}
}
//Set the selected columns for population in the list of ConfigureResultView.jsp
String[] selectedColumns = simpleQueryInterfaceForm.getSelectedColumnNames();
if(selectedColumns==null)
{
selectedColumns = (String[])session.getAttribute(Constants.CONFIGURED_SELECT_COLUMN_LIST);
if(selectedColumns==null)
{
QueryBizLogic bizLogic = (QueryBizLogic) BizLogicFactory
.getBizLogic(Constants.SIMPLE_QUERY_INTERFACE_ID);
List columnNameValueBeans = new ArrayList();
int i;
for(i=0;i<selectedTables.length;i++)
{
columnNameValueBeans.addAll(bizLogic.setColumnNames(selectedTables[i]));
}
selectedColumns = new String[columnNameValueBeans.size()];
Iterator columnNameValueBeansItr = columnNameValueBeans.iterator();
i=0;
while(columnNameValueBeansItr.hasNext())
{
selectedColumns[i]=((NameValueBean)columnNameValueBeansItr.next()).getValue();
i++;
}
}
simpleQueryInterfaceForm.setSelectedColumnNames(selectedColumns);
}
session.setAttribute(Constants.TABLE_ALIAS_NAME,selectedTables);
session.setAttribute(Constants.SIMPLE_QUERY_MAP,map);
}
request.setAttribute(Constants.PAGEOF,pageOf);
return (mapping.findForward(pageOf));
}
| protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
//Set the tables for the configuration
String pageOf=request.getParameter(Constants.PAGEOF);
if(pageOf.equals(Constants.PAGEOF_SIMPLE_QUERY_INTERFACE))
{
SimpleQueryInterfaceForm simpleQueryInterfaceForm = (SimpleQueryInterfaceForm)form;
HttpSession session =request.getSession();
Map map = simpleQueryInterfaceForm.getValuesMap();
Logger.out.debug("Form map size"+map.size());
Logger.out.debug("Form map"+map);
if(map.size()==0)
{
map=(Map)session.getAttribute(Constants.SIMPLE_QUERY_MAP);
Logger.out.debug("Session map size"+map.size());
Logger.out.debug("Session map"+map);
}
Iterator iterator = map.keySet().iterator();
//Retrieve the size of the condition list to set size of array of tables.
MapDataParser parser = new MapDataParser("edu.wustl.common.query");
Collection simpleConditionNodeCollection = parser.generateData(map, true);
int counter = simpleConditionNodeCollection.size();
String[] selectedTables = new String[counter];
int tableCount=0;
while (iterator.hasNext())
{
String key = (String)iterator.next();
Logger.out.debug("map key"+key);
if(key.endsWith("_table"))
{
String table = (String)map.get(key);
boolean exists = false;
for(int arrayCount=0;arrayCount<selectedTables.length;arrayCount++)
{
if(selectedTables[arrayCount]!=null)
{
if(selectedTables[arrayCount].equals(table))
exists = true;
}
}
if(!exists)
{
selectedTables[tableCount]= table;
tableCount++;
}
}
}
//Set the selected columns for population in the list of ConfigureResultView.jsp
String[] selectedColumns = simpleQueryInterfaceForm.getSelectedColumnNames();
if(selectedColumns==null)
{
selectedColumns = (String[])session.getAttribute(Constants.CONFIGURED_SELECT_COLUMN_LIST);
if(selectedColumns==null)
{
QueryBizLogic bizLogic = (QueryBizLogic) BizLogicFactory
.getBizLogic(Constants.SIMPLE_QUERY_INTERFACE_ID);
List columnNameValueBeans = new ArrayList();
int i;
for(i=0;i<selectedTables.length;i++)
{
columnNameValueBeans.addAll(bizLogic.setColumnNames(selectedTables[i]));
}
selectedColumns = new String[columnNameValueBeans.size()];
Iterator columnNameValueBeansItr = columnNameValueBeans.iterator();
i=0;
while(columnNameValueBeansItr.hasNext())
{
selectedColumns[i]=((NameValueBean)columnNameValueBeansItr.next()).getValue();
i++;
}
}
simpleQueryInterfaceForm.setSelectedColumnNames(selectedColumns);
}
session.setAttribute(Constants.TABLE_ALIAS_NAME,selectedTables);
//session.setAttribute(Constants.SIMPLE_QUERY_COUNTER,new String(""+counter));
//Logger.out.debug("counter in configure"+(String)session.getAttribute(Constants.SIMPLE_QUERY_COUNTER));
//Counter required for redefining the query
map.put("counter",new String(""+counter));
session.setAttribute(Constants.SIMPLE_QUERY_MAP,map);
}
request.setAttribute(Constants.PAGEOF,pageOf);
return (mapping.findForward(pageOf));
}
|
diff --git a/src/org/netbeans/gradle/project/tasks/GradleTasks.java b/src/org/netbeans/gradle/project/tasks/GradleTasks.java
index d9073dd3..0cb23559 100644
--- a/src/org/netbeans/gradle/project/tasks/GradleTasks.java
+++ b/src/org/netbeans/gradle/project/tasks/GradleTasks.java
@@ -1,485 +1,487 @@
package org.netbeans.gradle.project.tasks;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.gradle.tooling.BuildLauncher;
import org.gradle.tooling.GradleConnector;
import org.gradle.tooling.ProgressEvent;
import org.gradle.tooling.ProgressListener;
import org.gradle.tooling.ProjectConnection;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.gradle.project.NbGradleProject;
import org.netbeans.gradle.project.NbStrings;
import org.netbeans.gradle.project.model.GradleModelLoader;
import org.netbeans.gradle.project.output.BuildErrorConsumer;
import org.netbeans.gradle.project.output.FileLineConsumer;
import org.netbeans.gradle.project.output.InputOutputManager;
import org.netbeans.gradle.project.output.InputOutputManager.IORef;
import org.netbeans.gradle.project.output.LineEndUrlConsumer;
import org.netbeans.gradle.project.output.LineOutputWriter;
import org.netbeans.gradle.project.output.SmartOutputHandler;
import org.netbeans.gradle.project.output.StackTraceConsumer;
import org.netbeans.gradle.project.properties.GlobalGradleSettings;
import org.openide.LifecycleManager;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.RequestProcessor;
import org.openide.windows.OutputWriter;
public final class GradleTasks {
private static final RequestProcessor TASK_EXECUTOR
= new RequestProcessor("Gradle-Task-Executor", 10, true);
private static final Logger LOGGER = Logger.getLogger(GradleTasks.class.getName());
private static File getJavaHome() {
FileObject jdkHomeObj = GlobalGradleSettings.getCurrentGradleJdkHome();
return jdkHomeObj != null ? FileUtil.toFile(jdkHomeObj) : null;
}
private static void printCommand(OutputWriter buildOutput, String command, GradleTaskDef taskDef) {
buildOutput.println(NbStrings.getExecutingTaskMessage(command));
if (!taskDef.getArguments().isEmpty()) {
buildOutput.println(NbStrings.getTaskArgumentsMessage(taskDef.getArguments()));
}
if (!taskDef.getJvmArguments().isEmpty()) {
buildOutput.println(NbStrings.getTaskJvmArgumentsMessage(taskDef.getJvmArguments()));
}
buildOutput.println();
}
private static void configureBuildLauncher(BuildLauncher buildLauncher, GradleTaskDef taskDef, final ProgressHandle progress) {
File javaHome = getJavaHome();
if (javaHome != null) {
buildLauncher.setJavaHome(javaHome);
}
if (!taskDef.getJvmArguments().isEmpty()) {
buildLauncher.setJvmArguments(taskDef.getJvmArgumentsArray());
}
if (!taskDef.getArguments().isEmpty()) {
buildLauncher.withArguments(taskDef.getArgumentArray());
}
buildLauncher.addProgressListener(new ProgressListener() {
@Override
public void statusChanged(ProgressEvent pe) {
progress.progress(pe.getDescription());
}
});
buildLauncher.forTasks(taskDef.getTaskNamesArray());
}
private static OutputRef configureOutput(
NbGradleProject project,
GradleTaskDef taskDef,
BuildLauncher buildLauncher,
OutputWriter buildOutput,
OutputWriter buildErrOutput) {
List<SmartOutputHandler.Consumer> consumers = new LinkedList<SmartOutputHandler.Consumer>();
consumers.add(new StackTraceConsumer(project));
consumers.add(new LineEndUrlConsumer());
List<SmartOutputHandler.Consumer> outputConsumers = new LinkedList<SmartOutputHandler.Consumer>();
outputConsumers.addAll(consumers);
List<SmartOutputHandler.Consumer> errorConsumers = new LinkedList<SmartOutputHandler.Consumer>();
errorConsumers.add(new BuildErrorConsumer());
errorConsumers.addAll(consumers);
errorConsumers.add(new FileLineConsumer());
Writer forwardedStdOut = new LineOutputWriter(new SmartOutputHandler(
buildOutput,
Arrays.asList(taskDef.getStdOutListener()),
outputConsumers));
Writer forwardedStdErr = new LineOutputWriter(new SmartOutputHandler(
buildErrOutput,
Arrays.asList(taskDef.getStdErrListener()),
errorConsumers));
buildLauncher.setStandardOutput(new WriterOutputStream(forwardedStdOut));
buildLauncher.setStandardError(new WriterOutputStream(forwardedStdErr));
return new OutputRef(forwardedStdOut, forwardedStdErr);
}
private static void doGradleTasksWithProgress(
final ProgressHandle progress,
NbGradleProject project,
GradleTaskDef taskDef) {
StringBuilder commandBuilder = new StringBuilder(128);
commandBuilder.append("gradle");
for (String task : taskDef.getTaskNames()) {
commandBuilder.append(' ');
commandBuilder.append(task);
}
String command = commandBuilder.toString();
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.log(Level.INFO, "Executing: {0}, Args = {1}, JvmArg = {2}",
new Object[]{command, taskDef.getArguments(), taskDef.getJvmArguments()});
}
FileObject projectDir = project.getProjectDirectory();
GradleConnector gradleConnector = GradleModelLoader.createGradleConnector();
gradleConnector.forProjectDirectory(FileUtil.toFile(projectDir));
ProjectConnection projectConnection = null;
try {
projectConnection = gradleConnector.connect();
BuildLauncher buildLauncher = projectConnection.newBuild();
configureBuildLauncher(buildLauncher, taskDef, progress);
IORef ioRef = InputOutputManager.getInputOutput(
taskDef.getCaption(),
taskDef.isReuseOutput(),
taskDef.isCleanOutput());
try {
OutputWriter buildOutput = ioRef.getIo().getOut();
try {
OutputWriter buildErrOutput = ioRef.getIo().getErr();
try {
if (taskDef.isCleanOutput()) {
buildOutput.reset();
- buildErrOutput.reset();
+ // There is no need to reset buildErrOutput,
+ // at least this is what NetBeans tells you in its
+ // logs if you do.
}
printCommand(buildOutput, command, taskDef);
OutputRef outputRef = configureOutput(
project, taskDef, buildLauncher, buildOutput, buildErrOutput);
try {
ioRef.getIo().select();
buildLauncher.run();
} finally {
// This close method will only forward the last lines
// if they were not terminated with a line separator.
outputRef.close();
}
} catch (Throwable ex) {
LOGGER.log(
ex instanceof Exception ? Level.INFO : Level.SEVERE,
"Gradle build failure: " + command,
ex);
String buildFailureMessage = NbStrings.getBuildFailure(command);
buildErrOutput.println();
buildErrOutput.println(buildFailureMessage);
project.displayError(buildFailureMessage, ex, false);
} finally {
buildErrOutput.close();
}
} finally {
buildOutput.close();
}
} finally {
ioRef.close();
}
} finally {
if (projectConnection != null) {
projectConnection.close();
}
}
}
private static void preSubmitGradleTask() {
LifecycleManager.getDefault().saveAll();
}
private static void submitGradleTask(
final NbGradleProject project,
final Callable<GradleTaskDef> taskDefFactory) {
preSubmitGradleTask();
Callable<DaemonTaskDef> daemonTaskDefFactory = new Callable<DaemonTaskDef>() {
@Override
public DaemonTaskDef call() throws Exception {
GradleTaskDef taskDef = taskDefFactory.call();
if (taskDef == null) {
return null;
}
List<String> globalJvmArgs = GlobalGradleSettings.getGradleJvmArgs().getValue();
final GradleTaskDef newTaskDef;
if (globalJvmArgs != null && !globalJvmArgs.isEmpty()) {
GradleTaskDef.Builder builder = new GradleTaskDef.Builder(taskDef);
List<String> combinedJvmArgs = new ArrayList<String>(
taskDef.getJvmArguments().size() + globalJvmArgs.size());
combinedJvmArgs.addAll(taskDef.getJvmArguments());
combinedJvmArgs.addAll(globalJvmArgs);
builder.setJvmArguments(combinedJvmArgs);
newTaskDef = builder.create();
}
else {
newTaskDef = taskDef;
}
String caption = NbStrings.getExecuteTasksText(newTaskDef.getTaskNames());
boolean nonBlocking = newTaskDef.isNonBlocking();
return new DaemonTaskDef(caption, nonBlocking, new DaemonTask() {
@Override
public void run(ProgressHandle progress) {
doGradleTasksWithProgress(progress, project, newTaskDef);
}
});
}
};
GradleDaemonManager.submitGradleTask(TASK_EXECUTOR, daemonTaskDefFactory);
}
public static Runnable createAsyncGradleTask(NbGradleProject project, final GradleTaskDef taskDef) {
if (taskDef == null) throw new NullPointerException("taskDef");
return createAsyncGradleTask(project, new Callable<GradleTaskDef>() {
@Override
public GradleTaskDef call() {
return taskDef;
}
});
}
public static Runnable createAsyncGradleTask(NbGradleProject project, Callable<GradleTaskDef> taskDefFactory) {
return new AsyncGradleTask(project, taskDefFactory);
}
private static class AsyncGradleTask implements Runnable {
private final NbGradleProject project;
private final Callable<GradleTaskDef> taskDefFactroy;
public AsyncGradleTask(NbGradleProject project, Callable<GradleTaskDef> taskDefFactroy) {
if (project == null) throw new NullPointerException("project");
if (taskDefFactroy == null) throw new NullPointerException("taskDefFactroy");
this.project = project;
this.taskDefFactroy = taskDefFactroy;
}
@Override
public void run() {
submitGradleTask(project, taskDefFactroy);
}
}
private static class ReaderInputStream extends InputStream {
private final Reader reader;
private final Charset encoding;
private final AtomicReference<byte[]> cacheRef;
public ReaderInputStream(Reader reader) {
this(reader, Charset.defaultCharset());
}
public ReaderInputStream(Reader reader, Charset encoding) {
if (reader == null) throw new NullPointerException("reader");
if (encoding == null) throw new NullPointerException("encoding");
this.reader = reader;
this.encoding = encoding;
this.cacheRef = new AtomicReference<byte[]>(new byte[0]);
}
private int readFromCache(byte[] b, int offset, int length) {
byte[] cache;
byte[] newCache;
int toRead;
do {
cache = cacheRef.get();
toRead = Math.min(cache.length, length);
System.arraycopy(cache, 0, b, offset, toRead);
newCache = new byte[cache.length - toRead];
System.arraycopy(cache, toRead, newCache, 0, newCache.length);
} while (!cacheRef.compareAndSet(cache, newCache));
return toRead;
}
private boolean readToCache(int requiredBytes) throws IOException {
assert requiredBytes > 0;
// We rely on the encoder to choose the number of bytes to read but
// it does not have to be actually accurate, it only matters
// performance wise but this is not a performance critical code.
CharsetEncoder encoder = encoding.newEncoder();
int toRead = (int)((float)requiredBytes / encoder.averageBytesPerChar()) + 1;
toRead = Math.max(toRead, requiredBytes);
char[] readChars = new char[toRead];
int readCount = reader.read(readChars);
if (readCount <= 0) {
// readCount should never be zero but if reader returns zero
// regardless, assume that it believes that EOF has been
// reached.
return false;
}
ByteBuffer encodedBuffer = encoder.encode(CharBuffer.wrap(readChars, 0, readCount));
byte[] encoded = new byte[encodedBuffer.remaining()];
encodedBuffer.get(encoded);
byte[] oldCache;
byte[] newCache;
do {
oldCache = cacheRef.get();
newCache = new byte[oldCache.length + encoded.length];
System.arraycopy(oldCache, 0, newCache, 0, oldCache.length);
System.arraycopy(encoded, 0, newCache, oldCache.length, encoded.length);
} while (!cacheRef.compareAndSet(oldCache, newCache));
return true;
}
@Override
public int read() throws IOException {
byte[] result = new byte[1];
if (read(result) <= 0) {
// Althouth the above read should never return zero.
return -1;
}
else {
return ((int)result[0] & 0xFF);
}
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
// Note that while this method is implemented to be thread-safe
// calling it concurrently is unadvised, since read is not atomic.
if (b == null) {
throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
int currentOffset = off;
int currentLength = len;
int readCount = 0;
do {
int currentRead = readFromCache(b, currentOffset, currentLength);
readCount += currentRead;
currentOffset += currentRead;
currentLength -= currentRead;
if (readCount > 0) {
return readCount;
}
} while (readToCache(currentLength));
return readCount > 0 ? readCount : -1;
}
@Override
public void close() throws IOException {
reader.close();
}
@Override
public void mark(int readlimit) {
}
@Override
public void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
@Override
public boolean markSupported() {
return false;
}
}
private static class WriterOutputStream extends OutputStream {
private final Writer writer;
private final Charset encoding;
public WriterOutputStream(Writer writer, Charset encoding) {
if (writer == null) throw new NullPointerException("writer");
if (encoding == null) throw new NullPointerException("encoding");
this.writer = writer;
this.encoding = encoding;
}
public WriterOutputStream(Writer writer) {
this(writer, Charset.defaultCharset());
}
@Override
public void close() throws IOException {
writer.close();
}
@Override
public void flush() throws IOException {
writer.flush();
}
@Override
public void write(byte[] b) throws IOException {
writer.write(new String(b, encoding));
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
writer.write(new String(b, off, len, encoding));
}
@Override
public void write(int b) throws IOException {
write(new byte[]{(byte)b});
}
}
private static class OutputRef implements Closeable {
private final Writer[] writers;
public OutputRef(Writer... writers) {
this.writers = writers.clone();
for (Writer writer: this.writers) {
if (writer == null) throw new NullPointerException("writer");
}
}
@Override
public void close() throws IOException {
for (Writer writer: writers) {
writer.close();
}
}
}
private GradleTasks() {
throw new AssertionError();
}
}
| true | true | private static void doGradleTasksWithProgress(
final ProgressHandle progress,
NbGradleProject project,
GradleTaskDef taskDef) {
StringBuilder commandBuilder = new StringBuilder(128);
commandBuilder.append("gradle");
for (String task : taskDef.getTaskNames()) {
commandBuilder.append(' ');
commandBuilder.append(task);
}
String command = commandBuilder.toString();
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.log(Level.INFO, "Executing: {0}, Args = {1}, JvmArg = {2}",
new Object[]{command, taskDef.getArguments(), taskDef.getJvmArguments()});
}
FileObject projectDir = project.getProjectDirectory();
GradleConnector gradleConnector = GradleModelLoader.createGradleConnector();
gradleConnector.forProjectDirectory(FileUtil.toFile(projectDir));
ProjectConnection projectConnection = null;
try {
projectConnection = gradleConnector.connect();
BuildLauncher buildLauncher = projectConnection.newBuild();
configureBuildLauncher(buildLauncher, taskDef, progress);
IORef ioRef = InputOutputManager.getInputOutput(
taskDef.getCaption(),
taskDef.isReuseOutput(),
taskDef.isCleanOutput());
try {
OutputWriter buildOutput = ioRef.getIo().getOut();
try {
OutputWriter buildErrOutput = ioRef.getIo().getErr();
try {
if (taskDef.isCleanOutput()) {
buildOutput.reset();
buildErrOutput.reset();
}
printCommand(buildOutput, command, taskDef);
OutputRef outputRef = configureOutput(
project, taskDef, buildLauncher, buildOutput, buildErrOutput);
try {
ioRef.getIo().select();
buildLauncher.run();
} finally {
// This close method will only forward the last lines
// if they were not terminated with a line separator.
outputRef.close();
}
} catch (Throwable ex) {
LOGGER.log(
ex instanceof Exception ? Level.INFO : Level.SEVERE,
"Gradle build failure: " + command,
ex);
String buildFailureMessage = NbStrings.getBuildFailure(command);
buildErrOutput.println();
buildErrOutput.println(buildFailureMessage);
project.displayError(buildFailureMessage, ex, false);
} finally {
buildErrOutput.close();
}
} finally {
buildOutput.close();
}
} finally {
ioRef.close();
}
} finally {
if (projectConnection != null) {
projectConnection.close();
}
}
}
| private static void doGradleTasksWithProgress(
final ProgressHandle progress,
NbGradleProject project,
GradleTaskDef taskDef) {
StringBuilder commandBuilder = new StringBuilder(128);
commandBuilder.append("gradle");
for (String task : taskDef.getTaskNames()) {
commandBuilder.append(' ');
commandBuilder.append(task);
}
String command = commandBuilder.toString();
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.log(Level.INFO, "Executing: {0}, Args = {1}, JvmArg = {2}",
new Object[]{command, taskDef.getArguments(), taskDef.getJvmArguments()});
}
FileObject projectDir = project.getProjectDirectory();
GradleConnector gradleConnector = GradleModelLoader.createGradleConnector();
gradleConnector.forProjectDirectory(FileUtil.toFile(projectDir));
ProjectConnection projectConnection = null;
try {
projectConnection = gradleConnector.connect();
BuildLauncher buildLauncher = projectConnection.newBuild();
configureBuildLauncher(buildLauncher, taskDef, progress);
IORef ioRef = InputOutputManager.getInputOutput(
taskDef.getCaption(),
taskDef.isReuseOutput(),
taskDef.isCleanOutput());
try {
OutputWriter buildOutput = ioRef.getIo().getOut();
try {
OutputWriter buildErrOutput = ioRef.getIo().getErr();
try {
if (taskDef.isCleanOutput()) {
buildOutput.reset();
// There is no need to reset buildErrOutput,
// at least this is what NetBeans tells you in its
// logs if you do.
}
printCommand(buildOutput, command, taskDef);
OutputRef outputRef = configureOutput(
project, taskDef, buildLauncher, buildOutput, buildErrOutput);
try {
ioRef.getIo().select();
buildLauncher.run();
} finally {
// This close method will only forward the last lines
// if they were not terminated with a line separator.
outputRef.close();
}
} catch (Throwable ex) {
LOGGER.log(
ex instanceof Exception ? Level.INFO : Level.SEVERE,
"Gradle build failure: " + command,
ex);
String buildFailureMessage = NbStrings.getBuildFailure(command);
buildErrOutput.println();
buildErrOutput.println(buildFailureMessage);
project.displayError(buildFailureMessage, ex, false);
} finally {
buildErrOutput.close();
}
} finally {
buildOutput.close();
}
} finally {
ioRef.close();
}
} finally {
if (projectConnection != null) {
projectConnection.close();
}
}
}
|
diff --git a/dddsample/src/test/java/se/citerus/dddsample/web/CargoTrackingControllerTest.java b/dddsample/src/test/java/se/citerus/dddsample/web/CargoTrackingControllerTest.java
index dca77a2..28e744c 100644
--- a/dddsample/src/test/java/se/citerus/dddsample/web/CargoTrackingControllerTest.java
+++ b/dddsample/src/test/java/se/citerus/dddsample/web/CargoTrackingControllerTest.java
@@ -1,124 +1,123 @@
package se.citerus.dddsample.web;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockServletContext;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.ModelAndView;
import se.citerus.dddsample.domain.*;
import se.citerus.dddsample.service.CargoService;
import se.citerus.dddsample.service.dto.CargoWithHistoryDTO;
import se.citerus.dddsample.service.dto.HandlingEventDTO;
import se.citerus.dddsample.web.command.TrackCommand;
import java.util.Date;
public class CargoTrackingControllerTest extends TestCase {
CargoTrackingController controller;
MockHttpServletRequest request;
MockHttpServletResponse response;
MockHttpSession session;
MockServletContext servletContext;
protected void setUp() throws Exception {
servletContext = new MockServletContext("test");
request = new MockHttpServletRequest(servletContext);
response = new MockHttpServletResponse();
session = new MockHttpSession(servletContext);
request.setSession(session);
controller = new CargoTrackingController();
controller.setFormView("test-form");
controller.setSuccessView("test-success");
controller.setCommandName("test-command-name");
}
private CargoService getCargoServiceMock() {
return new CargoService() {
public CargoWithHistoryDTO track(TrackingId trackingId) {
final Location a5 = new Location(new UnLocode("AA","AAA"), "AAAAA");
final Location b5 = new Location(new UnLocode("BB","BBB"), "BBBBB");
Cargo cargo = new Cargo(trackingId, a5, b5);
HandlingEvent event = new HandlingEvent(cargo, new Date(10L), new Date(20L), HandlingEvent.Type.RECEIVE, b5, null);
// TODO: use DTO assemblers
CargoWithHistoryDTO cargoDTO = new CargoWithHistoryDTO(
cargo.trackingId().idString(),
cargo.origin().unLocode().idString(),
cargo.finalDestination().unLocode().idString(),
StatusCode.CLAIMED,
"AAAAA",
- "BALO",
- cargo.isMisdirected());
+ "BALO");
cargoDTO.addEvent(new HandlingEventDTO(
event.location().unLocode().idString(),
event.type().toString(),
null, // TODO: event hierarchy will remove this kind of code
event.completionTime()));
return cargoDTO;
}
public void notifyIfMisdirected(TrackingId trackingId) {
}
};
}
private CargoService getCargoServiceNullMock() {
return new CargoService() {
public CargoWithHistoryDTO track(TrackingId trackingId) {
return null;
}
public void notifyIfMisdirected(TrackingId trackingId) {}
};
}
public void testHandleGet() throws Exception {
controller.setCargoService(getCargoServiceMock());
request.setMethod("GET");
ModelAndView mav = controller.handleRequest(request, response);
assertEquals("test-form", mav.getViewName());
assertEquals(2, mav.getModel().size());
assertTrue(mav.getModel().get("test-command-name") instanceof TrackCommand);
}
public void testHandlePost() throws Exception {
controller.setCargoService(getCargoServiceMock());
request.addParameter("trackingId","JKL456");
request.setMethod("POST");
ModelAndView mav = controller.handleRequest(request, response);
assertEquals("test-form", mav.getViewName());
// Errors, command are two standard map attributes, the third should be the cargo object
assertEquals(3, mav.getModel().size());
CargoWithHistoryDTO cargo = (CargoWithHistoryDTO) mav.getModel().get("cargo");
assertEquals("AAAAA", cargo.getCurrentLocationId());
}
public void testUnknownCargo() throws Exception {
controller.setCargoService(getCargoServiceNullMock());
request.setMethod("POST");
request.setParameter("trackingId", "unknown-id");
ModelAndView mav = controller.handleRequest(request, response);
assertEquals("test-form", mav.getViewName());
assertEquals(2, mav.getModel().size());
TrackCommand command = (TrackCommand) mav.getModel().get(controller.getCommandName());
assertEquals("unknown-id", command.getTrackingId());
Errors errors = (Errors) mav.getModel().get(BindingResult.MODEL_KEY_PREFIX + controller.getCommandName());
FieldError fe = errors.getFieldError("trackingId");
assertEquals("cargo.unknown_id", fe.getCode());
assertEquals(1, fe.getArguments().length);
assertEquals(command.getTrackingId(), fe.getArguments()[0]);
}
}
| true | true | private CargoService getCargoServiceMock() {
return new CargoService() {
public CargoWithHistoryDTO track(TrackingId trackingId) {
final Location a5 = new Location(new UnLocode("AA","AAA"), "AAAAA");
final Location b5 = new Location(new UnLocode("BB","BBB"), "BBBBB");
Cargo cargo = new Cargo(trackingId, a5, b5);
HandlingEvent event = new HandlingEvent(cargo, new Date(10L), new Date(20L), HandlingEvent.Type.RECEIVE, b5, null);
// TODO: use DTO assemblers
CargoWithHistoryDTO cargoDTO = new CargoWithHistoryDTO(
cargo.trackingId().idString(),
cargo.origin().unLocode().idString(),
cargo.finalDestination().unLocode().idString(),
StatusCode.CLAIMED,
"AAAAA",
"BALO",
cargo.isMisdirected());
cargoDTO.addEvent(new HandlingEventDTO(
event.location().unLocode().idString(),
event.type().toString(),
null, // TODO: event hierarchy will remove this kind of code
event.completionTime()));
return cargoDTO;
}
public void notifyIfMisdirected(TrackingId trackingId) {
}
};
}
| private CargoService getCargoServiceMock() {
return new CargoService() {
public CargoWithHistoryDTO track(TrackingId trackingId) {
final Location a5 = new Location(new UnLocode("AA","AAA"), "AAAAA");
final Location b5 = new Location(new UnLocode("BB","BBB"), "BBBBB");
Cargo cargo = new Cargo(trackingId, a5, b5);
HandlingEvent event = new HandlingEvent(cargo, new Date(10L), new Date(20L), HandlingEvent.Type.RECEIVE, b5, null);
// TODO: use DTO assemblers
CargoWithHistoryDTO cargoDTO = new CargoWithHistoryDTO(
cargo.trackingId().idString(),
cargo.origin().unLocode().idString(),
cargo.finalDestination().unLocode().idString(),
StatusCode.CLAIMED,
"AAAAA",
"BALO");
cargoDTO.addEvent(new HandlingEventDTO(
event.location().unLocode().idString(),
event.type().toString(),
null, // TODO: event hierarchy will remove this kind of code
event.completionTime()));
return cargoDTO;
}
public void notifyIfMisdirected(TrackingId trackingId) {
}
};
}
|
diff --git a/gdx/src/com/badlogic/gdx/graphics/Sprite.java b/gdx/src/com/badlogic/gdx/graphics/Sprite.java
index 7a71032f6..223b1e5a0 100644
--- a/gdx/src/com/badlogic/gdx/graphics/Sprite.java
+++ b/gdx/src/com/badlogic/gdx/graphics/Sprite.java
@@ -1,547 +1,547 @@
/*
* Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected])
*
* 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.badlogic.gdx.graphics;
import com.badlogic.gdx.utils.MathUtils;
/**
* Holds the geometry, color, and texture information for drawing 2D sprites using {@link SpriteBatch}. A Sprite has a position
* and a size given as width and height. The position is relative to the origin of the coordinate system specified via
* {@link SpriteBatch#begin()} and the respective matrices. A Sprite is always rectangular and its position (x, y) are located in
* the bottom left corner of that rectangle. A Sprite also has an origin around which rotations and scaling are performed. The
* origin is given relative to the bottom left corner of the Sprite, its position.
* @author mzechner
* @author Nathan Sweet <[email protected]>
*/
public class Sprite extends TextureRegion {
static final int VERTEX_SIZE = 2 + 1 + 2;
static final int SPRITE_SIZE = 4 * VERTEX_SIZE;
final float[] vertices = new float[20];
private final Color color = new Color(1, 1, 1, 1);
private float x, y;
float width, height;
private float originX, originY;
private float rotation;
private float scaleX = 1, scaleY = 1;
private boolean dirty = true;
/**
* Creates an uninitialized sprite. The sprite will need a texture, texture region, bounds, and color set before it can be
* drawn.
*/
public Sprite () {
}
/**
* Creates a sprite with width, height, and texture region equal to the size of the texture.
*/
public Sprite (Texture texture) {
this(texture, 0, 0, texture.getWidth(), texture.getHeight());
}
/**
* Creates a sprite with width, height, and texture region equal to the specified size. The texture region's upper left corner
* will be 0,0. * @param srcWidth The width of the texture region. May be negative to flip the sprite when drawn.
* @param srcHeight The height of the texture region. May be negative to flip the sprite when drawn.
*/
public Sprite (Texture texture, int srcWidth, int srcHeight) {
this(texture, 0, 0, srcWidth, srcHeight);
}
/**
* Creates a sprite with width, height, and texture region equal to the specified size. * @param srcWidth The width of the
* texture region. May be negative to flip the sprite when drawn.
* @param srcHeight The height of the texture region. May be negative to flip the sprite when drawn.
*/
public Sprite (Texture texture, int srcX, int srcY, int srcWidth, int srcHeight) {
if (texture == null) throw new IllegalArgumentException("texture cannot be null.");
this.texture = texture;
setRegion(srcX, srcY, srcWidth, srcHeight);
setColor(1, 1, 1, 1);
setSize(Math.abs(srcWidth), Math.abs(srcHeight));
setOrigin(width / 2, height / 2);
}
// Note the region is copied.
public Sprite (TextureRegion region) {
setRegion(region);
setColor(1, 1, 1, 1);
setSize(Math.abs(region.getRegionWidth()), Math.abs(region.getRegionHeight()));
setOrigin(width / 2, height / 2);
}
/**
* Creates a sprite with width, height, and texture region equal to the specified size, relative to specified sprite's texture
* region. * @param srcWidth The width of the texture region. May be negative to flip the sprite when drawn.
* @param srcHeight The height of the texture region. May be negative to flip the sprite when drawn.
*/
public Sprite (TextureRegion region, int srcX, int srcY, int srcWidth, int srcHeight) {
setRegion(region, srcX, srcY, srcWidth, srcHeight);
setColor(1, 1, 1, 1);
setSize(Math.abs(region.getRegionWidth()), Math.abs(region.getRegionHeight()));
setOrigin(width / 2, height / 2);
}
/**
* Creates a sprite that is a copy in every way of the specified sprite.
*/
public Sprite (Sprite sprite) {
set(sprite);
}
public void set (Sprite sprite) {
if (sprite == null) throw new IllegalArgumentException("sprite cannot be null.");
System.arraycopy(sprite.vertices, 0, vertices, 0, SPRITE_SIZE);
texture = sprite.texture;
x = sprite.x;
y = sprite.y;
width = sprite.width;
height = sprite.height;
originX = sprite.originX;
originY = sprite.originY;
rotation = sprite.rotation;
scaleX = sprite.scaleX;
scaleY = sprite.scaleY;
dirty = sprite.dirty;
}
/**
* Sets the position and size of the sprite when drawn, before scaling and rotation are applied. If origin, rotation, or scale
* are changed, it is slightly more efficient to set the bounds after those operations.
*/
public void setBounds (float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
if (dirty) return;
float x2 = x + width;
float y2 = y + height;
float[] vertices = this.vertices;
vertices[X1] = x;
vertices[Y1] = y;
vertices[X2] = x;
vertices[Y2] = y2;
vertices[X3] = x2;
vertices[Y3] = y2;
vertices[X4] = x2;
vertices[Y4] = y;
if (rotation != 0 || scaleX != 1 || scaleY != 1) dirty = true;
}
/**
* Sets the size of the sprite when drawn, before scaling and rotation are applied. If origin, rotation, or scale are changed,
* it is slightly more efficient to set the size after those operations. If both position and size are to be changed, it is
* better to use {@link #setBounds(float, float, float, float)}.
*/
public void setSize (float width, float height) {
this.width = width;
this.height = height;
if (dirty) return;
float x2 = x + width;
float y2 = y + height;
float[] vertices = this.vertices;
vertices[X1] = x;
vertices[Y1] = y;
vertices[X2] = x;
vertices[Y2] = y2;
vertices[X3] = x2;
vertices[Y3] = y2;
vertices[X4] = x2;
vertices[Y4] = y;
if (rotation != 0 || scaleX != 1 || scaleY != 1) dirty = true;
}
/**
* Sets the position where the sprite will be drawn. If origin, rotation, or scale are changed, it is slightly more efficient
* to set the position after those operations. If both position and size are to be changed, it is better to use
* {@link #setBounds(float, float, float, float)}.
*/
public void setPosition (float x, float y) {
translate(x - this.x, y - this.y);
}
/**
* Sets the position relative to the current position where the sprite will be drawn. If origin, rotation, or scale are
* changed, it is slightly more efficient to translate after those operations.
*/
public void translate (float xAmount, float yAmount) {
x += xAmount;
y += yAmount;
if (dirty) return;
float[] vertices = this.vertices;
vertices[X1] += xAmount;
vertices[Y1] += yAmount;
vertices[X2] += xAmount;
vertices[Y2] += yAmount;
vertices[X3] += xAmount;
vertices[Y3] += yAmount;
vertices[X4] += xAmount;
vertices[Y4] += yAmount;
}
public void setColor (Color tint) {
float color = tint.toFloatBits();
float[] vertices = this.vertices;
vertices[C1] = color;
vertices[C2] = color;
vertices[C3] = color;
vertices[C4] = color;
}
public void setColor (float r, float g, float b, float a) {
int intBits = ((int)(255 * a) << 24) | ((int)(255 * b) << 16) | ((int)(255 * g) << 8) | ((int)(255 * r));
float color = Float.intBitsToFloat(intBits & 0xfeffffff);
float[] vertices = this.vertices;
vertices[C1] = color;
vertices[C2] = color;
vertices[C3] = color;
vertices[C4] = color;
}
/**
* Sets the origin in relation to the sprite's position for scaling and rotation.
*/
public void setOrigin (float originX, float originY) {
this.originX = originX;
this.originY = originY;
dirty = true;
}
public void setRotation (float degrees) {
this.rotation = degrees;
dirty = true;
}
/**
* Sets the sprite's rotation relative to the current rotation.
*/
public void rotate (float degrees) {
rotation += degrees;
dirty = true;
}
/**
* Rotates this sprite 90 degrees in-place by rotating the texture coordinates. This rotation is unaffected by
* {@link #setRotation(float)} and {@link #rotate(float)}.
*/
public void rotate90 (boolean clockwise) {
float[] vertices = this.vertices;
if (clockwise) {
float temp = vertices[V1];
vertices[V1] = vertices[V4];
vertices[V4] = vertices[V3];
vertices[V3] = vertices[V2];
vertices[V2] = temp;
temp = vertices[U1];
vertices[U1] = vertices[U4];
vertices[U4] = vertices[U3];
vertices[U3] = vertices[U2];
vertices[U2] = temp;
} else {
float temp = vertices[V1];
vertices[V1] = vertices[V2];
vertices[V2] = vertices[V3];
vertices[V3] = vertices[V4];
vertices[V4] = temp;
temp = vertices[U1];
vertices[U1] = vertices[U2];
vertices[U2] = vertices[U3];
vertices[U3] = vertices[U4];
vertices[U4] = temp;
}
}
public void setScale (float scaleXY) {
this.scaleX = scaleXY;
this.scaleY = scaleXY;
dirty = true;
}
public void setScale (float scaleX, float scaleY) {
this.scaleX = scaleX;
this.scaleY = scaleY;
dirty = true;
}
/**
* Sets the sprite's scale relative to the current scale.
*/
public void scale (float amount) {
this.scaleX += amount;
this.scaleY += amount;
dirty = true;
}
/**
* Returns the packed vertices, colors, and texture coordinates for this sprite.
*/
public float[] getVertices () {
if (dirty) {
dirty = false;
float[] vertices = this.vertices;
float localX = -originX;
float localY = -originY;
float localX2 = localX + width;
float localY2 = localY + height;
float worldOriginX = this.x - localX;
float worldOriginY = this.y - localY;
if (scaleX != 1 || scaleY != 1) {
localX *= scaleX;
localY *= scaleY;
localX2 *= scaleX;
localY2 *= scaleY;
}
if (rotation != 0) {
final float cos = MathUtils.cosDeg(rotation);
final float sin = MathUtils.sinDeg(rotation);
final float localXCos = localX * cos;
final float localXSin = localX * sin;
final float localYCos = localY * cos;
final float localYSin = localY * sin;
final float localX2Cos = localX2 * cos;
final float localX2Sin = localX2 * sin;
- final float localY2Cos = localX2 * cos;
+ final float localY2Cos = localY2 * cos;
final float localY2Sin = localY2 * sin;
final float x1 = localXCos - localYSin + worldOriginX;
final float y1 = localYCos + localXSin + worldOriginY;
vertices[X1] = x1;
vertices[Y1] = y1;
final float x2 = localXCos - localY2Sin + worldOriginX;
final float y2 = localY2Cos + localXSin + worldOriginY;
vertices[X2] = x2;
vertices[Y2] = y2;
final float x3 = localX2Cos - localY2Sin + worldOriginX;
final float y3 = localY2Cos + localX2Sin + worldOriginY;
vertices[X3] = x3;
vertices[Y3] = y3;
vertices[X4] = x1 + (x3 - x2);
vertices[Y4] = y3 - (y2 - y1);
} else {
final float x1 = localX + worldOriginX;
final float y1 = localY + worldOriginY;
final float x2 = localX2 + worldOriginX;
final float y2 = localY2 + worldOriginY;
vertices[X1] = x1;
vertices[Y1] = y1;
vertices[X2] = x1;
vertices[Y2] = y2;
vertices[X3] = x2;
vertices[Y3] = y2;
vertices[X4] = x2;
vertices[Y4] = y1;
}
}
return vertices;
}
public void draw (SpriteBatch spriteBatch) {
spriteBatch.draw(texture, getVertices(), 0, SPRITE_SIZE);
}
public float getX () {
return x;
}
public float getY () {
return y;
}
public float getWidth () {
return width;
}
public float getHeight () {
return height;
}
public float getOriginX () {
return originX;
}
public float getOriginY () {
return originY;
}
public float getRotation () {
return rotation;
}
public float getScaleX () {
return scaleX;
}
public float getScaleY () {
return scaleY;
}
/**
* Returns the color of this sprite. Changing the returned color will have no affect, {@link #setColor(Color)} or
* {@link #setColor(float, float, float, float)} must be used.
*/
public Color getColor () {
float floatBits = vertices[C1];
int intBits = Float.floatToRawIntBits(vertices[C1]);
Color color = this.color;
color.r = (intBits & 0xff) / 255f;
color.g = ((intBits >>> 8) & 0xff) / 255f;
color.b = ((intBits >>> 16) & 0xff) / 255f;
color.a = ((intBits >>> 24) & 0xff) / 255f;
return color;
}
public void setRegion (float u, float v, float u2, float v2) {
this.u = u;
this.v = v;
this.u2 = u2;
this.v2 = v2;
float[] vertices = Sprite.this.vertices;
vertices[U1] = u;
vertices[V1] = v2;
vertices[U2] = u;
vertices[V2] = v;
vertices[U3] = u2;
vertices[V3] = v;
vertices[U4] = u2;
vertices[V4] = v2;
}
public void setU (float u) {
this.u = u;
vertices[U1] = u;
vertices[U2] = u;
}
public void setV (float v) {
this.v = v;
vertices[V2] = v;
vertices[V3] = v;
}
public void setU2 (float u2) {
this.u2 = u2;
vertices[U3] = u2;
vertices[U4] = u2;
}
public void setV2 (float v2) {
this.v2 = v2;
vertices[V1] = v2;
vertices[V4] = v2;
}
public void flip (boolean x, boolean y) {
super.flip(x, y);
float[] vertices = Sprite.this.vertices;
if (x) {
float u = vertices[U1];
float u2 = vertices[U3];
this.u = u;
this.u2 = u2;
vertices[U1] = u2;
vertices[U2] = u2;
vertices[U3] = u;
vertices[U4] = u;
}
if (y) {
float v = vertices[V2];
float v2 = vertices[V1];
this.v = v;
this.v2 = v2;
vertices[V1] = v;
vertices[V2] = v2;
vertices[V3] = v2;
vertices[V4] = v;
}
}
public void scroll (float xAmount, float yAmount) {
float[] vertices = Sprite.this.vertices;
if (xAmount != 0) {
float u = (vertices[U1] + xAmount) % 1;
float u2 = u + width / texture.getWidth();
this.u = u;
this.u2 = u2;
vertices[U1] = u;
vertices[U2] = u;
vertices[U3] = u2;
vertices[U4] = u2;
}
if (yAmount != 0) {
float v = (vertices[V2] + yAmount) % 1;
float v2 = v + height / texture.getHeight();
this.v = v;
this.v2 = v2;
vertices[V1] = v2;
vertices[V2] = v;
vertices[V3] = v;
vertices[V4] = v2;
}
}
static private final int X1 = 0;
static private final int Y1 = 1;
static private final int C1 = 2;
static private final int U1 = 3;
static private final int V1 = 4;
static private final int X2 = 5;
static private final int Y2 = 6;
static private final int C2 = 7;
static private final int U2 = 8;
static private final int V2 = 9;
static private final int X3 = 10;
static private final int Y3 = 11;
static private final int C3 = 12;
static private final int U3 = 13;
static private final int V3 = 14;
static private final int X4 = 15;
static private final int Y4 = 16;
static private final int C4 = 17;
static private final int U4 = 18;
static private final int V4 = 19;
}
| true | true | public float[] getVertices () {
if (dirty) {
dirty = false;
float[] vertices = this.vertices;
float localX = -originX;
float localY = -originY;
float localX2 = localX + width;
float localY2 = localY + height;
float worldOriginX = this.x - localX;
float worldOriginY = this.y - localY;
if (scaleX != 1 || scaleY != 1) {
localX *= scaleX;
localY *= scaleY;
localX2 *= scaleX;
localY2 *= scaleY;
}
if (rotation != 0) {
final float cos = MathUtils.cosDeg(rotation);
final float sin = MathUtils.sinDeg(rotation);
final float localXCos = localX * cos;
final float localXSin = localX * sin;
final float localYCos = localY * cos;
final float localYSin = localY * sin;
final float localX2Cos = localX2 * cos;
final float localX2Sin = localX2 * sin;
final float localY2Cos = localX2 * cos;
final float localY2Sin = localY2 * sin;
final float x1 = localXCos - localYSin + worldOriginX;
final float y1 = localYCos + localXSin + worldOriginY;
vertices[X1] = x1;
vertices[Y1] = y1;
final float x2 = localXCos - localY2Sin + worldOriginX;
final float y2 = localY2Cos + localXSin + worldOriginY;
vertices[X2] = x2;
vertices[Y2] = y2;
final float x3 = localX2Cos - localY2Sin + worldOriginX;
final float y3 = localY2Cos + localX2Sin + worldOriginY;
vertices[X3] = x3;
vertices[Y3] = y3;
vertices[X4] = x1 + (x3 - x2);
vertices[Y4] = y3 - (y2 - y1);
} else {
final float x1 = localX + worldOriginX;
final float y1 = localY + worldOriginY;
final float x2 = localX2 + worldOriginX;
final float y2 = localY2 + worldOriginY;
vertices[X1] = x1;
vertices[Y1] = y1;
vertices[X2] = x1;
vertices[Y2] = y2;
vertices[X3] = x2;
vertices[Y3] = y2;
vertices[X4] = x2;
vertices[Y4] = y1;
}
}
return vertices;
}
| public float[] getVertices () {
if (dirty) {
dirty = false;
float[] vertices = this.vertices;
float localX = -originX;
float localY = -originY;
float localX2 = localX + width;
float localY2 = localY + height;
float worldOriginX = this.x - localX;
float worldOriginY = this.y - localY;
if (scaleX != 1 || scaleY != 1) {
localX *= scaleX;
localY *= scaleY;
localX2 *= scaleX;
localY2 *= scaleY;
}
if (rotation != 0) {
final float cos = MathUtils.cosDeg(rotation);
final float sin = MathUtils.sinDeg(rotation);
final float localXCos = localX * cos;
final float localXSin = localX * sin;
final float localYCos = localY * cos;
final float localYSin = localY * sin;
final float localX2Cos = localX2 * cos;
final float localX2Sin = localX2 * sin;
final float localY2Cos = localY2 * cos;
final float localY2Sin = localY2 * sin;
final float x1 = localXCos - localYSin + worldOriginX;
final float y1 = localYCos + localXSin + worldOriginY;
vertices[X1] = x1;
vertices[Y1] = y1;
final float x2 = localXCos - localY2Sin + worldOriginX;
final float y2 = localY2Cos + localXSin + worldOriginY;
vertices[X2] = x2;
vertices[Y2] = y2;
final float x3 = localX2Cos - localY2Sin + worldOriginX;
final float y3 = localY2Cos + localX2Sin + worldOriginY;
vertices[X3] = x3;
vertices[Y3] = y3;
vertices[X4] = x1 + (x3 - x2);
vertices[Y4] = y3 - (y2 - y1);
} else {
final float x1 = localX + worldOriginX;
final float y1 = localY + worldOriginY;
final float x2 = localX2 + worldOriginX;
final float y2 = localY2 + worldOriginY;
vertices[X1] = x1;
vertices[Y1] = y1;
vertices[X2] = x1;
vertices[Y2] = y2;
vertices[X3] = x2;
vertices[Y3] = y2;
vertices[X4] = x2;
vertices[Y4] = y1;
}
}
return vertices;
}
|
diff --git a/src/java/com/example/HelloWorld.java b/src/java/com/example/HelloWorld.java
index 15d4983..d535707 100644
--- a/src/java/com/example/HelloWorld.java
+++ b/src/java/com/example/HelloWorld.java
@@ -1,58 +1,58 @@
package com.example;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import com.vaadin.ui.Window;
import org.dellroad.stuff.vaadin.ContextApplication;
import org.dellroad.stuff.vaadin.SpringContextApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ConfigurableWebApplicationContext;
@SuppressWarnings("serial")
public class HelloWorld extends SpringContextApplication {
@Autowired
private MyBean myBean;
@Autowired
private MyApplicationBean myApplicationBean;
@Override
public void initSpringApplication(ConfigurableWebApplicationContext context) {
this.log.info("initializing HelloWorld application...");
Window mainWindow = new Window("Vaadin+Spring Demo #3");
mainWindow.addComponent(new Label(
"Notes: the bean \"myBean\" bean lives in the Spring application context that is associated with"
+ " the overall servlet context, that is, the Spring application context created by Spring's"
+ " ContextLoaderListener. It will not change until you reload the overall web application."
+ " The \"myApplicationBean\" is a bean in the Spring application context that is automatically"
+ " created along with each new Vaadin application instance (defined by \"HelloWorld.xml\")."
- + " It will not change if you just reload your browser, but if hit the \"Close Application\""
+ + " It will not change if you just reload your browser, but if you hit the \"Close Application\""
+ " URL below, then it will change. Similarly for \"vaadinConfigurableBean\", which is a bean that is"
+ " configured into the Spring application implicitly using AspectJ and the @VaadinConfigurable"
+ " annotation (rather than explictly in \"HelloWorld.xml\" as is \"myApplicationBean\")."));
mainWindow.addComponent(new Label("----------", Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("myBean: " + this.myBean.info(), Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("----------", Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("myApplicationBean: " + this.myApplicationBean.info(), Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("----------", Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("vaadinConfigurableBean: " + this.myApplicationBean.getVaadinConfigurableBean().info(),
Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("----------", Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Button("Close Application", new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent event) {
HelloWorld.this.log.info("closing HelloWorld application...");
HelloWorld.get().close();
}
}));
this.setMainWindow(mainWindow);
}
public static HelloWorld get() {
return ContextApplication.get(HelloWorld.class);
}
}
| true | true | public void initSpringApplication(ConfigurableWebApplicationContext context) {
this.log.info("initializing HelloWorld application...");
Window mainWindow = new Window("Vaadin+Spring Demo #3");
mainWindow.addComponent(new Label(
"Notes: the bean \"myBean\" bean lives in the Spring application context that is associated with"
+ " the overall servlet context, that is, the Spring application context created by Spring's"
+ " ContextLoaderListener. It will not change until you reload the overall web application."
+ " The \"myApplicationBean\" is a bean in the Spring application context that is automatically"
+ " created along with each new Vaadin application instance (defined by \"HelloWorld.xml\")."
+ " It will not change if you just reload your browser, but if hit the \"Close Application\""
+ " URL below, then it will change. Similarly for \"vaadinConfigurableBean\", which is a bean that is"
+ " configured into the Spring application implicitly using AspectJ and the @VaadinConfigurable"
+ " annotation (rather than explictly in \"HelloWorld.xml\" as is \"myApplicationBean\")."));
mainWindow.addComponent(new Label("----------", Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("myBean: " + this.myBean.info(), Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("----------", Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("myApplicationBean: " + this.myApplicationBean.info(), Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("----------", Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("vaadinConfigurableBean: " + this.myApplicationBean.getVaadinConfigurableBean().info(),
Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("----------", Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Button("Close Application", new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent event) {
HelloWorld.this.log.info("closing HelloWorld application...");
HelloWorld.get().close();
}
}));
this.setMainWindow(mainWindow);
}
| public void initSpringApplication(ConfigurableWebApplicationContext context) {
this.log.info("initializing HelloWorld application...");
Window mainWindow = new Window("Vaadin+Spring Demo #3");
mainWindow.addComponent(new Label(
"Notes: the bean \"myBean\" bean lives in the Spring application context that is associated with"
+ " the overall servlet context, that is, the Spring application context created by Spring's"
+ " ContextLoaderListener. It will not change until you reload the overall web application."
+ " The \"myApplicationBean\" is a bean in the Spring application context that is automatically"
+ " created along with each new Vaadin application instance (defined by \"HelloWorld.xml\")."
+ " It will not change if you just reload your browser, but if you hit the \"Close Application\""
+ " URL below, then it will change. Similarly for \"vaadinConfigurableBean\", which is a bean that is"
+ " configured into the Spring application implicitly using AspectJ and the @VaadinConfigurable"
+ " annotation (rather than explictly in \"HelloWorld.xml\" as is \"myApplicationBean\")."));
mainWindow.addComponent(new Label("----------", Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("myBean: " + this.myBean.info(), Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("----------", Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("myApplicationBean: " + this.myApplicationBean.info(), Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("----------", Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("vaadinConfigurableBean: " + this.myApplicationBean.getVaadinConfigurableBean().info(),
Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Label("----------", Label.CONTENT_PREFORMATTED));
mainWindow.addComponent(new Button("Close Application", new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent event) {
HelloWorld.this.log.info("closing HelloWorld application...");
HelloWorld.get().close();
}
}));
this.setMainWindow(mainWindow);
}
|
diff --git a/src/main/java/net/rubygrapefruit/platform/internal/NativeLibraryLocator.java b/src/main/java/net/rubygrapefruit/platform/internal/NativeLibraryLocator.java
index 075ba39..9d9a175 100755
--- a/src/main/java/net/rubygrapefruit/platform/internal/NativeLibraryLocator.java
+++ b/src/main/java/net/rubygrapefruit/platform/internal/NativeLibraryLocator.java
@@ -1,113 +1,113 @@
/*
* Copyright 2012 Adam Murdoch
*
* 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.rubygrapefruit.platform.internal;
import net.rubygrapefruit.platform.NativeException;
import net.rubygrapefruit.platform.internal.jni.NativeLibraryFunctions;
import java.io.*;
import java.net.URL;
import java.nio.channels.FileLock;
public class NativeLibraryLocator {
private final File extractDir;
public NativeLibraryLocator(File extractDir) {
this.extractDir = extractDir;
}
public File find(LibraryDef libraryDef) throws IOException {
String resourceName = String.format("net/rubygrapefruit/platform/%s/%s", libraryDef.platform, libraryDef.name);
if (extractDir != null) {
- File libFile = new File(extractDir, String.format("%s/%s", NativeLibraryFunctions.VERSION, libraryDef.name));
+ File libFile = new File(extractDir, String.format("%s/%s/%s", NativeLibraryFunctions.VERSION, libraryDef.platform, libraryDef.name));
File lockFile = new File(libFile.getParentFile(), libFile.getName() + ".lock");
lockFile.getParentFile().mkdirs();
lockFile.createNewFile();
RandomAccessFile lockFileAccess = new RandomAccessFile(lockFile, "rw");
try {
// Take exclusive lock on lock file
FileLock lock = lockFileAccess.getChannel().lock();
if (lockFile.length() > 0 && lockFileAccess.readBoolean()) {
// Library has been extracted
return libFile;
}
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
// Extract library and write marker to lock file
libFile.getParentFile().mkdirs();
copy(resource, libFile);
lockFileAccess.seek(0);
lockFileAccess.writeBoolean(true);
return libFile;
}
} finally {
// Also releases lock
lockFileAccess.close();
}
} else {
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
File libFile;
File libDir = File.createTempFile("native-platform", "dir");
libDir.delete();
libDir.mkdirs();
libFile = new File(libDir, libraryDef.name);
libFile.deleteOnExit();
copy(resource, libFile);
return libFile;
}
}
String componentName = libraryDef.name.replaceFirst("^lib", "").replaceFirst("\\.\\w+$", "");
int pos = componentName.indexOf("-");
while (pos >= 0) {
componentName = componentName.substring(0, pos) + Character.toUpperCase(componentName.charAt(pos + 1)) + componentName.substring(pos + 2);
pos = componentName.indexOf("-", pos);
}
File libFile = new File(String.format("build/binaries/%sSharedLibrary/%s/%s", componentName, libraryDef.platform.replace("-", "_"), libraryDef.name));
if (libFile.isFile()) {
return libFile;
}
return null;
}
private static void copy(URL source, File dest) {
try {
InputStream inputStream = source.openStream();
try {
OutputStream outputStream = new FileOutputStream(dest);
try {
byte[] buffer = new byte[4096];
while (true) {
int nread = inputStream.read(buffer);
if (nread < 0) {
break;
}
outputStream.write(buffer, 0, nread);
}
} finally {
outputStream.close();
}
} finally {
inputStream.close();
}
} catch (IOException e) {
throw new NativeException(String.format("Could not extract native JNI library."), e);
}
}
}
| true | true | public File find(LibraryDef libraryDef) throws IOException {
String resourceName = String.format("net/rubygrapefruit/platform/%s/%s", libraryDef.platform, libraryDef.name);
if (extractDir != null) {
File libFile = new File(extractDir, String.format("%s/%s", NativeLibraryFunctions.VERSION, libraryDef.name));
File lockFile = new File(libFile.getParentFile(), libFile.getName() + ".lock");
lockFile.getParentFile().mkdirs();
lockFile.createNewFile();
RandomAccessFile lockFileAccess = new RandomAccessFile(lockFile, "rw");
try {
// Take exclusive lock on lock file
FileLock lock = lockFileAccess.getChannel().lock();
if (lockFile.length() > 0 && lockFileAccess.readBoolean()) {
// Library has been extracted
return libFile;
}
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
// Extract library and write marker to lock file
libFile.getParentFile().mkdirs();
copy(resource, libFile);
lockFileAccess.seek(0);
lockFileAccess.writeBoolean(true);
return libFile;
}
} finally {
// Also releases lock
lockFileAccess.close();
}
} else {
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
File libFile;
File libDir = File.createTempFile("native-platform", "dir");
libDir.delete();
libDir.mkdirs();
libFile = new File(libDir, libraryDef.name);
libFile.deleteOnExit();
copy(resource, libFile);
return libFile;
}
}
String componentName = libraryDef.name.replaceFirst("^lib", "").replaceFirst("\\.\\w+$", "");
int pos = componentName.indexOf("-");
while (pos >= 0) {
componentName = componentName.substring(0, pos) + Character.toUpperCase(componentName.charAt(pos + 1)) + componentName.substring(pos + 2);
pos = componentName.indexOf("-", pos);
}
File libFile = new File(String.format("build/binaries/%sSharedLibrary/%s/%s", componentName, libraryDef.platform.replace("-", "_"), libraryDef.name));
if (libFile.isFile()) {
return libFile;
}
return null;
}
| public File find(LibraryDef libraryDef) throws IOException {
String resourceName = String.format("net/rubygrapefruit/platform/%s/%s", libraryDef.platform, libraryDef.name);
if (extractDir != null) {
File libFile = new File(extractDir, String.format("%s/%s/%s", NativeLibraryFunctions.VERSION, libraryDef.platform, libraryDef.name));
File lockFile = new File(libFile.getParentFile(), libFile.getName() + ".lock");
lockFile.getParentFile().mkdirs();
lockFile.createNewFile();
RandomAccessFile lockFileAccess = new RandomAccessFile(lockFile, "rw");
try {
// Take exclusive lock on lock file
FileLock lock = lockFileAccess.getChannel().lock();
if (lockFile.length() > 0 && lockFileAccess.readBoolean()) {
// Library has been extracted
return libFile;
}
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
// Extract library and write marker to lock file
libFile.getParentFile().mkdirs();
copy(resource, libFile);
lockFileAccess.seek(0);
lockFileAccess.writeBoolean(true);
return libFile;
}
} finally {
// Also releases lock
lockFileAccess.close();
}
} else {
URL resource = getClass().getClassLoader().getResource(resourceName);
if (resource != null) {
File libFile;
File libDir = File.createTempFile("native-platform", "dir");
libDir.delete();
libDir.mkdirs();
libFile = new File(libDir, libraryDef.name);
libFile.deleteOnExit();
copy(resource, libFile);
return libFile;
}
}
String componentName = libraryDef.name.replaceFirst("^lib", "").replaceFirst("\\.\\w+$", "");
int pos = componentName.indexOf("-");
while (pos >= 0) {
componentName = componentName.substring(0, pos) + Character.toUpperCase(componentName.charAt(pos + 1)) + componentName.substring(pos + 2);
pos = componentName.indexOf("-", pos);
}
File libFile = new File(String.format("build/binaries/%sSharedLibrary/%s/%s", componentName, libraryDef.platform.replace("-", "_"), libraryDef.name));
if (libFile.isFile()) {
return libFile;
}
return null;
}
|
diff --git a/src/com/github/kenji0717/a3cs/CarRaceGUI.java b/src/com/github/kenji0717/a3cs/CarRaceGUI.java
index d66bd96..f126da4 100644
--- a/src/com/github/kenji0717/a3cs/CarRaceGUI.java
+++ b/src/com/github/kenji0717/a3cs/CarRaceGUI.java
@@ -1,288 +1,295 @@
package com.github.kenji0717.a3cs;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.PrintStream;
import java.util.ResourceBundle;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.vecmath.Vector3d;
import jp.sourceforge.acerola3d.a3.*;
class CarRaceGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
CarRaceImpl impl;
SimpleIDE ide;
A3Canvas mainCanvas;
A3CSController a3csController;
A3SubCanvas carCanvas;
double cameraDist = 6.7;
JTextField carClassTF;
JLabel loadFromL;
JButton changeCPB;
JButton confB;
JButton ideB;
JLabel generalInfoL;
JCheckBox fastForwardCB;
JButton startB;
JButton pauseB;
JButton stopB;
//JLabel carEnergyL;
JTextArea stdOutTA;
JTextAreaOutputStream out;
//i18n
ResourceBundle messages;
String i18n(String s) {
return messages.getString(s);
}
CarRaceGUI(CarRaceImpl i,String carClass) {
super("CarRace");
PropertiesControl pc = new PropertiesControl("UTF-8");
messages = ResourceBundle.getBundle("Messages",pc);
System.out.println("i18n: test="+i18n("test"));
impl = i;
ide = new SimpleIDE(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
VBox baseBox = new VBox();
this.add(baseBox,BorderLayout.CENTER);
HBox controlBox = new HBox();
baseBox.myAdd(controlBox,0);
HBox classNameBox = new HBox();
classNameBox.setBorder(new TitledBorder(i18n("main.carClassname")));
controlBox.myAdd(classNameBox,1);
carClassTF = new JTextField(carClass,20);
classNameBox.myAdd(carClassTF,1);
HBox loadFromBox = new HBox();
loadFromBox.setBorder(new TitledBorder(i18n("main.loadFrom")));
controlBox.myAdd(loadFromBox,0);
loadFromL = new JLabel("loadFrom???");
loadFromBox.myAdd(loadFromL,0);
//changeCPB = new JButton(new String[]{"システムのみ","作業フォルダ","JARファイル"});
changeCPB = new JButton(i18n("main.change"));
changeCPB.addActionListener(this);
loadFromBox.myAdd(changeCPB,0);
VBox controlBox1 = new VBox();
controlBox.myAdd(controlBox1,0);
confB = new JButton(i18n("main.settings"));
confB.addActionListener(this);
controlBox1.myAdd(confB,0);
ideB = new JButton(i18n("main.programming"));
ideB.addActionListener(this);
controlBox1.myAdd(ideB,0);
VBox controlBox2 = new VBox();
controlBox.myAdd(controlBox2,0);
HBox generalInfoBox = new HBox();
controlBox2.myAdd(generalInfoBox,0);
fastForwardCB = new JCheckBox(i18n("main.fastForward"));
fastForwardCB.addActionListener(this);
generalInfoBox.myAdd(fastForwardCB,0);
generalInfoL = new JLabel(i18n("main.time"));
generalInfoBox.myAdd(generalInfoL,1);
HBox mainButtonsBox = new HBox();
controlBox2.myAdd(mainButtonsBox,0);
startB = new JButton(i18n("main.start"));
startB.addActionListener(this);
mainButtonsBox.myAdd(startB,1);
pauseB = new JButton(i18n("main.pause"));
pauseB.addActionListener(this);
mainButtonsBox.myAdd(pauseB,1);
stopB = new JButton(i18n("main.stop"));
stopB.addActionListener(this);
mainButtonsBox.myAdd(stopB,1);
- HBox displayBox = new HBox();
- baseBox.myAdd(displayBox,1);
+ JSplitPane displayAndStdOutSP = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
+ baseBox.myAdd(displayAndStdOutSP,1);
+ JSplitPane displaySP = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
+ displayAndStdOutSP.setTopComponent(displaySP);
mainCanvas = A3Canvas.createA3Canvas(400,400);
+ mainCanvas.setPreferredSize(new Dimension(400,400));
+ mainCanvas.setMinimumSize(new Dimension(40,40));
mainCanvas.setCameraLocImmediately(0.0,150.0,0.0);
mainCanvas.setCameraLookAtPointImmediately(-50.0,0.0,1.0);
a3csController = new A3CSController(150.0);
mainCanvas.setA3Controller(a3csController);
//mainCanvas.setNavigationMode(A3CanvasInterface.NaviMode.SIMPLE,150.0);
- displayBox.myAdd(mainCanvas,1);
+ displaySP.setLeftComponent(mainCanvas);
VBox subBox = new VBox();
- displayBox.myAdd(subBox,1);
+ displaySP.setRightComponent(subBox);
HBox carBox = new HBox();
subBox.myAdd(carBox,1);
carCanvas = A3SubCanvas.createA3SubCanvas(200,200);
+ carCanvas.setPreferredSize(new Dimension(200,200));
+ carCanvas.setMinimumSize(new Dimension(20,20));
carBox.myAdd(carCanvas,1);
//VBox carInfoBox = new VBox();
//carBox.myAdd(carInfoBox,0);
//carInfoBox.myAdd(new JLabel("CAR:"),0);
//carEnergyL = new JLabel("Energy: 000");
//carInfoBox.myAdd(carEnergyL,0);
stdOutTA = new JTextArea(10,40);
stdOutTA.setEditable(false);
JScrollPane sp = new JScrollPane(stdOutTA);
- sp.setMinimumSize(new Dimension(100,100));
- baseBox.myAdd(sp,0);
+ sp.setPreferredSize(new Dimension(100,100));
+ sp.setMinimumSize(new Dimension(10,10));
+ displayAndStdOutSP.setBottomComponent(sp);
out = new JTextAreaOutputStream(stdOutTA,System.out);
PrintStream ps = new PrintStream(out,true);
System.setOut(ps);
System.setErr(ps);
//this.pack();
//this.setVisible(true);
updateLoadFrom();
}
void setCar(CarBase c) {
carCanvas.setAvatar(c.car.a3);
Vector3d lookAt = new Vector3d(0.0,0.0,6.0);
Vector3d camera = new Vector3d(0.0,3.0,-6.0);
camera.normalize();
camera.scale(cameraDist);
Vector3d up = new Vector3d(0.0,1.0,0.0);
carCanvas.setNavigationMode(A3CanvasInterface.NaviMode.CHASE,lookAt,camera,up,10.0);
}
void updateCarInfo(CarBase c) {
//carEnergyL.setText("Energy: "+c.energy);
}
void updateTime(double t) {
generalInfoL.setText(i18n("main.time")+String.format("%4.2f",t));
}
@Override
public void actionPerformed(ActionEvent ae) {
Object s = ae.getSource();
if (s==startB) {
impl.startBattle();
} else if (s==pauseB) {
impl.pauseBattle();
} else if (s==stopB) {
impl.stopBattle();
} else if (s==changeCPB) {
changeCP();
} else if (s==confB) {
conf();
} else if (s==ideB) {
ide();
} else if (s==fastForwardCB) {
impl.fastForward(fastForwardCB.isSelected());
}
}
void changeCP() {
Object[] possibleValues = {
i18n("ccp.onlySystem"),
i18n("ccp.workingFolder"),
i18n("ccp.jarFile") };
Object iniVal;
if (impl.carClasspath.equals("System"))
iniVal = possibleValues[0];
else if (impl.carClasspath.equals("IDE"))
iniVal = possibleValues[1];
else
iniVal = possibleValues[2];
String selectedValue = (String)JOptionPane.showInputDialog(this,
i18n("ccp.whereLoadFrom"), "Input", JOptionPane.INFORMATION_MESSAGE,
null, possibleValues, iniVal);
if (selectedValue==null)
return;
if (selectedValue.equals(possibleValues[0]))
impl.changeCP("System");
else if (selectedValue.equals(possibleValues[1]))
if (impl.workDir==null) {
JOptionPane.showMessageDialog(this,i18n("ccp.warning1"));
} else {
impl.changeCP("IDE");
}
else {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JAR File", "jar");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
String url = f.toURI().toString();
url = "jar:"+url+"!/";
impl.changeCP(url);
}
}
updateLoadFrom();
}
void updateLoadFrom() {
if (impl.carClasspath.equals("System"))
loadFromL.setText(i18n("ccp.onlySystem"));
else if (impl.carClasspath.equals("IDE"))
loadFromL.setText(i18n("ccp.workingFolder"));
else
loadFromL.setText(i18n("ccp.jarFile"));
}
void setParamEditable(boolean b) {
carClassTF.setEditable(b);
changeCPB.setEnabled(b);
confB.setEnabled(b);
ideB.setEnabled(b);
}
void conf() {
Object[] possibleValues = {
i18n("conf.workingFolder"), i18n("conf.cameraTracking") };
String selectedValue = (String)JOptionPane.showInputDialog(this,
i18n("conf.whichOption"), "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
if (selectedValue==null)
return;
if (selectedValue.equals(possibleValues[0])) {
File iniF = null;
if (impl.workDir!=null) {
iniF = new File(impl.workDir);
}
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (iniF!=null)
chooser.setSelectedFile(iniF);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
impl.setWorkDir(f.getAbsolutePath());
impl.setWorkDirURL(f.toURI().toString());
} else {
//変更しないことにした
//impl.setWorkDir(null);
//impl.setWorkDirURL(null);
}
} else if (selectedValue.equals(possibleValues[1])) {
try {
String val = JOptionPane.showInputDialog(this,i18n("conf.distance"),"6.7");
if (val==null) return;
cameraDist = Double.parseDouble(val);
Vector3d lookAt = new Vector3d(0.0,0.0,6.0);
Vector3d camera = new Vector3d(0.0,3.0,-6.0);
camera.normalize();camera.scale(cameraDist);
Vector3d up = new Vector3d(0.0,1.0,0.0);
carCanvas.setNavigationMode(A3CanvasInterface.NaviMode.CHASE,lookAt,camera,up,10.0);
val = JOptionPane.showInputDialog(this,i18n("conf.interpolation"),"0.1");
if (val==null) return;
double dVal = Double.parseDouble(val);
carCanvas.setCameraInterpolateRatio(dVal);
} catch(Exception e) {
e.printStackTrace();
}
}
}
void ide() {
ide.popup(impl.workDir);
}
void clearTA() {
stdOutTA.setText("");
}
void clearCamera() {
mainCanvas.setCameraLocImmediately(0.0,150.0,0.0);
mainCanvas.setCameraLookAtPointImmediately(-50.0,0.0,1.0);
carCanvas.setCameraLocImmediately(-10,10,0);
carCanvas.setCameraLookAtPointImmediately(0,0,0);
}
}
| false | true | CarRaceGUI(CarRaceImpl i,String carClass) {
super("CarRace");
PropertiesControl pc = new PropertiesControl("UTF-8");
messages = ResourceBundle.getBundle("Messages",pc);
System.out.println("i18n: test="+i18n("test"));
impl = i;
ide = new SimpleIDE(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
VBox baseBox = new VBox();
this.add(baseBox,BorderLayout.CENTER);
HBox controlBox = new HBox();
baseBox.myAdd(controlBox,0);
HBox classNameBox = new HBox();
classNameBox.setBorder(new TitledBorder(i18n("main.carClassname")));
controlBox.myAdd(classNameBox,1);
carClassTF = new JTextField(carClass,20);
classNameBox.myAdd(carClassTF,1);
HBox loadFromBox = new HBox();
loadFromBox.setBorder(new TitledBorder(i18n("main.loadFrom")));
controlBox.myAdd(loadFromBox,0);
loadFromL = new JLabel("loadFrom???");
loadFromBox.myAdd(loadFromL,0);
//changeCPB = new JButton(new String[]{"システムのみ","作業フォルダ","JARファイル"});
changeCPB = new JButton(i18n("main.change"));
changeCPB.addActionListener(this);
loadFromBox.myAdd(changeCPB,0);
VBox controlBox1 = new VBox();
controlBox.myAdd(controlBox1,0);
confB = new JButton(i18n("main.settings"));
confB.addActionListener(this);
controlBox1.myAdd(confB,0);
ideB = new JButton(i18n("main.programming"));
ideB.addActionListener(this);
controlBox1.myAdd(ideB,0);
VBox controlBox2 = new VBox();
controlBox.myAdd(controlBox2,0);
HBox generalInfoBox = new HBox();
controlBox2.myAdd(generalInfoBox,0);
fastForwardCB = new JCheckBox(i18n("main.fastForward"));
fastForwardCB.addActionListener(this);
generalInfoBox.myAdd(fastForwardCB,0);
generalInfoL = new JLabel(i18n("main.time"));
generalInfoBox.myAdd(generalInfoL,1);
HBox mainButtonsBox = new HBox();
controlBox2.myAdd(mainButtonsBox,0);
startB = new JButton(i18n("main.start"));
startB.addActionListener(this);
mainButtonsBox.myAdd(startB,1);
pauseB = new JButton(i18n("main.pause"));
pauseB.addActionListener(this);
mainButtonsBox.myAdd(pauseB,1);
stopB = new JButton(i18n("main.stop"));
stopB.addActionListener(this);
mainButtonsBox.myAdd(stopB,1);
HBox displayBox = new HBox();
baseBox.myAdd(displayBox,1);
mainCanvas = A3Canvas.createA3Canvas(400,400);
mainCanvas.setCameraLocImmediately(0.0,150.0,0.0);
mainCanvas.setCameraLookAtPointImmediately(-50.0,0.0,1.0);
a3csController = new A3CSController(150.0);
mainCanvas.setA3Controller(a3csController);
//mainCanvas.setNavigationMode(A3CanvasInterface.NaviMode.SIMPLE,150.0);
displayBox.myAdd(mainCanvas,1);
VBox subBox = new VBox();
displayBox.myAdd(subBox,1);
HBox carBox = new HBox();
subBox.myAdd(carBox,1);
carCanvas = A3SubCanvas.createA3SubCanvas(200,200);
carBox.myAdd(carCanvas,1);
//VBox carInfoBox = new VBox();
//carBox.myAdd(carInfoBox,0);
//carInfoBox.myAdd(new JLabel("CAR:"),0);
//carEnergyL = new JLabel("Energy: 000");
//carInfoBox.myAdd(carEnergyL,0);
stdOutTA = new JTextArea(10,40);
stdOutTA.setEditable(false);
JScrollPane sp = new JScrollPane(stdOutTA);
sp.setMinimumSize(new Dimension(100,100));
baseBox.myAdd(sp,0);
out = new JTextAreaOutputStream(stdOutTA,System.out);
PrintStream ps = new PrintStream(out,true);
System.setOut(ps);
System.setErr(ps);
//this.pack();
//this.setVisible(true);
updateLoadFrom();
}
| CarRaceGUI(CarRaceImpl i,String carClass) {
super("CarRace");
PropertiesControl pc = new PropertiesControl("UTF-8");
messages = ResourceBundle.getBundle("Messages",pc);
System.out.println("i18n: test="+i18n("test"));
impl = i;
ide = new SimpleIDE(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
VBox baseBox = new VBox();
this.add(baseBox,BorderLayout.CENTER);
HBox controlBox = new HBox();
baseBox.myAdd(controlBox,0);
HBox classNameBox = new HBox();
classNameBox.setBorder(new TitledBorder(i18n("main.carClassname")));
controlBox.myAdd(classNameBox,1);
carClassTF = new JTextField(carClass,20);
classNameBox.myAdd(carClassTF,1);
HBox loadFromBox = new HBox();
loadFromBox.setBorder(new TitledBorder(i18n("main.loadFrom")));
controlBox.myAdd(loadFromBox,0);
loadFromL = new JLabel("loadFrom???");
loadFromBox.myAdd(loadFromL,0);
//changeCPB = new JButton(new String[]{"システムのみ","作業フォルダ","JARファイル"});
changeCPB = new JButton(i18n("main.change"));
changeCPB.addActionListener(this);
loadFromBox.myAdd(changeCPB,0);
VBox controlBox1 = new VBox();
controlBox.myAdd(controlBox1,0);
confB = new JButton(i18n("main.settings"));
confB.addActionListener(this);
controlBox1.myAdd(confB,0);
ideB = new JButton(i18n("main.programming"));
ideB.addActionListener(this);
controlBox1.myAdd(ideB,0);
VBox controlBox2 = new VBox();
controlBox.myAdd(controlBox2,0);
HBox generalInfoBox = new HBox();
controlBox2.myAdd(generalInfoBox,0);
fastForwardCB = new JCheckBox(i18n("main.fastForward"));
fastForwardCB.addActionListener(this);
generalInfoBox.myAdd(fastForwardCB,0);
generalInfoL = new JLabel(i18n("main.time"));
generalInfoBox.myAdd(generalInfoL,1);
HBox mainButtonsBox = new HBox();
controlBox2.myAdd(mainButtonsBox,0);
startB = new JButton(i18n("main.start"));
startB.addActionListener(this);
mainButtonsBox.myAdd(startB,1);
pauseB = new JButton(i18n("main.pause"));
pauseB.addActionListener(this);
mainButtonsBox.myAdd(pauseB,1);
stopB = new JButton(i18n("main.stop"));
stopB.addActionListener(this);
mainButtonsBox.myAdd(stopB,1);
JSplitPane displayAndStdOutSP = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
baseBox.myAdd(displayAndStdOutSP,1);
JSplitPane displaySP = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
displayAndStdOutSP.setTopComponent(displaySP);
mainCanvas = A3Canvas.createA3Canvas(400,400);
mainCanvas.setPreferredSize(new Dimension(400,400));
mainCanvas.setMinimumSize(new Dimension(40,40));
mainCanvas.setCameraLocImmediately(0.0,150.0,0.0);
mainCanvas.setCameraLookAtPointImmediately(-50.0,0.0,1.0);
a3csController = new A3CSController(150.0);
mainCanvas.setA3Controller(a3csController);
//mainCanvas.setNavigationMode(A3CanvasInterface.NaviMode.SIMPLE,150.0);
displaySP.setLeftComponent(mainCanvas);
VBox subBox = new VBox();
displaySP.setRightComponent(subBox);
HBox carBox = new HBox();
subBox.myAdd(carBox,1);
carCanvas = A3SubCanvas.createA3SubCanvas(200,200);
carCanvas.setPreferredSize(new Dimension(200,200));
carCanvas.setMinimumSize(new Dimension(20,20));
carBox.myAdd(carCanvas,1);
//VBox carInfoBox = new VBox();
//carBox.myAdd(carInfoBox,0);
//carInfoBox.myAdd(new JLabel("CAR:"),0);
//carEnergyL = new JLabel("Energy: 000");
//carInfoBox.myAdd(carEnergyL,0);
stdOutTA = new JTextArea(10,40);
stdOutTA.setEditable(false);
JScrollPane sp = new JScrollPane(stdOutTA);
sp.setPreferredSize(new Dimension(100,100));
sp.setMinimumSize(new Dimension(10,10));
displayAndStdOutSP.setBottomComponent(sp);
out = new JTextAreaOutputStream(stdOutTA,System.out);
PrintStream ps = new PrintStream(out,true);
System.setOut(ps);
System.setErr(ps);
//this.pack();
//this.setVisible(true);
updateLoadFrom();
}
|
diff --git a/src/java/net/sf/jabref/util/MassSetFieldAction.java b/src/java/net/sf/jabref/util/MassSetFieldAction.java
index 22f4bd41f..f1dfa1a9c 100644
--- a/src/java/net/sf/jabref/util/MassSetFieldAction.java
+++ b/src/java/net/sf/jabref/util/MassSetFieldAction.java
@@ -1,202 +1,211 @@
package net.sf.jabref.util;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Collection;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.sf.jabref.*;
import net.sf.jabref.undo.NamedCompound;
import com.jgoodies.forms.builder.ButtonBarBuilder;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
/**
* An Action for launching mass field.
*
* Functionality:
* * Defaults to selected entries, or all entries if none are selected.
* * Input field name
* * Either set field, or clear field.
*/
public class MassSetFieldAction extends MnemonicAwareAction {
private JabRefFrame frame;
private JDialog diag;
private JRadioButton all, selected, clear, set, rename;
private JTextField field, text, renameTo;
private JButton ok, cancel;
boolean cancelled = true;
private JCheckBox overwrite;
public MassSetFieldAction(JabRefFrame frame) {
putValue(NAME, "Set/clear/rename fields");
this.frame = frame;
}
private void createDialog() {
diag = new JDialog(frame, Globals.lang("Set/clear/rename fields"), true);
field = new JTextField();
text = new JTextField();
text.setEnabled(false);
renameTo = new JTextField();
renameTo.setEnabled(false);
ok = new JButton(Globals.lang("Ok"));
cancel = new JButton(Globals.lang("Cancel"));
all = new JRadioButton(Globals.lang("All entries"));
selected = new JRadioButton(Globals.lang("Selected entries"));
clear = new JRadioButton(Globals.lang("Clear fields"));
set = new JRadioButton(Globals.lang("Set fields"));
rename = new JRadioButton(Globals.lang("Rename field to:"));
rename.setToolTipText(Globals.lang("Move contents of a field into a field with a different name"));
set.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
// Entering a text is only relevant if we are setting, not clearing:
text.setEnabled(set.isSelected());
}
});
clear.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
// Overwrite protection makes no sense if we are clearing the field:
overwrite.setEnabled(!clear.isSelected());
}
});
rename.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
// Entering a text is only relevant if we are renaming
renameTo.setEnabled(rename.isSelected());
}
});
overwrite = new JCheckBox(Globals.lang("Overwrite existing field values"), true);
ButtonGroup bg = new ButtonGroup();
bg.add(all);
bg.add(selected);
bg = new ButtonGroup();
bg.add(clear);
bg.add(set);
bg.add(rename);
DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout(
"left:pref, 4dlu, fill:100dlu", ""));
builder.appendSeparator(Globals.lang("Field name"));
builder.append(Globals.lang("Field name"));
builder.append(field);
builder.nextLine();
builder.appendSeparator(Globals.lang("Include entries"));
builder.append(all, 3);
builder.nextLine();
builder.append(selected, 3);
builder.nextLine();
builder.appendSeparator(Globals.lang("New field value"));
builder.append(set);
builder.append(text);
builder.nextLine();
builder.append(clear);
builder.nextLine();
builder.append(rename);
builder.append(renameTo);
builder.nextLine();
builder.append(overwrite, 3);
ButtonBarBuilder bb = new ButtonBarBuilder();
bb.addGlue();
bb.addGridded(ok);
bb.addGridded(cancel);
bb.addGlue();
builder.getPanel().setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
diag.getContentPane().add(builder.getPanel(), BorderLayout.CENTER);
diag.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
diag.pack();
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
+ // Check if the user tries to rename multiple fields:
+ if (rename.isSelected()) {
+ String[] fields = getFieldNames(field.getText());
+ if (fields.length > 1) {
+ JOptionPane.showMessageDialog(diag, Globals.lang("You can only rename one field at a time"),
+ "", JOptionPane.ERROR_MESSAGE);
+ return; // Do not close the dialog.
+ }
+ }
cancelled = false;
diag.dispose();
}
});
AbstractAction cancelAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
cancelled = true;
diag.dispose();
}
};
cancel.addActionListener(cancelAction);
// Key bindings:
ActionMap am = builder.getPanel().getActionMap();
InputMap im = builder.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(Globals.prefs.getKey("Close dialog"), "close");
am.put("close", cancelAction);
}
private void prepareDialog(boolean selection) {
selected.setEnabled(selection);
if (selection)
selected.setSelected(true);
else
all.setSelected(true);
// Make sure one of the following ones is selected:
if (!set.isSelected() && !clear.isSelected() && !rename.isSelected())
set.setSelected(true);
}
public void actionPerformed(ActionEvent e) {
BasePanel bp = frame.basePanel();
if (bp == null)
return;
BibtexEntry[] entries = bp.getSelectedEntries();
// Lazy creation of the dialog:
if (diag == null)
createDialog();
cancelled = true;
prepareDialog(entries.length > 0);
Util.placeDialog(diag, frame);
diag.setVisible(true);
if (cancelled)
return;
Collection<BibtexEntry> entryList;
// If all entries should be treated, change the entries array:
if (all.isSelected())
entryList = bp.database().getEntries();
else
entryList = Arrays.asList(entries);
String toSet = text.getText();
if (toSet.length() == 0)
toSet = null;
String[] fields = getFieldNames(field.getText().trim().toLowerCase());
NamedCompound ce = new NamedCompound(Globals.lang("Set field"));
if (rename.isSelected()) {
if (fields.length > 1) {
// TODO: message: can only rename a single field
}
else {
ce.addEdit(Util.massRenameField(entryList, fields[0], renameTo.getText(),
overwrite.isSelected()));
}
} else {
for (int i = 0; i < fields.length; i++) {
ce.addEdit(Util.massSetField(entryList, fields[i],
set.isSelected() ? toSet : null,
overwrite.isSelected()));
}
}
ce.end();
bp.undoManager.addEdit(ce);
bp.markBaseChanged();
}
private String[] getFieldNames(String s) {
return s.split("[^a-z]");
}
}
| true | true | private void createDialog() {
diag = new JDialog(frame, Globals.lang("Set/clear/rename fields"), true);
field = new JTextField();
text = new JTextField();
text.setEnabled(false);
renameTo = new JTextField();
renameTo.setEnabled(false);
ok = new JButton(Globals.lang("Ok"));
cancel = new JButton(Globals.lang("Cancel"));
all = new JRadioButton(Globals.lang("All entries"));
selected = new JRadioButton(Globals.lang("Selected entries"));
clear = new JRadioButton(Globals.lang("Clear fields"));
set = new JRadioButton(Globals.lang("Set fields"));
rename = new JRadioButton(Globals.lang("Rename field to:"));
rename.setToolTipText(Globals.lang("Move contents of a field into a field with a different name"));
set.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
// Entering a text is only relevant if we are setting, not clearing:
text.setEnabled(set.isSelected());
}
});
clear.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
// Overwrite protection makes no sense if we are clearing the field:
overwrite.setEnabled(!clear.isSelected());
}
});
rename.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
// Entering a text is only relevant if we are renaming
renameTo.setEnabled(rename.isSelected());
}
});
overwrite = new JCheckBox(Globals.lang("Overwrite existing field values"), true);
ButtonGroup bg = new ButtonGroup();
bg.add(all);
bg.add(selected);
bg = new ButtonGroup();
bg.add(clear);
bg.add(set);
bg.add(rename);
DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout(
"left:pref, 4dlu, fill:100dlu", ""));
builder.appendSeparator(Globals.lang("Field name"));
builder.append(Globals.lang("Field name"));
builder.append(field);
builder.nextLine();
builder.appendSeparator(Globals.lang("Include entries"));
builder.append(all, 3);
builder.nextLine();
builder.append(selected, 3);
builder.nextLine();
builder.appendSeparator(Globals.lang("New field value"));
builder.append(set);
builder.append(text);
builder.nextLine();
builder.append(clear);
builder.nextLine();
builder.append(rename);
builder.append(renameTo);
builder.nextLine();
builder.append(overwrite, 3);
ButtonBarBuilder bb = new ButtonBarBuilder();
bb.addGlue();
bb.addGridded(ok);
bb.addGridded(cancel);
bb.addGlue();
builder.getPanel().setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
diag.getContentPane().add(builder.getPanel(), BorderLayout.CENTER);
diag.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
diag.pack();
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelled = false;
diag.dispose();
}
});
AbstractAction cancelAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
cancelled = true;
diag.dispose();
}
};
cancel.addActionListener(cancelAction);
// Key bindings:
ActionMap am = builder.getPanel().getActionMap();
InputMap im = builder.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(Globals.prefs.getKey("Close dialog"), "close");
am.put("close", cancelAction);
}
| private void createDialog() {
diag = new JDialog(frame, Globals.lang("Set/clear/rename fields"), true);
field = new JTextField();
text = new JTextField();
text.setEnabled(false);
renameTo = new JTextField();
renameTo.setEnabled(false);
ok = new JButton(Globals.lang("Ok"));
cancel = new JButton(Globals.lang("Cancel"));
all = new JRadioButton(Globals.lang("All entries"));
selected = new JRadioButton(Globals.lang("Selected entries"));
clear = new JRadioButton(Globals.lang("Clear fields"));
set = new JRadioButton(Globals.lang("Set fields"));
rename = new JRadioButton(Globals.lang("Rename field to:"));
rename.setToolTipText(Globals.lang("Move contents of a field into a field with a different name"));
set.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
// Entering a text is only relevant if we are setting, not clearing:
text.setEnabled(set.isSelected());
}
});
clear.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
// Overwrite protection makes no sense if we are clearing the field:
overwrite.setEnabled(!clear.isSelected());
}
});
rename.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
// Entering a text is only relevant if we are renaming
renameTo.setEnabled(rename.isSelected());
}
});
overwrite = new JCheckBox(Globals.lang("Overwrite existing field values"), true);
ButtonGroup bg = new ButtonGroup();
bg.add(all);
bg.add(selected);
bg = new ButtonGroup();
bg.add(clear);
bg.add(set);
bg.add(rename);
DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout(
"left:pref, 4dlu, fill:100dlu", ""));
builder.appendSeparator(Globals.lang("Field name"));
builder.append(Globals.lang("Field name"));
builder.append(field);
builder.nextLine();
builder.appendSeparator(Globals.lang("Include entries"));
builder.append(all, 3);
builder.nextLine();
builder.append(selected, 3);
builder.nextLine();
builder.appendSeparator(Globals.lang("New field value"));
builder.append(set);
builder.append(text);
builder.nextLine();
builder.append(clear);
builder.nextLine();
builder.append(rename);
builder.append(renameTo);
builder.nextLine();
builder.append(overwrite, 3);
ButtonBarBuilder bb = new ButtonBarBuilder();
bb.addGlue();
bb.addGridded(ok);
bb.addGridded(cancel);
bb.addGlue();
builder.getPanel().setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
diag.getContentPane().add(builder.getPanel(), BorderLayout.CENTER);
diag.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
diag.pack();
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Check if the user tries to rename multiple fields:
if (rename.isSelected()) {
String[] fields = getFieldNames(field.getText());
if (fields.length > 1) {
JOptionPane.showMessageDialog(diag, Globals.lang("You can only rename one field at a time"),
"", JOptionPane.ERROR_MESSAGE);
return; // Do not close the dialog.
}
}
cancelled = false;
diag.dispose();
}
});
AbstractAction cancelAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
cancelled = true;
diag.dispose();
}
};
cancel.addActionListener(cancelAction);
// Key bindings:
ActionMap am = builder.getPanel().getActionMap();
InputMap im = builder.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(Globals.prefs.getKey("Close dialog"), "close");
am.put("close", cancelAction);
}
|
diff --git a/src/java/axiom/scripting/rhino/RhinoCore.java b/src/java/axiom/scripting/rhino/RhinoCore.java
index ac63d6c..cfeeea9 100755
--- a/src/java/axiom/scripting/rhino/RhinoCore.java
+++ b/src/java/axiom/scripting/rhino/RhinoCore.java
@@ -1,1284 +1,1284 @@
/*
* Helma License Notice
*
* The contents of this file are subject to the Helma License
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://adele.helma.org/download/helma/license.txt
*
* Copyright 1998-2003 Helma Software. All Rights Reserved.
*
* $RCSfile: RhinoCore.java,v $
* $Author: hannes $
* $Revision: 1.90 $
* $Date: 2006/05/12 13:30:47 $
*/
/*
* Modified by:
*
* Axiom Software Inc., 11480 Commerce Park Drive, Third Floor, Reston, VA 20191 USA
* email: [email protected]
*/
package axiom.scripting.rhino;
import org.mozilla.javascript.*;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;
import axiom.framework.ErrorReporter;
import axiom.framework.core.*;
import axiom.framework.repository.Resource;
import axiom.objectmodel.*;
import axiom.objectmodel.db.DbMapping;
import axiom.objectmodel.db.DbSource;
import axiom.scripting.*;
import axiom.scripting.rhino.extensions.*;
import axiom.scripting.rhino.extensions.activex.ActiveX;
import axiom.util.CacheMap;
import axiom.util.ResourceProperties;
import axiom.util.SystemMap;
import axiom.util.TALTemplate;
import axiom.util.WeakCacheMap;
import axiom.util.WrappedMap;
import java.io.*;
import java.text.*;
import java.util.*;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
/**
* This is the implementation of ScriptingEnvironment for the Mozilla Rhino EcmaScript interpreter.
*/
public final class RhinoCore implements ScopeProvider {
// the application we're running in
public final Application app;
// the global object
GlobalObject global;
// caching table for JavaScript object wrappers
CacheMap wrappercache;
// table containing JavaScript prototypes
Hashtable prototypes;
// timestamp of last type update
volatile long lastUpdate = 0;
// the wrap factory
WrapFactory wrapper;
// the prototype for AxiomObject
ScriptableObject axiomObjectProto;
// the prototype for FileObject
ScriptableObject fileObjectProto;
// the prototype for ImageObject
ScriptableObject imageObjectProto;
// Any error that may have been found in global code
String globalError;
// dynamic portion of the type check sleep that grows
// as the app remains unchanged
long updateSnooze = 500;
// Prevent prototype resource checks from occuring
// upon every request, but rather, the resource update checks should occur by demand
private boolean isInitialized = false;
/* tal migration
*
*/
static HashMap templates = new HashMap();
private static HashMap cache = new HashMap();
protected static String DEBUGGER_PROPERTY = "rhino.debugger";
/**
* Create a Rhino evaluator for the given application and request evaluator.
*/
public RhinoCore(Application app) {
this.app = app;
wrappercache = new WeakCacheMap(500);
prototypes = new Hashtable();
Context context = Context.enter();
context.setLanguageVersion(170);
context.setCompileFunctionsWithDynamicScope(true);
context.setApplicationClassLoader(app.getClassLoader());
wrapper = new WrapMaker();
wrapper.setJavaPrimitiveWrap(false);
context.setWrapFactory(wrapper);
// Set default optimization level according to whether debugger is on
- int optLevel = "true".equals(app.getProperty(DEBUGGER_PROPERTY)) ? 0 : -1;
+ int optLevel = "true".equals(app.getProperty(DEBUGGER_PROPERTY)) ? -1 : 9;
String opt = app.getProperty("rhino.optlevel");
if (opt != null) {
try {
optLevel = Integer.parseInt(opt);
} catch (Exception ignore) {
app.logError(ErrorReporter.errorMsg(this.getClass(), "ctor")
+ "Invalid rhino optlevel: " + opt);
}
}
context.setOptimizationLevel(optLevel);
try {
// create global object
global = new GlobalObject(this, app, false);
// call the initStandardsObject in ImporterTopLevel so that
// importClass() and importPackage() are set up.
global.initStandardObjects(context, false);
global.init();
axiomObjectProto = AxiomObject.init(this);
fileObjectProto = FileObject.initFileProto(this);
imageObjectProto = ImageObject.initImageProto(this);
// Reference initialization
try {
new ReferenceObjCtor(this, Reference.init(this));
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "ctor")
+ "Could not add ctor for Reference", x);
}
// MultiValue initialization
try {
new MultiValueCtor(this, MultiValue.init(this));
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "ctor")
+ "Could not add ctor for MultiValue", x);
}
// use lazy loaded constructors for all extension objects that
// adhere to the ScriptableObject.defineClass() protocol
/*
* Changes made, namely:
*
* 1) Removed the File and Image objects in preference to the File/Image objects
* we built in house
* 2) Added the following objects to the Rhino scripting environment:
* LdapClient
* Filter (for specifying queries)
* Sort (for specifying the sort order of queries)
* DOMParser (for parsing xml into a dom object)
* XMLSerializer (for writing a dom object to an xml string)
*
*/
new LazilyLoadedCtor(global, "FtpClient",
"axiom.scripting.rhino.extensions.FtpObject", false);
new LazilyLoadedCtor(global, "LdapClient",
"axiom.scripting.rhino.extensions.LdapObject", false);
new LazilyLoadedCtor(global, "Filter",
"axiom.scripting.rhino.extensions.filter.FilterObject", false);
new LazilyLoadedCtor(global, "NativeFilter",
"axiom.scripting.rhino.extensions.filter.NativeFilterObject", false);
new LazilyLoadedCtor(global, "AndFilter",
"axiom.scripting.rhino.extensions.filter.AndFilterObject", false);
new LazilyLoadedCtor(global, "OrFilter",
"axiom.scripting.rhino.extensions.filter.OrFilterObject", false);
new LazilyLoadedCtor(global, "NotFilter",
"axiom.scripting.rhino.extensions.filter.NotFilterObject", false);
new LazilyLoadedCtor(global, "RangeFilter",
"axiom.scripting.rhino.extensions.filter.RangeFilterObject", false);
new LazilyLoadedCtor(global, "SearchFilter",
"axiom.scripting.rhino.extensions.filter.SearchFilterObject", false);
new LazilyLoadedCtor(global, "Sort",
"axiom.scripting.rhino.extensions.filter.SortObject", false);
ArrayList names = app.getDbNames();
for(int i = 0; i < names.size(); i++){
try{
String dbname = names.get(i).toString();
DbSource dbsource = app.getDbSource(dbname);
String hitsObject = dbsource.getProperty("hitsObject", null);
String hitsClass = dbsource.getProperty("hitsClass", null);
if(hitsObject != null && hitsClass != null){
new LazilyLoadedCtor(global, hitsObject,
hitsClass, false);
}
String filters = dbsource.getProperty("filters", null);
if(filters != null){
StringBuffer sb = new StringBuffer(filters);
int idx;
while ((idx = sb.indexOf("{")) > -1) {
sb.deleteCharAt(idx);
}
while ((idx = sb.indexOf("}")) > -1) {
sb.deleteCharAt(idx);
}
filters = sb.toString().trim();
String[] pairs = filters.split(",");
for (int j = 0; j < pairs.length; j++) {
String[] pair = pairs[j].split(":");
new LazilyLoadedCtor(global, pair[0].trim(),
pair[1].trim(), false);
}
}
}
catch(Exception e){
app.logError("Error during LazilyLoadedCtor initialization for external databases");
}
}
new LazilyLoadedCtor(global, "LuceneHits",
"axiom.scripting.rhino.extensions.LuceneHitsObject", false);
new LazilyLoadedCtor(global, "TopDocs",
"axiom.scripting.rhino.extensions.TopDocsObject", false);
new LazilyLoadedCtor(global, "DOMParser",
"axiom.scripting.rhino.extensions.DOMParser", false);
new LazilyLoadedCtor(global, "XMLSerializer",
"axiom.scripting.rhino.extensions.XMLSerializer", false);
if ("true".equalsIgnoreCase(app.getProperty(RhinoCore.DEBUGGER_PROPERTY))) {
new LazilyLoadedCtor(global, "Debug",
"axiom.scripting.rhino.debug.Debug", false);
}
MailObject.init(global, app.getProperties());
// defining the ActiveX scriptable object for exposure of its API in Axiom
ScriptableObject.defineClass(global, ActiveX.class);
// add some convenience functions to string, date and number prototypes
Scriptable stringProto = ScriptableObject.getClassPrototype(global, "String");
stringProto.put("trim", stringProto, new StringTrim());
Scriptable dateProto = ScriptableObject.getClassPrototype(global, "Date");
dateProto.put("format", dateProto, new DateFormat());
Scriptable numberProto = ScriptableObject.getClassPrototype(global, "Number");
numberProto.put("format", numberProto, new NumberFormat());
initialize();
loadTemplates(app);
} catch (Exception e) {
System.err.println("Cannot initialize interpreter");
System.err.println("Error: " + e);
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
Context.exit();
}
}
/**
* Initialize the evaluator, making sure the minimum type information
* necessary to bootstrap the rest is parsed.
*/
private synchronized void initialize() {
Collection protos = app.getPrototypes();
for (Iterator i = protos.iterator(); i.hasNext();) {
Prototype proto = (Prototype) i.next();
initPrototype(proto);
// getPrototype(proto.getName());
}
// always fully initialize global prototype, because
// we always need it and there's no chance to trigger
// creation on demand.
getPrototype("global");
}
/**
* Initialize a prototype info without compiling its script files.
*
* @param prototype the prototype to be created
*/
private synchronized void initPrototype(Prototype prototype) {
String name = prototype.getName();
String lowerCaseName = prototype.getLowerCaseName();
TypeInfo type = (TypeInfo) prototypes.get(lowerCaseName);
// check if the prototype info exists already
ScriptableObject op = (type == null) ? null : type.objProto;
// if prototype info doesn't exist (i.e. is a standard prototype
// built by AxiomExtension), create it.
if (op == null) {
if ("global".equals(lowerCaseName)) {
op = global;
} else if ("axiomobject".equals(lowerCaseName)) {
op = axiomObjectProto;
} else if ("file".equals(lowerCaseName)) {
op = fileObjectProto;
} else if ("image".equals(lowerCaseName)) {
op = imageObjectProto;
} else {
op = new AxiomObject(name, this);
}
registerPrototype(prototype, op);
}
// Register a constructor for all types except global.
// This will first create a new prototyped AxiomObject and then calls
// the actual (scripted) constructor on it.
if (!"global".equals(lowerCaseName)) {
if ("file".equals(lowerCaseName)) {
try {
new FileObjectCtor(this, op);
op.setParentScope(global);
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "initPrototype")
+ "Could not add ctor for " + name, x);
}
} else if ("image".equals(lowerCaseName)) {
try {
new ImageObjectCtor(this, op);
op.setParentScope(global);
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "initPrototype")
+ "Could not add ctor for " + name, x);
}
} else {
try {
new AxiomObjectCtor(name, this, op);
op.setParentScope(global);
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "initPrototype")
+ "Could not add ctor for " + name, x);
}
}
}
}
/**
* Set up a prototype, parsing and compiling all its script files.
*
* @param type the info, containing the object proto, last update time and
* the set of compiled functions properties
*/
private synchronized void evaluatePrototype(TypeInfo type) {
type.prepareCompilation();
Prototype prototype = type.frameworkProto;
// set the parent prototype in case it hasn't been done before
// or it has changed...
setParentPrototype(prototype, type);
type.error = null;
if ("global".equals(prototype.getLowerCaseName())) {
globalError = null;
}
// loop through the prototype's code elements and evaluate them
ArrayList code = prototype.getCodeResourceList();
final int size = code.size();
for (int i = 0; i < size; i++) {
evaluate(type, (Resource) code.get(i));
}
loadCompiledCode(type, prototype.getName());
type.commitCompilation();
}
private void loadTemplates(Application app) throws Exception {
HashMap templSources = getAllTemplateSources();
Iterator keys = templSources.keySet().iterator();
while (keys.hasNext()) {
String name = keys.next().toString();
retrieveDocument(app, name);
}
}
public Object retrieveDocument(Application app, String name)
throws Exception {
HashMap map = retrieveTemplatesForApp(app);
Object xml = null;
Resource templateSource = (Resource) findTemplateSource(name, app);
if (templateSource == null) {
// throw new Exception("ERROR in TAL(): Could not find the TAL template file indicated by '" + name + "'.");
return null;
}
TALTemplate template = null;
synchronized (map) {
if ((template = getTemplateByName(map, name)) != null && template.getLastModified() >= templateSource.lastModified()) {
xml = template.getDocument();
} else {
xml = ((Resource) templateSource).getContent().trim();
if (template != null) {
template.setDocument(xml);
template.setLastModified(templateSource.lastModified());
} else {
map.put(name, new TALTemplate(name, xml, templateSource.lastModified()));
}
}
}
return xml;
}
private static TALTemplate getTemplateByName(HashMap map, String name) {
return (TALTemplate) map.get(name);
}
private static HashMap retrieveTemplatesForApp(Application app) {
HashMap map = null;
synchronized (templates) {
Object ret = templates.get(app);
if (ret != null)
map = (HashMap) ret;
else {
map = new HashMap();
templates.put(app, map);
}
}
return map;
}
public static Object findTemplateSource(String name, Application app) throws Exception {
Resource resource = (Resource) cache.get(name);
if (resource == null || !resource.exists()) {
resource = null;
try {
int pos = name.indexOf(':');
Prototype prototype = app.getPrototypeByName(name.substring(0, pos));
name = name.substring(pos + 1) + ".tal";
if (prototype != null) {
resource = scanForResource(prototype, name);
}
} catch (Exception ex) {
throw new Exception("Unable to resolve source: " + name + " " + ex);
}
}
return resource;
}
private static Resource scanForResource(Prototype prototype, String name) throws Exception {
Resource resource = null;
// scan for resources with extension .tal:
Resource[] resources = prototype.getResources();
for (int i = 0; i < resources.length; i++) {
Resource res = resources[i];
if (res.exists() && res.getShortName().equals(name)) {
cache.put(name, res);
resource = res;
break;
}
}
return resource;
}
public HashMap getAllTemplateSources() throws Exception {
HashMap templSources = new HashMap();
ArrayList mylist = new ArrayList(app.getPrototypes());
final int size = mylist.size();
for (int i = 0; i < size; i++) {
Prototype prototype = (Prototype) mylist.get(i);
String proto = prototype.getName() + ":";
Resource[] resources = prototype.getResources();
final int length = resources.length;
for (int j = 0; j < length; j++) {
if (resources[j].exists() && resources[j].getShortName().endsWith(".tal")) {
templSources.put(proto + resources[j].getBaseName(), resources[j]);
}
}
}
return templSources;
}
/*
*
*
*
*
*
*/
/**
* Set the parent prototype on the ObjectPrototype.
*
* @param prototype the prototype spec
* @param type the prototype object info
*/
private void setParentPrototype(Prototype prototype, TypeInfo type) {
String name = prototype.getName();
String lowerCaseName = prototype.getLowerCaseName();
if (!"global".equals(lowerCaseName) && !"axiomobject".equals(lowerCaseName)) {
// get the prototype's prototype if possible and necessary
TypeInfo parentType = null;
Prototype parent = prototype.getParentPrototype();
if (parent != null) {
// see if parent prototype is already registered. if not, register it
parentType = getPrototypeInfo(parent.getName());
}
if (parentType == null && !app.isJavaPrototype(name)) {
// FIXME: does this ever occur?
parentType = getPrototypeInfo("axiomobject");
}
type.setParentType(parentType);
}
}
/**
* This method is called before an execution context is entered to let the
* engine know it should update its prototype information. The update policy
* here is to check for update those prototypes which already have been compiled
* before. Others will be updated/compiled on demand.
*/
public synchronized void updatePrototypes(boolean forceUpdate) throws IOException {
if ((System.currentTimeMillis() - lastUpdate) < 1000L + updateSnooze) {
return;
}
// We are no longer checking for prototype updates on a
// per request basis, but rather only when there is an explicit request to update
// the prototype resource mappings
if (!forceUpdate && this.isInitialized) {
return;
}
// init prototypes and/or update prototype checksums
app.typemgr.checkPrototypes();
// get a collection of all prototypes (code directories)
Collection protos = app.getPrototypes();
// in order to respect inter-prototype dependencies, we try to update
// the global prototype before all other prototypes, and parent
// prototypes before their descendants.
HashSet checked = new HashSet(protos.size() * 2);
TypeInfo type = (TypeInfo) prototypes.get("global");
if (type != null) {
updatePrototype(type, checked);
}
for (Iterator i = protos.iterator(); i.hasNext();) {
Prototype proto = (Prototype) i.next();
if (checked.contains(proto)) {
continue;
}
type = (TypeInfo) prototypes.get(proto.getLowerCaseName());
if (type == null) {
// a prototype we don't know anything about yet. Init local update info.
initPrototype(proto);
}
type = (TypeInfo) prototypes.get(proto.getLowerCaseName());
if (type != null && (type.lastUpdate > -1 || !this.isInitialized)) {
// only need to update prototype if it has already been initialized.
// otherwise, this will be done on demand.
updatePrototype(type, checked);
}
}
this.isInitialized = true;
//lastUpdate = System.currentTimeMillis();
// max updateSnooze is 4 seconds, reached after 66.6 idle minutes
//long newSnooze = (lastUpdate - app.typemgr.getLastCodeUpdate()) / 1000;
//updateSnooze = Math.min(4000, Math.max(0, newSnooze));
}
/**
* Check one prototype for updates. Used by <code>upatePrototypes()</code>.
*
* @param type the type info to check
* @param checked a set of prototypes that have already been checked
*/
private void updatePrototype(TypeInfo type, HashSet checked) {
// first, remember prototype as updated
checked.add(type.frameworkProto);
if (type.parentType != null &&
!checked.contains(type.parentType.frameworkProto)) {
updatePrototype(type.getParentType(), checked);
}
// let the prototype check if its resources have changed
type.frameworkProto.checkForUpdates();
// and re-evaluate if necessary
if (type.needsUpdate() || !this.isInitialized) {
evaluatePrototype(type);
}
}
/**
* A version of getPrototype() that retrieves a prototype and checks
* if it is valid, i.e. there were no errors when compiling it. If
* invalid, a ScriptingException is thrown.
*/
public Scriptable getValidPrototype(String protoName) {
if (globalError != null) {
throw new EvaluatorException(globalError);
}
TypeInfo type = getPrototypeInfo(protoName);
if (type != null) {
if (type.hasError()) {
throw new EvaluatorException(type.getError());
}
return type.objProto;
}
return null;
}
/**
* Get the object prototype for a prototype name and initialize/update it
* if necessary. The policy here is to update the prototype only if it
* hasn't been updated before, otherwise we assume it already was updated
* by updatePrototypes(), which is called for each request.
*/
public Scriptable getPrototype(String protoName) {
TypeInfo type = getPrototypeInfo(protoName);
return type == null ? null : type.objProto;
}
/**
* Get an array containing the property ids of all properties that were
* compiled from scripts for the given prototype.
*
* @param protoName the name of the prototype
* @return an array containing all compiled properties of the given prototype
*/
public Map getPrototypeProperties(String protoName) {
TypeInfo type = getPrototypeInfo(protoName);
SystemMap map = new SystemMap();
Iterator it = type.compiledProperties.iterator();
while(it.hasNext()) {
Object key = it.next();
if (key instanceof String)
map.put(key, type.objProto.get((String) key, type.objProto));
}
return map;
}
/**
* Private helper function that retrieves a prototype's TypeInfo
* and creates it if not yet created. This is used by getPrototype() and
* getValidPrototype().
*/
private TypeInfo getPrototypeInfo(String protoName) {
if (protoName == null) {
return null;
}
TypeInfo type = (TypeInfo) prototypes.get(protoName.toLowerCase());
// if type exists and hasn't been evaluated (used) yet, evaluate it now.
// otherwise, it has already been evaluated for this request by updatePrototypes(),
// which is called before a request is handled.
if ((type != null) && (type.lastUpdate == -1)) {
type.frameworkProto.checkForUpdates();
if (type.needsUpdate()) {
evaluatePrototype(type);
}
}
return type;
}
/**
* Register an object prototype for a prototype name.
*/
private TypeInfo registerPrototype(Prototype proto, ScriptableObject op) {
TypeInfo type = new TypeInfo(proto, op);
prototypes.put(proto.getLowerCaseName(), type);
return type;
}
/**
* Check if an object has a function property (public method if it
* is a java object) with that name.
*/
public boolean hasFunction(String protoname, String fname) {
// throws EvaluatorException if type has a syntax error
Scriptable op = getValidPrototype(protoname);
// if this is an untyped object return false
if (op == null) {
return false;
}
return ScriptableObject.getProperty(op, fname) instanceof Function;
}
/**
* Convert an input argument from Java to the scripting runtime
* representation.
*/
public Object processXmlRpcArgument (Object what) throws Exception {
if (what == null)
return null;
if (what instanceof Vector) {
Vector v = (Vector) what;
Object[] a = v.toArray();
for (int i=0; i<a.length; i++) {
a[i] = processXmlRpcArgument(a[i]);
}
return Context.getCurrentContext().newArray(global, a);
}
if (what instanceof Hashtable) {
Hashtable t = (Hashtable) what;
for (Enumeration e=t.keys(); e.hasMoreElements(); ) {
Object key = e.nextElement();
t.put(key, processXmlRpcArgument(t.get(key)));
}
return Context.toObject(new SystemMap(t), global);
}
if (what instanceof String)
return what;
if (what instanceof Number)
return what;
if (what instanceof Boolean)
return what;
if (what instanceof Date) {
Date d = (Date) what;
Object[] args = { new Long(d.getTime()) };
return Context.getCurrentContext().newObject(global, "Date", args);
}
return Context.toObject(what, global);
}
/**
* convert a JavaScript Object object to a generic Java object stucture.
*/
public Object processXmlRpcResponse (Object what) throws Exception {
// unwrap if argument is a Wrapper
if (what instanceof Wrapper) {
what = ((Wrapper) what).unwrap();
}
if (what instanceof NativeObject) {
NativeObject no = (NativeObject) what;
Object[] ids = no.getIds();
Hashtable ht = new Hashtable(ids.length*2);
for (int i=0; i<ids.length; i++) {
if (ids[i] instanceof String) {
String key = (String) ids[i];
Object o = no.get(key, no);
if (o != null) {
ht.put(key, processXmlRpcResponse(o));
}
}
}
what = ht;
} else if (what instanceof NativeArray) {
NativeArray na = (NativeArray) what;
Number n = (Number) na.get("length", na);
int l = n.intValue();
Vector retval = new Vector(l);
for (int i=0; i<l; i++) {
retval.add(i, processXmlRpcResponse(na.get(i, na)));
}
what = retval;
} else if (what instanceof Map) {
Map map = (Map) what;
Hashtable ht = new Hashtable(map.size()*2);
for (Iterator it=map.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
ht.put(entry.getKey().toString(),
processXmlRpcResponse(entry.getValue()));
}
what = ht;
} else if (what instanceof Number) {
Number n = (Number) what;
if (what instanceof Float || what instanceof Long) {
what = new Double(n.doubleValue());
} else if (!(what instanceof Double)) {
what = new Integer(n.intValue());
}
} else if (what instanceof Scriptable) {
Scriptable s = (Scriptable) what;
if ("Date".equals(s.getClassName())) {
what = new Date((long) ScriptRuntime.toNumber(s));
}
}
return what;
}
/**
* Return the application we're running in
*/
public Application getApplication() {
return app;
}
/**
* Get a Script wrapper for any given object. If the object implements the IPathElement
* interface, the getPrototype method will be used to retrieve the name of the prototype
* to use. Otherwise, a Java-Class-to-Script-Prototype mapping is consulted.
*/
public Scriptable getElementWrapper(Object e) {
WeakReference ref = (WeakReference) wrappercache.get(e);
Scriptable wrapper = ref == null ? null : (Scriptable) ref.get();
if (wrapper == null) {
// Gotta find out the prototype name to use for this object...
String prototypeName = app.getPrototypeName(e);
Scriptable op = getPrototype(prototypeName);
if (op == null) {
// no prototype found, return an unscripted wrapper
wrapper = new NativeJavaObject(global, e, e.getClass());
} else {
wrapper = new JavaObject(global, e, prototypeName, op, this);
}
wrappercache.put(e, new WeakReference(wrapper));
}
return wrapper;
}
/**
* Get a script wrapper for an instance of axiom.objectmodel.INode
*/
public Scriptable getNodeWrapper(INode n) {
if (n == null) {
return null;
}
AxiomObject esn = (AxiomObject) wrappercache.get(n);
if (esn == null) {
String protoname = n.getPrototype();
Scriptable op = getValidPrototype(protoname);
// no prototype found for this node
if (op == null) {
// maybe this object has a prototype name that has been
// deleted, but the storage layer was able to set a
// DbMapping matching the relational table the object
// was fetched from.
DbMapping dbmap = n.getDbMapping();
if (dbmap != null && (protoname = dbmap.getTypeName()) != null) {
op = getValidPrototype(protoname);
}
// if not found, fall back to AxiomObject prototype
if (op == null) {
protoname = "AxiomObject";
op = getValidPrototype("AxiomObject");
}
}
if ("File".equals(protoname)) {
esn = new FileObject("File", this, n, op);
} else if ("Image".equals(protoname)) {
esn = new ImageObject("Image", this, n, op);
} else {
esn = new AxiomObject(protoname, this, n, op);
}
wrappercache.put(n, esn);
}
return esn;
}
protected String postProcessHref(Object obj, String protoName, String basicHref)
throws UnsupportedEncodingException, IOException {
// check if the app.properties specify a href-function to post-process the
// basic href.
String hrefFunction = app.getProperty("hrefFunction", null);
if (hrefFunction != null) {
Object handler = obj;
String proto = protoName;
while (handler != null) {
if (hasFunction(proto, hrefFunction)) {
// get the currently active rhino engine and invoke the function
Context cx = Context.getCurrentContext();
RhinoEngine engine = (RhinoEngine) cx.getThreadLocal("engine");
Object result;
try {
result = engine.invoke(handler, hrefFunction,
new Object[] { basicHref },
ScriptingEngine.ARGS_WRAP_DEFAULT,
false);
} catch (ScriptingException x) {
throw new EvaluatorException("Error in hrefFunction: " + x);
}
if (result == null) {
throw new EvaluatorException("hrefFunction " + hrefFunction +
" returned null");
}
basicHref = result.toString();
break;
}
handler = app.getParentElement(handler);
proto = app.getPrototypeName(handler);
}
}
return basicHref;
}
////////////////////////////////////////////////
// private evaluation/compilation methods
////////////////////////////////////////////////
private synchronized void loadCompiledCode(TypeInfo type, String protoname) {
// get the current context
Context cx = Context.getCurrentContext();
// unregister the per-thread scope while evaluating
Object threadScope = cx.getThreadLocal("threadscope");
cx.removeThreadLocal("threadscope");
try{
Script compiled = (Script) Class.forName("axiom.compiled."+protoname).newInstance();
compiled.exec(cx, type.objProto);
}catch(ClassNotFoundException e){
// no compiled code loaded, ignore
}catch(Exception e){
app.logError(ErrorReporter.errorMsg(this.getClass(), "loadCompiledCode")
+ "Error loading compiled js for prototype: " + protoname, e);
// mark prototype as broken
if (type.error == null) {
type.error = e.getMessage();
if (type.error == null || e instanceof EcmaError) {
type.error = e.toString();
}
if ("global".equals(type.frameworkProto.getLowerCaseName())) {
globalError = type.error;
}
wrappercache.clear();
}
}finally{
if (threadScope != null) {
cx.putThreadLocal("threadscope", threadScope);
}
}
}
private synchronized void evaluate (TypeInfo type, Resource code) {
// get the current context
Context cx = Context.getCurrentContext();
// unregister the per-thread scope while evaluating
Object threadScope = cx.getThreadLocal("threadscope");
cx.removeThreadLocal("threadscope");
String sourceName = code.getName();
Reader reader = null;
try {
Scriptable op = type.objProto;
// do the update, evaluating the file
if (sourceName.endsWith(".js")) {
reader = new InputStreamReader(code.getInputStream());
} else if (sourceName.endsWith(".tal")) {
reader = new StringReader(ResourceConverter.convertTal(code));
}
cx.evaluateReader(op, reader, sourceName, 1, null);
} catch (Exception e) {
app.logError(ErrorReporter.errorMsg(this.getClass(), "evaluate")
+ "Error parsing file " + sourceName, e);
// mark prototype as broken
if (type.error == null) {
type.error = e.getMessage();
if (type.error == null || e instanceof EcmaError) {
type.error = e.toString();
}
if ("global".equals(type.frameworkProto.getLowerCaseName())) {
globalError = type.error;
}
wrappercache.clear();
}
// e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {
}
}
if (threadScope != null) {
cx.putThreadLocal("threadscope", threadScope);
}
}
}
/**
* Return the global scope of this RhinoCore.
*/
public Scriptable getScope() {
return global;
}
public GlobalObject getGlobal(){
return global;
}
/**
* TypeInfo helper class
*/
class TypeInfo {
// the framework prototype object
Prototype frameworkProto;
// the JavaScript prototype for this type
ScriptableObject objProto;
// timestamp of last update. This is -1 so even an empty prototype directory
// (with lastUpdate == 0) gets evaluated at least once, which is necessary
// to get the prototype chain set.
long lastUpdate = -1;
// the parent prototype info
TypeInfo parentType;
// a set of property keys that were in script compilation.
// Used to decide which properties should be removed if not renewed.
Set compiledProperties;
// a set of property keys that were present before first script compilation
final Set predefinedProperties;
String error;
public TypeInfo(Prototype proto, ScriptableObject op) {
frameworkProto = proto;
objProto = op;
// remember properties already defined on this object prototype
compiledProperties = new HashSet();
predefinedProperties = new HashSet();
Object[] keys = op.getAllIds();
for (int i = 0; i < keys.length; i++) {
predefinedProperties.add(keys[i].toString());
}
}
/**
* If prototype implements PropertyRecorder tell it to start
* registering property puts.
*/
public void prepareCompilation() {
if (objProto instanceof PropertyRecorder) {
((PropertyRecorder) objProto).startRecording();
}
}
/**
* Compilation has been completed successfully - switch over to code
* from temporary prototype, removing properties that haven't been
* renewed.
*/
public void commitCompilation() {
// loop through properties defined on the prototype object
// and remove thos properties which haven't been renewed during
// this compilation/evaluation pass.
if (objProto instanceof PropertyRecorder) {
PropertyRecorder recorder = (PropertyRecorder) objProto;
recorder.stopRecording();
Set changedProperties = recorder.getChangeSet();
recorder.clearChangeSet();
// ignore all properties that were defined before we started
// compilation. We won't manage these properties, even
// if they were set during compilation.
changedProperties.removeAll(predefinedProperties);
// remove all renewed properties from the previously compiled
// property names so we can remove those properties that were not
// renewed in this compilation
compiledProperties.removeAll(changedProperties);
Iterator it = compiledProperties.iterator();
while (it.hasNext()) {
String key = (String) it.next();
try {
objProto.setAttributes(key, 0);
objProto.delete(key);
} catch (Exception px) {
System.err.println("Error unsetting property "+key+" on "+
frameworkProto.getName());
}
}
// update compiled properties
compiledProperties = changedProperties;
}
// mark this type as updated
lastUpdate = frameworkProto.lastCodeUpdate();
// If this prototype defines a postCompile() function, call it
Context cx = Context.getCurrentContext();
try {
Object fObj = ScriptableObject.getProperty(objProto,
"onCodeUpdate");
if (fObj instanceof Function) {
Object[] args = {frameworkProto.getName()};
((Function) fObj).call(cx, global, objProto, args);
}
} catch (Exception x) {
app.logError(ErrorReporter.errorMsg(this.getClass(), "commitCompilation")
+ "Exception in "+frameworkProto.getName()+
".onCodeUpdate(): " + x, x);
}
}
public boolean needsUpdate() {
return frameworkProto.lastCodeUpdate() > lastUpdate;
}
public void setParentType(TypeInfo type) {
parentType = type;
if (type == null) {
objProto.setPrototype(null);
} else {
objProto.setPrototype(type.objProto);
}
}
public TypeInfo getParentType() {
return parentType;
}
public boolean hasError() {
TypeInfo p = this;
while (p != null) {
if (p.error != null)
return true;
p = p.parentType;
}
return false;
}
public String getError() {
TypeInfo p = this;
while (p != null) {
if (p.error != null)
return p.error;
p = p.parentType;
}
return null;
}
public String toString() {
return ("TypeInfo[" + frameworkProto + "," + new Date(lastUpdate) + "]");
}
}
/**
* Object wrapper class
*/
class WrapMaker extends WrapFactory {
public Object wrap(Context cx, Scriptable scope, Object obj, Class staticType) {
// Wrap Nodes
if (obj instanceof INode) {
return getNodeWrapper((INode) obj);
}
// Masquerade SystemMap and WrappedMap as native JavaScript objects
if (obj instanceof SystemMap || obj instanceof WrappedMap) {
return new MapWrapper((Map) obj, RhinoCore.this);
}
// Convert java.util.Date objects to JavaScript Dates
if (obj instanceof Date) {
Object[] args = { new Long(((Date) obj).getTime()) };
try {
return cx.newObject(global, "Date", args);
} catch (JavaScriptException nafx) {
return obj;
}
}
// Wrap scripted Java objects
if (obj != null && app.getPrototypeName(obj) != null) {
return getElementWrapper(obj);
}
return super.wrap(cx, scope, obj, staticType);
}
public Scriptable wrapNewObject(Context cx, Scriptable scope, Object obj) {
// System.err.println ("N-Wrapping: "+obj);
if (obj instanceof INode) {
return getNodeWrapper((INode) obj);
}
if (obj != null && app.getPrototypeName(obj) != null) {
return getElementWrapper(obj);
}
return super.wrapNewObject(cx, scope, obj);
}
}
class StringTrim extends BaseFunction {
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
String str = thisObj.toString();
return str.trim();
}
}
class DateFormat extends BaseFunction {
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
Date date = new Date((long) ScriptRuntime.toNumber(thisObj));
SimpleDateFormat df;
if (args.length > 0 && args[0] != Undefined.instance && args[0] != null) {
if (args.length > 1 && args[1] instanceof NativeJavaObject) {
Object locale = ((NativeJavaObject) args[1]).unwrap();
if (locale instanceof Locale) {
df = new SimpleDateFormat(args[0].toString(), (Locale) locale);
} else {
throw new IllegalArgumentException("Second argument to Date.format() not a java.util.Locale: " +
locale.getClass());
}
} else {
df = new SimpleDateFormat(args[0].toString());
}
} else {
df = new SimpleDateFormat();
}
return df.format(date);
}
}
class NumberFormat extends BaseFunction {
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
DecimalFormat df;
if (args.length > 0 && args[0] != Undefined.instance) {
df = new DecimalFormat(args[0].toString());
} else {
df = new DecimalFormat("#,##0.00");
}
return df.format(ScriptRuntime.toNumber(thisObj));
}
}
}
| true | true | public RhinoCore(Application app) {
this.app = app;
wrappercache = new WeakCacheMap(500);
prototypes = new Hashtable();
Context context = Context.enter();
context.setLanguageVersion(170);
context.setCompileFunctionsWithDynamicScope(true);
context.setApplicationClassLoader(app.getClassLoader());
wrapper = new WrapMaker();
wrapper.setJavaPrimitiveWrap(false);
context.setWrapFactory(wrapper);
// Set default optimization level according to whether debugger is on
int optLevel = "true".equals(app.getProperty(DEBUGGER_PROPERTY)) ? 0 : -1;
String opt = app.getProperty("rhino.optlevel");
if (opt != null) {
try {
optLevel = Integer.parseInt(opt);
} catch (Exception ignore) {
app.logError(ErrorReporter.errorMsg(this.getClass(), "ctor")
+ "Invalid rhino optlevel: " + opt);
}
}
context.setOptimizationLevel(optLevel);
try {
// create global object
global = new GlobalObject(this, app, false);
// call the initStandardsObject in ImporterTopLevel so that
// importClass() and importPackage() are set up.
global.initStandardObjects(context, false);
global.init();
axiomObjectProto = AxiomObject.init(this);
fileObjectProto = FileObject.initFileProto(this);
imageObjectProto = ImageObject.initImageProto(this);
// Reference initialization
try {
new ReferenceObjCtor(this, Reference.init(this));
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "ctor")
+ "Could not add ctor for Reference", x);
}
// MultiValue initialization
try {
new MultiValueCtor(this, MultiValue.init(this));
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "ctor")
+ "Could not add ctor for MultiValue", x);
}
// use lazy loaded constructors for all extension objects that
// adhere to the ScriptableObject.defineClass() protocol
/*
* Changes made, namely:
*
* 1) Removed the File and Image objects in preference to the File/Image objects
* we built in house
* 2) Added the following objects to the Rhino scripting environment:
* LdapClient
* Filter (for specifying queries)
* Sort (for specifying the sort order of queries)
* DOMParser (for parsing xml into a dom object)
* XMLSerializer (for writing a dom object to an xml string)
*
*/
new LazilyLoadedCtor(global, "FtpClient",
"axiom.scripting.rhino.extensions.FtpObject", false);
new LazilyLoadedCtor(global, "LdapClient",
"axiom.scripting.rhino.extensions.LdapObject", false);
new LazilyLoadedCtor(global, "Filter",
"axiom.scripting.rhino.extensions.filter.FilterObject", false);
new LazilyLoadedCtor(global, "NativeFilter",
"axiom.scripting.rhino.extensions.filter.NativeFilterObject", false);
new LazilyLoadedCtor(global, "AndFilter",
"axiom.scripting.rhino.extensions.filter.AndFilterObject", false);
new LazilyLoadedCtor(global, "OrFilter",
"axiom.scripting.rhino.extensions.filter.OrFilterObject", false);
new LazilyLoadedCtor(global, "NotFilter",
"axiom.scripting.rhino.extensions.filter.NotFilterObject", false);
new LazilyLoadedCtor(global, "RangeFilter",
"axiom.scripting.rhino.extensions.filter.RangeFilterObject", false);
new LazilyLoadedCtor(global, "SearchFilter",
"axiom.scripting.rhino.extensions.filter.SearchFilterObject", false);
new LazilyLoadedCtor(global, "Sort",
"axiom.scripting.rhino.extensions.filter.SortObject", false);
ArrayList names = app.getDbNames();
for(int i = 0; i < names.size(); i++){
try{
String dbname = names.get(i).toString();
DbSource dbsource = app.getDbSource(dbname);
String hitsObject = dbsource.getProperty("hitsObject", null);
String hitsClass = dbsource.getProperty("hitsClass", null);
if(hitsObject != null && hitsClass != null){
new LazilyLoadedCtor(global, hitsObject,
hitsClass, false);
}
String filters = dbsource.getProperty("filters", null);
if(filters != null){
StringBuffer sb = new StringBuffer(filters);
int idx;
while ((idx = sb.indexOf("{")) > -1) {
sb.deleteCharAt(idx);
}
while ((idx = sb.indexOf("}")) > -1) {
sb.deleteCharAt(idx);
}
filters = sb.toString().trim();
String[] pairs = filters.split(",");
for (int j = 0; j < pairs.length; j++) {
String[] pair = pairs[j].split(":");
new LazilyLoadedCtor(global, pair[0].trim(),
pair[1].trim(), false);
}
}
}
catch(Exception e){
app.logError("Error during LazilyLoadedCtor initialization for external databases");
}
}
new LazilyLoadedCtor(global, "LuceneHits",
"axiom.scripting.rhino.extensions.LuceneHitsObject", false);
new LazilyLoadedCtor(global, "TopDocs",
"axiom.scripting.rhino.extensions.TopDocsObject", false);
new LazilyLoadedCtor(global, "DOMParser",
"axiom.scripting.rhino.extensions.DOMParser", false);
new LazilyLoadedCtor(global, "XMLSerializer",
"axiom.scripting.rhino.extensions.XMLSerializer", false);
if ("true".equalsIgnoreCase(app.getProperty(RhinoCore.DEBUGGER_PROPERTY))) {
new LazilyLoadedCtor(global, "Debug",
"axiom.scripting.rhino.debug.Debug", false);
}
MailObject.init(global, app.getProperties());
// defining the ActiveX scriptable object for exposure of its API in Axiom
ScriptableObject.defineClass(global, ActiveX.class);
// add some convenience functions to string, date and number prototypes
Scriptable stringProto = ScriptableObject.getClassPrototype(global, "String");
stringProto.put("trim", stringProto, new StringTrim());
Scriptable dateProto = ScriptableObject.getClassPrototype(global, "Date");
dateProto.put("format", dateProto, new DateFormat());
Scriptable numberProto = ScriptableObject.getClassPrototype(global, "Number");
numberProto.put("format", numberProto, new NumberFormat());
initialize();
loadTemplates(app);
} catch (Exception e) {
System.err.println("Cannot initialize interpreter");
System.err.println("Error: " + e);
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
Context.exit();
}
}
| public RhinoCore(Application app) {
this.app = app;
wrappercache = new WeakCacheMap(500);
prototypes = new Hashtable();
Context context = Context.enter();
context.setLanguageVersion(170);
context.setCompileFunctionsWithDynamicScope(true);
context.setApplicationClassLoader(app.getClassLoader());
wrapper = new WrapMaker();
wrapper.setJavaPrimitiveWrap(false);
context.setWrapFactory(wrapper);
// Set default optimization level according to whether debugger is on
int optLevel = "true".equals(app.getProperty(DEBUGGER_PROPERTY)) ? -1 : 9;
String opt = app.getProperty("rhino.optlevel");
if (opt != null) {
try {
optLevel = Integer.parseInt(opt);
} catch (Exception ignore) {
app.logError(ErrorReporter.errorMsg(this.getClass(), "ctor")
+ "Invalid rhino optlevel: " + opt);
}
}
context.setOptimizationLevel(optLevel);
try {
// create global object
global = new GlobalObject(this, app, false);
// call the initStandardsObject in ImporterTopLevel so that
// importClass() and importPackage() are set up.
global.initStandardObjects(context, false);
global.init();
axiomObjectProto = AxiomObject.init(this);
fileObjectProto = FileObject.initFileProto(this);
imageObjectProto = ImageObject.initImageProto(this);
// Reference initialization
try {
new ReferenceObjCtor(this, Reference.init(this));
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "ctor")
+ "Could not add ctor for Reference", x);
}
// MultiValue initialization
try {
new MultiValueCtor(this, MultiValue.init(this));
} catch (Exception x) {
app.logError(ErrorReporter.fatalErrorMsg(this.getClass(), "ctor")
+ "Could not add ctor for MultiValue", x);
}
// use lazy loaded constructors for all extension objects that
// adhere to the ScriptableObject.defineClass() protocol
/*
* Changes made, namely:
*
* 1) Removed the File and Image objects in preference to the File/Image objects
* we built in house
* 2) Added the following objects to the Rhino scripting environment:
* LdapClient
* Filter (for specifying queries)
* Sort (for specifying the sort order of queries)
* DOMParser (for parsing xml into a dom object)
* XMLSerializer (for writing a dom object to an xml string)
*
*/
new LazilyLoadedCtor(global, "FtpClient",
"axiom.scripting.rhino.extensions.FtpObject", false);
new LazilyLoadedCtor(global, "LdapClient",
"axiom.scripting.rhino.extensions.LdapObject", false);
new LazilyLoadedCtor(global, "Filter",
"axiom.scripting.rhino.extensions.filter.FilterObject", false);
new LazilyLoadedCtor(global, "NativeFilter",
"axiom.scripting.rhino.extensions.filter.NativeFilterObject", false);
new LazilyLoadedCtor(global, "AndFilter",
"axiom.scripting.rhino.extensions.filter.AndFilterObject", false);
new LazilyLoadedCtor(global, "OrFilter",
"axiom.scripting.rhino.extensions.filter.OrFilterObject", false);
new LazilyLoadedCtor(global, "NotFilter",
"axiom.scripting.rhino.extensions.filter.NotFilterObject", false);
new LazilyLoadedCtor(global, "RangeFilter",
"axiom.scripting.rhino.extensions.filter.RangeFilterObject", false);
new LazilyLoadedCtor(global, "SearchFilter",
"axiom.scripting.rhino.extensions.filter.SearchFilterObject", false);
new LazilyLoadedCtor(global, "Sort",
"axiom.scripting.rhino.extensions.filter.SortObject", false);
ArrayList names = app.getDbNames();
for(int i = 0; i < names.size(); i++){
try{
String dbname = names.get(i).toString();
DbSource dbsource = app.getDbSource(dbname);
String hitsObject = dbsource.getProperty("hitsObject", null);
String hitsClass = dbsource.getProperty("hitsClass", null);
if(hitsObject != null && hitsClass != null){
new LazilyLoadedCtor(global, hitsObject,
hitsClass, false);
}
String filters = dbsource.getProperty("filters", null);
if(filters != null){
StringBuffer sb = new StringBuffer(filters);
int idx;
while ((idx = sb.indexOf("{")) > -1) {
sb.deleteCharAt(idx);
}
while ((idx = sb.indexOf("}")) > -1) {
sb.deleteCharAt(idx);
}
filters = sb.toString().trim();
String[] pairs = filters.split(",");
for (int j = 0; j < pairs.length; j++) {
String[] pair = pairs[j].split(":");
new LazilyLoadedCtor(global, pair[0].trim(),
pair[1].trim(), false);
}
}
}
catch(Exception e){
app.logError("Error during LazilyLoadedCtor initialization for external databases");
}
}
new LazilyLoadedCtor(global, "LuceneHits",
"axiom.scripting.rhino.extensions.LuceneHitsObject", false);
new LazilyLoadedCtor(global, "TopDocs",
"axiom.scripting.rhino.extensions.TopDocsObject", false);
new LazilyLoadedCtor(global, "DOMParser",
"axiom.scripting.rhino.extensions.DOMParser", false);
new LazilyLoadedCtor(global, "XMLSerializer",
"axiom.scripting.rhino.extensions.XMLSerializer", false);
if ("true".equalsIgnoreCase(app.getProperty(RhinoCore.DEBUGGER_PROPERTY))) {
new LazilyLoadedCtor(global, "Debug",
"axiom.scripting.rhino.debug.Debug", false);
}
MailObject.init(global, app.getProperties());
// defining the ActiveX scriptable object for exposure of its API in Axiom
ScriptableObject.defineClass(global, ActiveX.class);
// add some convenience functions to string, date and number prototypes
Scriptable stringProto = ScriptableObject.getClassPrototype(global, "String");
stringProto.put("trim", stringProto, new StringTrim());
Scriptable dateProto = ScriptableObject.getClassPrototype(global, "Date");
dateProto.put("format", dateProto, new DateFormat());
Scriptable numberProto = ScriptableObject.getClassPrototype(global, "Number");
numberProto.put("format", numberProto, new NumberFormat());
initialize();
loadTemplates(app);
} catch (Exception e) {
System.err.println("Cannot initialize interpreter");
System.err.println("Error: " + e);
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
Context.exit();
}
}
|
diff --git a/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/module/ResolverImpl.java b/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/module/ResolverImpl.java
index 300669d2..491533af 100644
--- a/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/module/ResolverImpl.java
+++ b/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/module/ResolverImpl.java
@@ -1,1408 +1,1414 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 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
*******************************************************************************/
package org.eclipse.osgi.internal.module;
import java.util.*;
import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor;
import org.eclipse.osgi.framework.debug.Debug;
import org.eclipse.osgi.framework.debug.FrameworkDebugOptions;
import org.eclipse.osgi.internal.resolver.BundleDescriptionImpl;
import org.eclipse.osgi.service.resolver.*;
import org.eclipse.osgi.util.ManifestElement;
import org.osgi.framework.*;
public class ResolverImpl implements org.eclipse.osgi.service.resolver.Resolver {
// Debug fields
private static final String RESOLVER = FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME + "/resolver"; //$NON-NLS-1$
private static final String OPTION_DEBUG = RESOLVER + "/debug";//$NON-NLS-1$
private static final String OPTION_WIRING = RESOLVER + "/wiring"; //$NON-NLS-1$
private static final String OPTION_IMPORTS = RESOLVER + "/imports"; //$NON-NLS-1$
private static final String OPTION_REQUIRES = RESOLVER + "/requires"; //$NON-NLS-1$
private static final String OPTION_GENERICS = RESOLVER + "/generics"; //$NON-NLS-1$
private static final String OPTION_GROUPING = RESOLVER + "/grouping"; //$NON-NLS-1$
private static final String OPTION_CYCLES = RESOLVER + "/cycles"; //$NON-NLS-1$
public static boolean DEBUG = false;
public static boolean DEBUG_WIRING = false;
public static boolean DEBUG_IMPORTS = false;
public static boolean DEBUG_REQUIRES = false;
public static boolean DEBUG_GENERICS = false;
public static boolean DEBUG_GROUPING = false;
public static boolean DEBUG_CYCLES = false;
private static String[][] CURRENT_EES;
// The State associated with this resolver
private State state;
// Used to check permissions for import/export, provide/require, host/fragment
private PermissionChecker permissionChecker;
// Set of bundles that are pending removal
private MappedList removalPending = new MappedList();
// Indicates whether this resolver has been initialized
private boolean initialized = false;
// Repository for exports
private VersionHashMap resolverExports = null;
// Repository for bundles
private VersionHashMap resolverBundles = null;
// Repository for generics
private VersionHashMap resolverGenerics = null;
// List of unresolved bundles
private ArrayList unresolvedBundles = null;
// Keys are BundleDescriptions, values are ResolverBundles
private HashMap bundleMapping = null;
private GroupingChecker groupingChecker;
private Comparator selectionPolicy;
private boolean developmentMode = false;
public ResolverImpl(BundleContext context, boolean checkPermissions) {
this.permissionChecker = new PermissionChecker(context, checkPermissions, this);
}
PermissionChecker getPermissionChecker() {
return permissionChecker;
}
// Initializes the resolver
private void initialize() {
resolverExports = new VersionHashMap(this);
resolverBundles = new VersionHashMap(this);
resolverGenerics = new VersionHashMap(this);
unresolvedBundles = new ArrayList();
bundleMapping = new HashMap();
BundleDescription[] bundles = state.getBundles();
groupingChecker = new GroupingChecker();
ArrayList fragmentBundles = new ArrayList();
// Add each bundle to the resolver's internal state
for (int i = 0; i < bundles.length; i++)
initResolverBundle(bundles[i], fragmentBundles, false);
// Add each removal pending bundle to the resolver's internal state
Object[] removedBundles = removalPending.getAllValues();
for (int i = 0; i < removedBundles.length; i++)
initResolverBundle((BundleDescription) removedBundles[i], fragmentBundles, true);
// Iterate over the resolved fragments and attach them to their hosts
for (Iterator iter = fragmentBundles.iterator(); iter.hasNext();) {
ResolverBundle fragment = (ResolverBundle) iter.next();
BundleDescription[] hosts = ((HostSpecification) fragment.getHost().getVersionConstraint()).getHosts();
for (int i = 0; i < hosts.length; i++) {
ResolverBundle host = (ResolverBundle) bundleMapping.get(hosts[i]);
if (host != null)
// Do not add fragment exports here because they would have been added by the host above.
host.attachFragment(fragment, false);
}
}
rewireBundles(); // Reconstruct wirings
ResolverBundle[] initBundles = (ResolverBundle[]) bundleMapping.values().toArray(new ResolverBundle[bundleMapping.size()]);
for (int i = 0; i < initBundles.length; i++)
// only initialize grouping constraint for resolved bundles;
// we add the constraints for unresolved bundles before we start a resolve opertation
if (initBundles[i].isResolved())
groupingChecker.addInitialGroupingConstraints(initBundles[i]);
setDebugOptions();
initialized = true;
}
private void initResolverBundle(BundleDescription bundleDesc, ArrayList fragmentBundles, boolean pending) {
ResolverBundle bundle = new ResolverBundle(bundleDesc, this);
bundleMapping.put(bundleDesc, bundle);
if (!pending || bundleDesc.isResolved()) {
resolverExports.put(bundle.getExportPackages());
resolverBundles.put(bundle.getName(), bundle);
resolverGenerics.put(bundle.getGenericCapabilities());
}
if (bundleDesc.isResolved()) {
bundle.setState(ResolverBundle.RESOLVED);
if (bundleDesc.getHost() != null)
fragmentBundles.add(bundle);
} else {
if (!pending)
unresolvedBundles.add(bundle);
}
}
// Re-wire previously resolved bundles
private void rewireBundles() {
ArrayList visited = new ArrayList(bundleMapping.size());
for (Iterator iter = bundleMapping.values().iterator(); iter.hasNext();) {
ResolverBundle rb = (ResolverBundle) iter.next();
if (!rb.getBundle().isResolved() || rb.isFragment())
continue;
rewireBundle(rb, visited);
}
}
private void rewireBundle(ResolverBundle rb, ArrayList visited) {
if (visited.contains(rb))
return;
visited.add(rb);
// Wire requires to bundles
BundleConstraint[] requires = rb.getRequires();
for (int i = 0; i < requires.length; i++) {
rewireRequire(requires[i], visited);
}
// Wire imports to exports
ResolverImport[] imports = rb.getImportPackages();
for (int i = 0; i < imports.length; i++) {
rewireImport(imports[i], visited);
}
// Wire generics
GenericConstraint[] genericRequires = rb.getGenericRequires();
for (int i = 0; i < genericRequires.length; i++)
rewireGeneric(genericRequires[i], visited);
}
private void rewireGeneric(GenericConstraint constraint, ArrayList visited) {
if (constraint.getMatchingCapabilities() != null)
return;
GenericDescription[] suppliers = ((GenericSpecification) constraint.getVersionConstraint()).getSuppliers();
if (suppliers == null)
return;
Object[] matches = resolverGenerics.get(constraint.getName());
for (int i = 0; i < matches.length; i++) {
GenericCapability match = (GenericCapability) matches[i];
for (int j = 0; j < suppliers.length; j++)
if (match.getBaseDescription() == suppliers[j])
constraint.setMatchingCapability(match);
}
GenericCapability[] matchingCapabilities = constraint.getMatchingCapabilities();
if (matchingCapabilities != null)
for (int i = 0; i < matchingCapabilities.length; i++)
rewireBundle(matchingCapabilities[i].getResolverBundle(), visited);
}
private void rewireRequire(BundleConstraint req, ArrayList visited) {
if (req.getMatchingBundle() != null)
return;
ResolverBundle matchingBundle = (ResolverBundle) bundleMapping.get(req.getVersionConstraint().getSupplier());
req.setMatchingBundle(matchingBundle);
if (matchingBundle == null && !req.isOptional()) {
System.err.println("Could not find matching bundle for " + req.getVersionConstraint()); //$NON-NLS-1$
// TODO log error!!
}
if (matchingBundle != null) {
rewireBundle(matchingBundle, visited);
}
}
private void rewireImport(ResolverImport imp, ArrayList visited) {
if (imp.isDynamic() || imp.getMatchingExport() != null)
return;
// Re-wire 'imp'
ResolverExport matchingExport = null;
ExportPackageDescription importSupplier = (ExportPackageDescription) imp.getVersionConstraint().getSupplier();
ResolverBundle exporter = importSupplier == null ? null : (ResolverBundle) bundleMapping.get(importSupplier.getExporter());
Object[] matches = resolverExports.get(imp.getName());
for (int j = 0; j < matches.length; j++) {
ResolverExport export = (ResolverExport) matches[j];
if (export.getExporter() == exporter && imp.isSatisfiedBy(export)) {
matchingExport = export;
break;
}
}
imp.setMatchingExport(matchingExport);
// Check if we wired to a reprovided package (in which case the ResolverExport doesn't exist)
if (matchingExport == null && exporter != null) {
ResolverExport reprovidedExport = new ResolverExport(exporter, importSupplier);
if (exporter.getExport(imp.getName()) == null) {
exporter.addExport(reprovidedExport);
resolverExports.put(reprovidedExport.getName(), reprovidedExport);
}
imp.setMatchingExport(reprovidedExport);
}
// If we still have a null wire and it's not optional, then we have an error
if (imp.getMatchingExport() == null && !imp.isOptional()) {
System.err.println("Could not find matching export for " + imp.getVersionConstraint()); //$NON-NLS-1$
// TODO log error!!
}
if (imp.getMatchingExport() != null) {
rewireBundle(imp.getMatchingExport().getExporter(), visited);
}
}
// Checks a bundle to make sure it is valid. If this method returns false for
// a given bundle, then that bundle will not even be considered for resolution
private boolean isResolvable(BundleDescription bundle, Dictionary[] platformProperties, ArrayList rejectedSingletons) {
// check if this is a rejected singleton
if (rejectedSingletons.contains(bundle))
return false;
// Check for singletons
if (bundle.isSingleton()) {
Object[] sameName = resolverBundles.get(bundle.getName());
if (sameName.length > 1) // Need to check if one is already resolved
for (int i = 0; i < sameName.length; i++) {
if (sameName[i] == bundle || !((ResolverBundle) sameName[i]).getBundle().isSingleton())
continue; // Ignore the bundle we are resolving and non-singletons
if (((ResolverBundle) sameName[i]).getBundle().isResolved()) {
rejectedSingletons.add(bundle);
return false; // Must fail since there is already a resolved bundle
}
}
}
// check the required execution environment
String[] ees = bundle.getExecutionEnvironments();
boolean matchedEE = ees.length == 0;
if (!matchedEE)
for (int i = 0; i < ees.length && !matchedEE; i++)
for (int j = 0; j < CURRENT_EES.length && !matchedEE; j++)
for (int k = 0; k < CURRENT_EES[j].length && !matchedEE; k++)
if (CURRENT_EES[j][k].equals(ees[i])) {
((BundleDescriptionImpl) bundle).setEquinoxEE(j);
matchedEE = true;
}
if (!matchedEE) {
StringBuffer bundleEE = new StringBuffer(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT.length() + 20);
bundleEE.append(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT).append(": "); //$NON-NLS-1$
for (int i = 0; i < ees.length; i++) {
if (i > 0)
bundleEE.append(","); //$NON-NLS-1$
bundleEE.append(ees[i]);
}
state.addResolverError(bundle, ResolverError.MISSING_EXECUTION_ENVIRONMENT, bundleEE.toString(), null);
return false;
}
// check the platform filter
String platformFilter = bundle.getPlatformFilter();
if (platformFilter == null)
return true;
if (platformProperties == null)
return false;
try {
Filter filter = FrameworkUtil.createFilter(platformFilter);
for (int i = 0; i < platformProperties.length; i++)
if (filter.match(platformProperties[i]))
return true;
} catch (InvalidSyntaxException e) {
// return false below
}
state.addResolverError(bundle, ResolverError.PLATFORM_FILTER, platformFilter, null);
return false;
}
// Attach fragment to its host
private void attachFragment(ResolverBundle bundle, ArrayList rejectedSingletons) {
if (!bundle.isFragment() || !bundle.isResolvable() || rejectedSingletons.contains(bundle.getBundle()))
return;
// no need to select singletons now; it will be done when we select the rest of the singleton bundles (bug 152042)
// find all available hosts to attach to.
boolean foundMatch = false;
BundleConstraint hostConstraint = bundle.getHost();
Object[] hosts = resolverBundles.get(hostConstraint.getVersionConstraint().getName());
for (int i = 0; i < hosts.length; i++)
if (((ResolverBundle) hosts[i]).isResolvable() && hostConstraint.isSatisfiedBy((ResolverBundle) hosts[i])) {
foundMatch = true;
resolverExports.put(((ResolverBundle) hosts[i]).attachFragment(bundle, true));
}
if (!foundMatch)
state.addResolverError(bundle.getBundle(), ResolverError.MISSING_FRAGMENT_HOST, bundle.getHost().getVersionConstraint().toString(), bundle.getHost().getVersionConstraint());
}
public synchronized void resolve(BundleDescription[] reRefresh, Dictionary[] platformProperties) {
if (DEBUG)
ResolverImpl.log("*** BEGIN RESOLUTION ***"); //$NON-NLS-1$
if (state == null)
throw new IllegalStateException("RESOLVER_NO_STATE"); //$NON-NLS-1$
if (!initialized)
initialize();
developmentMode = platformProperties.length == 0 ? false : org.eclipse.osgi.framework.internal.core.Constants.DEVELOPMENT_MODE.equals(platformProperties[0].get(org.eclipse.osgi.framework.internal.core.Constants.OSGI_RESOLVER_MODE));
reRefresh = addDevConstraints(reRefresh);
// Unresolve all the supplied bundles and their dependents
if (reRefresh != null)
for (int i = 0; i < reRefresh.length; i++) {
ResolverBundle rb = (ResolverBundle) bundleMapping.get(reRefresh[i]);
if (rb != null)
unresolveBundle(rb, false);
}
// reorder exports and bundles after unresolving the bundles
resolverExports.reorder();
resolverBundles.reorder();
resolverGenerics.reorder();
// always get the latest EEs
getCurrentEEs(platformProperties);
// keep a list of rejected singltons
ArrayList rejectedSingletons = new ArrayList();
boolean resolveOptional = platformProperties.length == 0 ? false : "true".equals(platformProperties[0].get("osgi.resolveOptional")); //$NON-NLS-1$//$NON-NLS-2$
ResolverBundle[] currentlyResolved = null;
if (resolveOptional) {
BundleDescription[] resolvedBundles = state.getResolvedBundles();
currentlyResolved = new ResolverBundle[resolvedBundles.length];
for (int i = 0; i < resolvedBundles.length; i++)
currentlyResolved[i] = (ResolverBundle) bundleMapping.get(resolvedBundles[i]);
}
// attempt to resolve all unresolved bundles
ResolverBundle[] bundles = (ResolverBundle[]) unresolvedBundles.toArray(new ResolverBundle[unresolvedBundles.size()]);
resolveBundles(bundles, platformProperties, rejectedSingletons);
if (selectSingletons(bundles, rejectedSingletons)) {
// a singleton was unresolved as a result of selecting a different version
// try to resolve unresolved bundles again; this will attempt to use the selected singleton
bundles = (ResolverBundle[]) unresolvedBundles.toArray(new ResolverBundle[unresolvedBundles.size()]);
resolveBundles(bundles, platformProperties, rejectedSingletons);
}
for (Iterator rejected = rejectedSingletons.iterator(); rejected.hasNext();) {
BundleDescription reject = (BundleDescription) rejected.next();
BundleDescription sameName = state.getBundle(reject.getSymbolicName(), null);
state.addResolverError(reject, ResolverError.SINGLETON_SELECTION, sameName.toString(), null);
}
if (resolveOptional)
resolveOptionalConstraints(currentlyResolved);
if (DEBUG)
ResolverImpl.log("*** END RESOLUTION ***"); //$NON-NLS-1$
}
private BundleDescription[] addDevConstraints(BundleDescription[] reRefresh) {
if (!developmentMode)
return reRefresh; // we don't care about this unless we are in development mode
// when in develoment mode we need to reRefresh hosts of unresolved fragments that add new constraints
// and reRefresh and unresolved bundles that have dependents
HashSet additionalRefresh = new HashSet();
ResolverBundle[] unresolved = (ResolverBundle[]) unresolvedBundles.toArray(new ResolverBundle[unresolvedBundles.size()]);
for (int i = 0; i < unresolved.length; i++) {
addUnresolvedWithDependents(unresolved[i], additionalRefresh);
addHostsFromFragmentConstraints(unresolved[i], additionalRefresh);
}
if (additionalRefresh.size() == 0)
return reRefresh; // no new bundles found to refresh
// add the original reRefresh bundles to the set
if (reRefresh != null)
for (int i = 0; i < reRefresh.length; i++)
additionalRefresh.add(reRefresh[i]);
return (BundleDescription[]) additionalRefresh.toArray(new BundleDescription[additionalRefresh.size()]);
}
private void addUnresolvedWithDependents(ResolverBundle unresolved, HashSet additionalRefresh) {
BundleDescription[] dependents = unresolved.getBundle().getDependents();
if (dependents.length > 0)
additionalRefresh.add(unresolved.getBundle());
}
private void addHostsFromFragmentConstraints(ResolverBundle unresolved, Set additionalRefresh) {
if (!unresolved.isFragment())
return;
ImportPackageSpecification[] newImports = unresolved.getBundle().getImportPackages();
BundleSpecification[] newRequires = unresolved.getBundle().getRequiredBundles();
if (newImports.length == 0 && newRequires.length == 0)
return; // the fragment does not have its own constraints
BundleConstraint hostConstraint = unresolved.getHost();
Object[] hosts = resolverBundles.get(hostConstraint.getVersionConstraint().getName());
for (int j = 0; j < hosts.length; j++)
if (hostConstraint.isSatisfiedBy((ResolverBundle) hosts[j]) && ((ResolverBundle) hosts[j]).isResolved())
// we found a host that is resolved;
// add it to the set of bundle to refresh so we can ensure this fragment is allowed to resolve
additionalRefresh.add(((ResolverBundle) hosts[j]).getBundle());
}
private void resolveOptionalConstraints(ResolverBundle[] bundles) {
for (int i = 0; i < bundles.length; i++) {
if (bundles[i] != null)
resolveOptionalConstraints(bundles[i]);
}
}
private void resolveOptionalConstraints(ResolverBundle bundle) {
BundleConstraint[] requires = bundle.getRequires();
ArrayList cycle = new ArrayList();
boolean resolvedOptional = false;
for (int i = 0; i < requires.length; i++)
if (requires[i].isOptional() && requires[i].getMatchingBundle() == null) {
cycle.clear();
resolveRequire(requires[i], cycle);
if (requires[i].getMatchingBundle() != null)
resolvedOptional = true;
}
ResolverImport[] imports = bundle.getImportPackages();
for (int i = 0; i < imports.length; i++)
if (imports[i].isOptional() && imports[i].getMatchingExport() == null) {
cycle.clear();
resolveImport(imports[i], true, cycle);
if (imports[i].getMatchingExport() != null)
resolvedOptional = true;
}
if (resolvedOptional) {
state.resolveBundle(bundle.getBundle(), false, null, null, null, null);
stateResolveConstraints(bundle);
stateResolveBundle(bundle);
}
}
private void getCurrentEEs(Dictionary[] platformProperties) {
CURRENT_EES = new String[platformProperties.length][];
for (int i = 0; i < platformProperties.length; i++) {
String eeSpecs = (String) platformProperties[i].get(Constants.FRAMEWORK_EXECUTIONENVIRONMENT);
CURRENT_EES[i] = ManifestElement.getArrayFromList(eeSpecs, ","); //$NON-NLS-1$
}
}
private void resolveBundles(ResolverBundle[] bundles, Dictionary[] platformProperties, ArrayList rejectedSingletons) {
// First check that all the meta-data is valid for each unresolved bundle
// This will reset the resolvable flag for each bundle
for (int i = 0; i < bundles.length; i++) {
state.removeResolverErrors(bundles[i].getBundle());
// if in development mode then make all bundles resolvable
// we still want to call isResolvable here to populate any possible ResolverErrors for the bundle
bundles[i].setResolvable(isResolvable(bundles[i].getBundle(), platformProperties, rejectedSingletons) || developmentMode);
bundles[i].clearRefs();
groupingChecker.removeAllExportConstraints(bundles[i]);
}
// First attach all fragments to the matching hosts
for (int i = 0; i < bundles.length; i++)
attachFragment(bundles[i], rejectedSingletons);
// add initial grouping constraints after fragments have been attached
for (int i = 0; i < bundles.length; i++)
groupingChecker.addInitialGroupingConstraints(bundles[i]);
// Lists of cyclic dependencies recording during resolving
ArrayList cycle = new ArrayList(1); // start small
ArrayList resolvedBundles = new ArrayList(bundles.length);
// Attempt to resolve all unresolved bundles
for (int i = 0; i < bundles.length; i++) {
if (DEBUG)
ResolverImpl.log("** RESOLVING " + bundles[i] + " **"); //$NON-NLS-1$ //$NON-NLS-2$
cycle.clear();
resolveBundle(bundles[i], cycle);
// Check for any bundles involved in a cycle.
// if any bundles in the cycle are not resolved then we need to resolve the resolvable ones
checkCycle(cycle);
if (bundles[i].isResolvable())
resolvedBundles.add(bundles[i]);
}
// Resolve all fragments that are still attached to at least one host.
if (unresolvedBundles.size() > 0) {
ResolverBundle[] unresolved = (ResolverBundle[]) unresolvedBundles.toArray(new ResolverBundle[unresolvedBundles.size()]);
for (int i = 0; i < unresolved.length; i++)
resolveFragment(unresolved[i]);
}
if (DEBUG_WIRING)
printWirings();
// set the resolved status of the bundles in the State
stateResolveBundles(bundles);
}
private void checkCycle(ArrayList cycle) {
int cycleSize = cycle.size();
if (cycleSize == 0)
return;
for (int i = cycleSize - 1; i >= 0; i--) {
ResolverBundle cycleBundle = (ResolverBundle) cycle.get(i);
// clear grouping (uses) constraints so we can do proper constaint checking now that the cycle is resolved
groupingChecker.removeAllExportConstraints(cycleBundle);
groupingChecker.addInitialGroupingConstraints(cycleBundle);
if (!cycleBundle.isResolvable())
cycle.remove(i); // remove this from the list of bundles that need reresolved
}
boolean reresolveCycle = cycle.size() != cycleSize || !isCycleConsistent(cycle); //we removed an unresolvable bundle; must reresolve remaining cycle
for (int i = 0; i < cycle.size(); i++) {
ResolverBundle rb = (ResolverBundle) cycle.get(0);
// Check that we haven't wired to any dropped exports
ResolverImport[] imports = rb.getImportPackages();
for (int j = 0; j < imports.length; j++)
// check for dropped exports
if (imports[j].getMatchingExport() != null && imports[j].getMatchingExport().isDropped()) {
imports[j].addUnresolvableWiring(imports[j].getMatchingExport().getExporter());
reresolveCycle = true;
}
}
if (reresolveCycle) {
for (int i = 0; i < cycle.size(); i++) {
ResolverBundle cycleBundle = (ResolverBundle) cycle.get(i);
groupingChecker.removeAllExportConstraints(cycleBundle);
groupingChecker.addInitialGroupingConstraints(cycleBundle);
cycleBundle.clearWires(false);
cycleBundle.clearRefs();
}
groupingChecker.setCheckCycles(true); // need to do the expensive cycle checks now
ArrayList innerCycle = new ArrayList(cycle.size());
for (int i = 0; i < cycle.size(); i++)
resolveBundle((ResolverBundle) cycle.get(i), innerCycle);
groupingChecker.setCheckCycles(false); // disable the expensive cycle checks
checkCycle(innerCycle);
} else {
for (int i = 0; i < cycle.size(); i++) {
if (DEBUG || DEBUG_CYCLES)
ResolverImpl.log("Pushing " + cycle.get(i) + " to RESOLVED"); //$NON-NLS-1$ //$NON-NLS-2$
setBundleResolved((ResolverBundle) cycle.get(i));
}
}
}
// checks all the uses constraints of a cycle to make sure they
// are consistent now that the cycle has been resolved.
private boolean isCycleConsistent(ArrayList cycle) {
for (Iterator iter = cycle.iterator(); iter.hasNext();) {
ResolverBundle bundle = (ResolverBundle) iter.next();
BundleConstraint[] requires = bundle.getRequires();
for (int i = 0; i < requires.length; i++)
if (requires[i].getMatchingBundle() != null && groupingChecker.isConsistent(requires[i], requires[i].getMatchingBundle()) != null)
return false;
ResolverImport[] imports = bundle.getImportPackages();
for (int i = 0; i < imports.length; i++)
if (imports[i].getMatchingExport() != null && groupingChecker.isConsistent(imports[i], imports[i].getMatchingExport()) != null)
return false;
}
return true;
}
private boolean selectSingletons(ResolverBundle[] bundles, ArrayList rejectedSingletons) {
if (developmentMode)
return false; // do no want to unresolve singletons in development mode
boolean result = false;
for (int i = 0; i < bundles.length; i++) {
BundleDescription bundleDesc = bundles[i].getBundle();
if (!bundleDesc.isSingleton() || !bundleDesc.isResolved() || rejectedSingletons.contains(bundleDesc))
continue;
Object[] sameName = resolverBundles.get(bundleDesc.getName());
if (sameName.length > 1) { // Need to make a selection based off of num dependents
for (int j = 0; j < sameName.length; j++) {
BundleDescription sameNameDesc = ((VersionSupplier) sameName[j]).getBundle();
ResolverBundle sameNameBundle = (ResolverBundle) sameName[j];
if (sameName[j] == bundles[i] || !sameNameDesc.isSingleton() || !sameNameDesc.isResolved() || rejectedSingletons.contains(sameNameDesc))
continue; // Ignore the bundle we are selecting, non-singletons, and non-resolved
result = true;
boolean rejectedPolicy = selectionPolicy != null ? selectionPolicy.compare(sameNameDesc, bundleDesc) < 0 : sameNameDesc.getVersion().compareTo(bundleDesc.getVersion()) > 0;
if (rejectedPolicy && sameNameBundle.getRefs() >= bundles[i].getRefs()) {
// this bundle is not selected; add it to the rejected list
if (!rejectedSingletons.contains(bundles[i].getBundle()))
rejectedSingletons.add(bundles[i].getBundle());
break;
}
// we did not select the sameNameDesc; add the bundle to the rejected list
if (!rejectedSingletons.contains(sameNameDesc))
rejectedSingletons.add(sameNameDesc);
}
}
}
// unresolve the rejected singletons
for (Iterator rejects = rejectedSingletons.iterator(); rejects.hasNext();)
unresolveBundle((ResolverBundle) bundleMapping.get(rejects.next()), false);
return result;
}
private void resolveFragment(ResolverBundle fragment) {
if (!fragment.isFragment())
return;
if (fragment.getHost().foundMatchingBundles()) {
stateResolveFragConstraints(fragment);
if (!developmentMode || state.getResolverErrors(fragment.getBundle()).length == 0)
setBundleResolved(fragment);
}
}
// This method will attempt to resolve the supplied bundle and any bundles that it is dependent on
private boolean resolveBundle(ResolverBundle bundle, ArrayList cycle) {
if (bundle.isFragment())
return false;
if (!bundle.isResolvable()) {
if (DEBUG)
ResolverImpl.log(" - " + bundle + " is unresolvable"); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
if (bundle.getState() == ResolverBundle.RESOLVED) {
// 'bundle' is already resolved so just return
if (DEBUG)
ResolverImpl.log(" - " + bundle + " already resolved"); //$NON-NLS-1$ //$NON-NLS-2$
return true;
} else if (bundle.getState() == ResolverBundle.UNRESOLVED) {
// 'bundle' is UNRESOLVED so move to RESOLVING
bundle.clearWires(true);
setBundleResolving(bundle);
}
boolean failed = false;
if (!failed) {
GenericConstraint[] genericRequires = bundle.getGenericRequires();
for (int i = 0; i < genericRequires.length; i++) {
if (!resolveGenericReq(genericRequires[i], cycle)) {
if (DEBUG || DEBUG_GENERICS)
ResolverImpl.log("** GENERICS " + genericRequires[i].getVersionConstraint().getName() + "[" + genericRequires[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
state.addResolverError(genericRequires[i].getVersionConstraint().getBundle(), ResolverError.MISSING_GENERIC_CAPABILITY, genericRequires[i].getVersionConstraint().toString(), genericRequires[i].getVersionConstraint());
if (genericRequires[i].isFromFragment()) {
if (!developmentMode) // only detach fragments when not in devmode
resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(genericRequires[i].getVersionConstraint().getBundle()), null));
continue;
}
- failed = true;
- if (!developmentMode)
+ if (!developmentMode) {
+ // fail fast; otherwise we want to attempt to resolver other constraints in dev mode
+ failed = true;
break;
+ }
}
}
}
if (!failed) {
// Iterate thru required bundles of 'bundle' trying to find matching bundles.
BundleConstraint[] requires = bundle.getRequires();
for (int i = 0; i < requires.length; i++) {
if (!resolveRequire(requires[i], cycle)) {
if (DEBUG || DEBUG_REQUIRES)
ResolverImpl.log("** REQUIRE " + requires[i].getVersionConstraint().getName() + "[" + requires[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
state.addResolverError(requires[i].getVersionConstraint().getBundle(), ResolverError.MISSING_REQUIRE_BUNDLE, requires[i].getVersionConstraint().toString(), requires[i].getVersionConstraint());
// If the require has failed to resolve and it is from a fragment, then remove the fragment from the host
if (requires[i].isFromFragment()) {
if (!developmentMode) // only detach fragments when not in devmode
resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(requires[i].getVersionConstraint().getBundle()), requires[i]));
continue;
}
- failed = true;
- if (!developmentMode) // in dev mode continue to next constraint
+ if (!developmentMode) {
+ // fail fast; otherwise we want to attempt to resolver other constraints in dev mode
+ failed = true;
break;
+ }
}
}
}
if (!failed) {
// Iterate thru imports of 'bundle' trying to find matching exports.
ResolverImport[] imports = bundle.getImportPackages();
for (int i = 0; i < imports.length; i++) {
// Only resolve non-dynamic imports here
if (!imports[i].isDynamic() && !resolveImport(imports[i], true, cycle)) {
if (DEBUG || DEBUG_IMPORTS)
ResolverImpl.log("** IMPORT " + imports[i].getName() + "[" + imports[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// If the import has failed to resolve and it is from a fragment, then remove the fragment from the host
state.addResolverError(imports[i].getVersionConstraint().getBundle(), ResolverError.MISSING_IMPORT_PACKAGE, imports[i].getVersionConstraint().toString(), imports[i].getVersionConstraint());
if (imports[i].isFromFragment()) {
if (!developmentMode) // only detach fragments when not in devmode
resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(imports[i].getBundleDescription()), imports[i]));
continue;
}
- failed = true;
- if (!developmentMode) // in dev mode continue to next constraint
+ if (!developmentMode) {
+ // fail fast; otherwise we want to attempt to resolver other constraints in dev mode
+ failed = true;
break;
+ }
}
}
}
// check that fragment constraints are met by the constraints that got resolved to the host
checkFragmentConstraints(bundle);
// do some extra checking when in development mode to see if other resolver error occurred
if (developmentMode && !failed && state.getResolverErrors(bundle.getBundle()).length > 0)
failed = true;
// Need to check that all mandatory imports are wired. If they are then
// set the bundle RESOLVED, otherwise set it back to UNRESOLVED
if (failed) {
setBundleUnresolved(bundle, false, developmentMode);
if (DEBUG)
ResolverImpl.log(bundle + " NOT RESOLVED"); //$NON-NLS-1$
} else if (!cycle.contains(bundle)) {
setBundleResolved(bundle);
if (DEBUG)
ResolverImpl.log(bundle + " RESOLVED"); //$NON-NLS-1$
}
if (bundle.getState() == ResolverBundle.UNRESOLVED)
bundle.setResolvable(false); // Set it to unresolvable so we don't attempt to resolve it again in this round
// tell the state what we resolved the constraints to
stateResolveConstraints(bundle);
return bundle.getState() != ResolverBundle.UNRESOLVED;
}
private void checkFragmentConstraints(ResolverBundle bundle) {
// get all currently attached fragments and ensure that any constraints
// they have do not conflict with the constraints resolved to by the host
ResolverBundle[] fragments = bundle.getFragments();
for (int i = 0; i < fragments.length; i++) {
BundleDescription fragment = fragments[i].getBundle();
if (bundle.constraintsConflict(fragment, fragment.getImportPackages(), fragment.getRequiredBundles(), fragment.getGenericRequires()) && !developmentMode)
// found some conflicts; detach the fragment
resolverExports.remove(bundle.detachFragment(fragments[i], null));
}
}
private boolean resolveGenericReq(GenericConstraint constraint, ArrayList cycle) {
if (DEBUG_REQUIRES)
ResolverImpl.log("Trying to resolve: " + constraint.getBundle() + ", " + constraint.getVersionConstraint()); //$NON-NLS-1$ //$NON-NLS-2$
GenericCapability[] matchingCapabilities = constraint.getMatchingCapabilities();
if (matchingCapabilities != null) {
// Check for unrecorded cyclic dependency
for (int i = 0; i < matchingCapabilities.length; i++)
if (matchingCapabilities[i].getResolverBundle().getState() == ResolverBundle.RESOLVING)
if (!cycle.contains(constraint.getBundle()))
cycle.add(constraint.getBundle());
if (DEBUG_REQUIRES)
ResolverImpl.log(" - already wired"); //$NON-NLS-1$
return true; // Already wired (due to grouping dependencies) so just return
}
Object[] capabilities = resolverGenerics.get(constraint.getVersionConstraint().getName());
boolean result = false;
for (int i = 0; i < capabilities.length; i++) {
GenericCapability capability = (GenericCapability) capabilities[i];
if (DEBUG_GENERICS)
ResolverImpl.log("CHECKING GENERICS: " + capability.getBaseDescription()); //$NON-NLS-1$
// Check if capability matches
if (constraint.isSatisfiedBy(capability)) {
capability.getResolverBundle().addRef(constraint.getBundle());
if (result && (((GenericSpecification) constraint.getVersionConstraint()).getResolution() & GenericSpecification.RESOLUTION_MULTIPLE) == 0)
continue; // found a match already and this is not a multiple constraint
constraint.setMatchingCapability(capability); // Wire to the capability
if (constraint.getBundle() == capability.getResolverBundle()) {
result = true; // Wired to ourselves
continue;
}
ResolverBundle[] capabilityHosts = capability.isFromFragment() ? capability.getResolverBundle().getHost().getMatchingBundles() : new ResolverBundle[] {capability.getResolverBundle()};
boolean foundResolvedMatch = false;
for (int j = 0; capabilityHosts != null && j < capabilityHosts.length; j++)
// if in dev mode then allow a constraint to resolve to an unresolved bundle
if (capabilityHosts[j].getState() == ResolverBundle.RESOLVED || (resolveBundle(capabilityHosts[j], cycle) || developmentMode)) {
foundResolvedMatch |= !capability.isFromFragment() ? true : capability.getResolverBundle().getHost().getMatchingBundles() != null;
// Check cyclic dependencies
if (capabilityHosts[j].getState() == ResolverBundle.RESOLVING)
if (!cycle.contains(capabilityHosts[j]))
cycle.add(capabilityHosts[j]);
}
if (!foundResolvedMatch) {
constraint.removeMatchingCapability(capability);
continue; // constraint hasn't resolved
}
if (DEBUG_GENERICS)
ResolverImpl.log("Found match: " + capability.getBaseDescription() + ". Wiring"); //$NON-NLS-1$ //$NON-NLS-2$
result = true;
}
}
return result ? true : (((GenericSpecification) constraint.getVersionConstraint()).getResolution() & GenericSpecification.RESOLUTION_OPTIONAL) != 0;
}
// Resolve the supplied import. Returns true if the import can be resolved, false otherwise
private boolean resolveRequire(BundleConstraint req, ArrayList cycle) {
if (DEBUG_REQUIRES)
ResolverImpl.log("Trying to resolve: " + req.getBundle() + ", " + req.getVersionConstraint()); //$NON-NLS-1$ //$NON-NLS-2$
if (req.getMatchingBundle() != null) {
// Check for unrecorded cyclic dependency
if (req.getMatchingBundle().getState() == ResolverBundle.RESOLVING)
if (!cycle.contains(req.getBundle())) {
cycle.add(req.getBundle());
if (DEBUG_CYCLES)
ResolverImpl.log("require-bundle cycle: " + req.getBundle() + " -> " + req.getMatchingBundle()); //$NON-NLS-1$ //$NON-NLS-2$
}
if (DEBUG_REQUIRES)
ResolverImpl.log(" - already wired"); //$NON-NLS-1$
return true; // Already wired (due to grouping dependencies) so just return
}
Object[] bundles = resolverBundles.get(req.getVersionConstraint().getName());
boolean result = false;
for (int i = 0; i < bundles.length; i++) {
ResolverBundle bundle = (ResolverBundle) bundles[i];
if (DEBUG_REQUIRES)
ResolverImpl.log("CHECKING: " + bundle.getBundle()); //$NON-NLS-1$
// Check if export matches
if (req.isSatisfiedBy(bundle)) {
bundle.addRef(req.getBundle());
if (result)
continue;
req.setMatchingBundle(bundle); // Wire to the bundle
if (req.getBundle() == bundle) {
result = true; // Wired to ourselves
continue;
}
// if in dev mode then allow a constraint to resolve to an unresolved bundle
if (bundle.getState() != ResolverBundle.RESOLVED && !resolveBundle(bundle, cycle) && !developmentMode) {
req.setMatchingBundle(null);
continue; // Bundle hasn't resolved
}
// Check cyclic dependencies
if (bundle.getState() == ResolverBundle.RESOLVING)
// If the bundle is RESOLVING, we have a cyclic dependency
if (!cycle.contains(req.getBundle())) {
cycle.add(req.getBundle());
if (DEBUG_CYCLES)
ResolverImpl.log("require-bundle cycle: " + req.getBundle() + " -> " + req.getMatchingBundle()); //$NON-NLS-1$ //$NON-NLS-2$
}
if (DEBUG_REQUIRES)
ResolverImpl.log("Found match: " + bundle.getBundle() + ". Wiring"); //$NON-NLS-1$ //$NON-NLS-2$
result = checkRequiresConstraints(req, req.getMatchingBundle());
}
}
if (result || req.isOptional())
return true; // If the req is optional then just return true
return false;
}
private boolean checkRequiresConstraints(BundleConstraint req, ResolverBundle bundle) {
if (groupingChecker.isConsistent(req, bundle) != null) {
req.setMatchingBundle(null);
state.addResolverError(req.getBundleDescription(), ResolverError.REQUIRE_BUNDLE_USES_CONFLICT, bundle.getBundle().toString(), req.getVersionConstraint());
return req.isOptional();
}
return true;
}
// Resolve the supplied import. Returns true if the import can be resolved, false otherwise
private boolean resolveImport(ResolverImport imp, boolean checkReexportsFromRequires, ArrayList cycle) {
if (DEBUG_IMPORTS)
ResolverImpl.log("Trying to resolve: " + imp.getBundle() + ", " + imp.getName()); //$NON-NLS-1$ //$NON-NLS-2$
if (imp.getMatchingExport() != null) {
// Check for unrecorded cyclic dependency
if (imp.getMatchingExport().getExporter().getState() == ResolverBundle.RESOLVING)
if (!cycle.contains(imp.getBundle())) {
cycle.add(imp.getBundle());
if (DEBUG_CYCLES)
ResolverImpl.log("import-package cycle: " + imp.getBundle() + " -> " + imp.getMatchingExport() + " from " + imp.getMatchingExport().getBundle()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
if (DEBUG_IMPORTS)
ResolverImpl.log(" - already wired"); //$NON-NLS-1$
return true; // Already wired (due to grouping dependencies) so just return
}
boolean result = false;
Object[] exports = resolverExports.get(imp.getName());
exportsloop: for (int i = 0; i < exports.length; i++) {
ResolverExport export = (ResolverExport) exports[i];
if (DEBUG_IMPORTS)
ResolverImpl.log("CHECKING: " + export.getExporter().getBundle() + ", " + export.getName()); //$NON-NLS-1$ //$NON-NLS-2$
// Check if export matches
if (imp.isSatisfiedBy(export) && imp.isNotAnUnresolvableWiring(export)) {
int originalState = export.getExporter().getState();
if (imp.isDynamic() && originalState != ResolverBundle.RESOLVED)
continue; // Must not attempt to resolve an exporter when dynamic
if (imp.getBundle() == export.getExporter() && !export.getExportPackageDescription().isRoot())
continue; // Can't wire to our own re-export
export.getExporter().addRef(imp.getBundle());
if (result)
continue;
imp.setMatchingExport(export); // Wire the import to the export
ResolverExport[] importerExps = null;
if (imp.getBundle() != export.getExporter()) {
// Save the exports of this package from the importer in case we need to add them back
importerExps = imp.getBundle().getExports(imp.getName());
for (int j = 0; j < importerExps.length; j++) {
if (importerExps[j].getExportPackageDescription().isRoot() && !export.getExportPackageDescription().isRoot())
continue exportsloop; // to prevent imports from getting wired to re-exports if we offer a root export
if (importerExps[j].getExportPackageDescription().isRoot()) // do not drop reexports when import wins
resolverExports.remove(importerExps[j]); // Import wins, remove export
}
// if in dev mode then allow a constraint to resolve to an unresolved bundle
if ((originalState != ResolverBundle.RESOLVED && !resolveBundle(export.getExporter(), cycle) && !developmentMode) || export.isDropped()) {
if (imp.getMatchingExport() != null && imp.getMatchingExport() != export) // has been resolved to some other export recursively
return true;
// add back the exports of this package from the importer
for (int j = 0; j < importerExps.length; j++)
resolverExports.put(importerExps[j].getName(), importerExps[j]);
imp.setMatchingExport(null);
continue; // Bundle hasn't resolved || export has not been selected and is unavailable
}
}
// If the importer has become unresolvable then stop here
if (!imp.getBundle().isResolvable())
return false;
// Check grouping dependencies
if (checkImportConstraints(imp, imp.getMatchingExport(), cycle, importerExps) && imp.getMatchingExport() != null) {
// Record any cyclic dependencies
if (export != imp.getMatchingExport())
export = imp.getMatchingExport();
if (imp.getBundle() != export.getExporter())
if (export.getExporter().getState() == ResolverBundle.RESOLVING) {
// If the exporter is RESOLVING, we have a cyclic dependency
if (!cycle.contains(imp.getBundle())) {
cycle.add(imp.getBundle());
if (DEBUG_CYCLES)
ResolverImpl.log("import-package cycle: " + imp.getBundle() + " -> " + imp.getMatchingExport() + " from " + imp.getMatchingExport().getBundle()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
if (DEBUG_IMPORTS)
ResolverImpl.log("Found match: " + export.getExporter() + ". Wiring " + imp.getBundle() + ":" + imp.getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
result = true;
} else if (!imp.getBundle().isResolvable()) {
// If grouping has caused recursive calls to resolveImport, and the grouping has failed
// then we need to catch that here, so we don't continue trying to wire here
return false;
}
if (!result && imp.getMatchingExport() != null && imp.getMatchingExport() != export)
return true; // Grouping has changed the wiring, so return here
}
}
if (result)
return true;
if (checkReexportsFromRequires && resolveImportReprovide(imp, cycle))
return true; // A reprovide satisfies imp
if (imp.isOptional())
return true; // If the import is optional then just return true
return false;
}
// Check if the import can be resolved to a re-exported package (has no export object to match to)
private boolean resolveImportReprovide(ResolverImport imp, ArrayList cycle) {
String bsn = ((ImportPackageSpecification) imp.getVersionConstraint()).getBundleSymbolicName();
// If no symbolic name specified then just return (since this is a
// re-export an import not specifying a bsn will wire to the root)
if (bsn == null)
return false;
if (DEBUG_IMPORTS)
ResolverImpl.log("Checking reprovides: " + imp.getName()); //$NON-NLS-1$
// Find bundle with specified bsn
Object[] bundles = resolverBundles.get(bsn);
for (int i = 0; i < bundles.length; i++)
if (resolveBundle((ResolverBundle) bundles[i], cycle))
if (resolveImportReprovide0(imp, (ResolverBundle) bundles[i], (ResolverBundle) bundles[i], cycle, new ArrayList(5)))
return true;
return false;
}
private boolean resolveImportReprovide0(ResolverImport imp, ResolverBundle reexporter, ResolverBundle rb, ArrayList cycle, ArrayList visited) {
if (visited.contains(rb))
return false; // make sure we don't endless recurse cycles
visited.add(rb);
BundleConstraint[] requires = rb.getRequires();
for (int i = 0; i < requires.length; i++) {
if (!((BundleSpecification) requires[i].getVersionConstraint()).isExported())
continue; // Skip require if it doesn't re-export the packages
// Check exports to see if we've found the root
if (requires[i].getMatchingBundle() == null)
continue;
ResolverExport[] exports = requires[i].getMatchingBundle().getExports(imp.getName());
for (int j = 0; j < exports.length; j++) {
Map directives = exports[j].getExportPackageDescription().getDirectives();
directives.remove(Constants.USES_DIRECTIVE);
ExportPackageDescription epd = state.getFactory().createExportPackageDescription(exports[j].getName(), exports[j].getVersion(), directives, exports[j].getExportPackageDescription().getAttributes(), false, reexporter.getBundle());
if (imp.getVersionConstraint().isSatisfiedBy(epd)) {
// Create reexport and add to bundle and resolverExports
if (DEBUG_IMPORTS)
ResolverImpl.log(" - Creating re-export for reprovide: " + reexporter + ":" + epd.getName()); //$NON-NLS-1$ //$NON-NLS-2$
ResolverExport re = new ResolverExport(reexporter, epd);
reexporter.addExport(re);
resolverExports.put(re.getName(), re);
// Resolve import
if (resolveImport(imp, false, cycle))
return true;
}
}
// Check requires of matching bundle (recurse down the chain)
if (resolveImportReprovide0(imp, reexporter, requires[i].getMatchingBundle(), cycle, visited))
return true;
}
return false;
}
// This method checks and resolves (if possible) grouping dependencies
// Returns true, if the dependencies can be resolved, false otherwise
private boolean checkImportConstraints(ResolverImport imp, ResolverExport exp, ArrayList cycle, ResolverExport[] importerExps) {
if (DEBUG_GROUPING)
ResolverImpl.log(" Checking grouping for " + imp.getBundle() + ":" + imp.getName() + " -> " + exp.getExporter() + ":" + exp.getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
ResolverBundle importer = imp.getBundle();
ResolverExport clash = groupingChecker.isConsistent(imp, exp);
if (clash == null)
return true;
if (DEBUG_GROUPING)
ResolverImpl.log(" * grouping clash with " + clash.getExporter() + ":" + clash.getName()); //$NON-NLS-1$ //$NON-NLS-2$
// Try to rewire imp
imp.addUnresolvableWiring(exp.getExporter());
imp.setMatchingExport(null);
if (resolveImport(imp, false, cycle))
return true;
if (imp.isDynamic())
return false;
// Rewiring of imp has failed so try to rewire clashing import
imp.clearUnresolvableWirings();
imp.setMatchingExport(exp);
ResolverImport[] imports = importer.getImportPackages();
for (int i = 0; i < imports.length; i++) {
if (imports[i].getMatchingExport() != null && imports[i].getMatchingExport().getName().equals(clash.getName())) {
imports[i].addUnresolvableWiring(imports[i].getMatchingExport().getExporter());
imports[i].setMatchingExport(null); // clear the conflicting wire
// If the clashing import package was also exported then
// we need to put the export back into resolverExports
if (importerExps != null)
resolverExports.put(importerExps);
}
}
// Try to re-resolve the bundle
if (resolveBundle(importer, cycle))
return true;
state.addResolverError(imp.getVersionConstraint().getBundle(), ResolverError.IMPORT_PACKAGE_USES_CONFLICT, imp.getVersionConstraint().toString(), imp.getVersionConstraint());
return false;
}
// Move a bundle to UNRESOLVED
private void setBundleUnresolved(ResolverBundle bundle, boolean removed, boolean isDevMode) {
if (bundle.getState() == ResolverBundle.UNRESOLVED)
return;
if (bundle.getBundle().isResolved()) {
resolverExports.remove(bundle.getExportPackages());
if (removed)
resolverGenerics.remove(bundle.getGenericCapabilities());
bundle.initialize(false);
if (!removed)
resolverExports.put(bundle.getExportPackages());
}
if (!removed)
unresolvedBundles.add(bundle);
if (!isDevMode)
bundle.detachAllFragments();
bundle.setState(ResolverBundle.UNRESOLVED);
}
// Move a bundle to RESOLVED
private void setBundleResolved(ResolverBundle bundle) {
if (bundle.getState() == ResolverBundle.RESOLVED)
return;
unresolvedBundles.remove(bundle);
bundle.setState(ResolverBundle.RESOLVED);
}
// Move a bundle to RESOLVING
private void setBundleResolving(ResolverBundle bundle) {
if (bundle.getState() == ResolverBundle.RESOLVING)
return;
unresolvedBundles.remove(bundle);
bundle.setState(ResolverBundle.RESOLVING);
}
// Resolves the bundles in the State
private void stateResolveBundles(ResolverBundle[] resolvedBundles) {
for (int i = 0; i < resolvedBundles.length; i++)
if (!resolvedBundles[i].getBundle().isResolved())
stateResolveBundle(resolvedBundles[i]);
}
private void stateResolveConstraints(ResolverBundle rb) {
ResolverImport[] imports = rb.getImportPackages();
for (int i = 0; i < imports.length; i++) {
ResolverExport export = imports[i].getMatchingExport();
BaseDescription supplier = export == null ? null : export.getExportPackageDescription();
state.resolveConstraint(imports[i].getVersionConstraint(), supplier);
}
BundleConstraint[] requires = rb.getRequires();
for (int i = 0; i < requires.length; i++) {
ResolverBundle bundle = requires[i].getMatchingBundle();
BaseDescription supplier = bundle == null ? null : bundle.getBundle();
state.resolveConstraint(requires[i].getVersionConstraint(), supplier);
}
GenericConstraint[] genericRequires = rb.getGenericRequires();
for (int i = 0; i < genericRequires.length; i++) {
GenericCapability[] matchingCapabilities = genericRequires[i].getMatchingCapabilities();
if (matchingCapabilities == null)
state.resolveConstraint(genericRequires[i].getVersionConstraint(), null);
else
for (int j = 0; j < matchingCapabilities.length; j++)
state.resolveConstraint(genericRequires[i].getVersionConstraint(), matchingCapabilities[j].getBaseDescription());
}
}
private void stateResolveFragConstraints(ResolverBundle rb) {
ResolverBundle host = rb.getHost().getMatchingBundle();
ImportPackageSpecification[] imports = rb.getBundle().getImportPackages();
for (int i = 0; i < imports.length; i++) {
ResolverImport hostImport = host.getImport(imports[i].getName());
ResolverExport export = hostImport == null ? null : hostImport.getMatchingExport();
BaseDescription supplier = export == null ? null : export.getExportPackageDescription();
state.resolveConstraint(imports[i], supplier);
}
BundleSpecification[] requires = rb.getBundle().getRequiredBundles();
for (int i = 0; i < requires.length; i++) {
BundleConstraint hostRequire = host.getRequire(requires[i].getName());
ResolverBundle bundle = hostRequire == null ? null : hostRequire.getMatchingBundle();
BaseDescription supplier = bundle == null ? null : bundle.getBundle();
state.resolveConstraint(requires[i], supplier);
}
}
private void stateResolveBundle(ResolverBundle rb) {
// if in dev mode then we want to tell the state about the constraints we were able to resolve
if (!rb.isResolved() && !developmentMode)
return;
// Gather selected exports
ResolverExport[] exports = rb.getSelectedExports();
ArrayList selectedExports = new ArrayList(exports.length);
for (int i = 0; i < exports.length; i++) {
selectedExports.add(exports[i].getExportPackageDescription());
}
ExportPackageDescription[] selectedExportsArray = (ExportPackageDescription[]) selectedExports.toArray(new ExportPackageDescription[selectedExports.size()]);
// Gather exports that have been wired to
ResolverImport[] imports = rb.getImportPackages();
ArrayList exportsWiredTo = new ArrayList(imports.length);
for (int i = 0; i < imports.length; i++) {
if (imports[i].getMatchingExport() != null) {
exportsWiredTo.add(imports[i].getMatchingExport().getExportPackageDescription());
}
}
ExportPackageDescription[] exportsWiredToArray = (ExportPackageDescription[]) exportsWiredTo.toArray(new ExportPackageDescription[exportsWiredTo.size()]);
// Gather bundles that have been wired to
BundleConstraint[] requires = rb.getRequires();
ArrayList bundlesWiredTo = new ArrayList(requires.length);
for (int i = 0; i < requires.length; i++)
if (requires[i].getMatchingBundle() != null)
bundlesWiredTo.add(requires[i].getMatchingBundle().getBundle());
BundleDescription[] bundlesWiredToArray = (BundleDescription[]) bundlesWiredTo.toArray(new BundleDescription[bundlesWiredTo.size()]);
BundleDescription[] hostBundles = null;
if (rb.isFragment()) {
ResolverBundle[] matchingBundles = rb.getHost().getMatchingBundles();
if (matchingBundles != null && matchingBundles.length > 0) {
hostBundles = new BundleDescription[matchingBundles.length];
for (int i = 0; i < matchingBundles.length; i++) {
hostBundles[i] = matchingBundles[i].getBundle();
if (rb.isNewFragmentExports() && hostBundles[i].isResolved()) {
// update the host's set of selected exports
ResolverExport[] hostExports = matchingBundles[i].getSelectedExports();
ExportPackageDescription[] hostExportsArray = new ExportPackageDescription[hostExports.length];
for (int j = 0; j < hostExports.length; j++)
hostExportsArray[j] = hostExports[j].getExportPackageDescription();
state.resolveBundle(hostBundles[i], true, null, hostExportsArray, hostBundles[i].getResolvedRequires(), hostBundles[i].getResolvedImports());
}
}
}
}
// Resolve the bundle in the state
state.resolveBundle(rb.getBundle(), rb.isResolved(), hostBundles, selectedExportsArray, bundlesWiredToArray, exportsWiredToArray);
}
// Resolve dynamic import
public synchronized ExportPackageDescription resolveDynamicImport(BundleDescription importingBundle, String requestedPackage) {
if (state == null)
throw new IllegalStateException("RESOLVER_NO_STATE"); //$NON-NLS-1$
// Make sure the resolver is initialized
if (!initialized)
initialize();
ResolverBundle rb = (ResolverBundle) bundleMapping.get(importingBundle);
if (rb.getExport(requestedPackage) != null)
return null; // do not allow dynamic wires for packages which this bundle exports
ResolverImport[] resolverImports = rb.getImportPackages();
// Check through the ResolverImports of this bundle.
// If there is a matching one then pass it into resolveImport()
boolean found = false;
for (int j = 0; j < resolverImports.length; j++) {
// Make sure it is a dynamic import
if (!resolverImports[j].isDynamic())
continue;
String importName = resolverImports[j].getName();
// If the import uses a wildcard, then temporarily replace this with the requested package
if (importName.equals("*") || //$NON-NLS-1$
(importName.endsWith(".*") && requestedPackage.startsWith(importName.substring(0, importName.length() - 2)))) { //$NON-NLS-1$
resolverImports[j].setName(requestedPackage);
}
// Resolve the import
if (requestedPackage.equals(resolverImports[j].getName())) {
found = true;
if (resolveImport(resolverImports[j], true, new ArrayList())) {
// If the import resolved then return it's matching export
resolverImports[j].setName(null);
if (DEBUG_IMPORTS)
ResolverImpl.log("Resolved dynamic import: " + rb + ":" + resolverImports[j].getName() + " -> " + resolverImports[j].getMatchingExport().getExporter() + ":" + requestedPackage); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
ExportPackageDescription matchingExport = resolverImports[j].getMatchingExport().getExportPackageDescription();
// If it is a wildcard import then clear the wire, so other
// exported packages can be found for it
if (importName.endsWith("*")) //$NON-NLS-1$
resolverImports[j].setMatchingExport(null);
return matchingExport;
}
}
// Reset the import package name
resolverImports[j].setName(null);
}
// this is to support adding dynamic imports on the fly.
if (!found) {
Map directives = new HashMap(1);
directives.put(Constants.RESOLUTION_DIRECTIVE, ImportPackageSpecification.RESOLUTION_DYNAMIC);
ImportPackageSpecification packageSpec = state.getFactory().createImportPackageSpecification(requestedPackage, null, null, null, directives, null, importingBundle);
ResolverImport newImport = new ResolverImport(rb, packageSpec);
if (resolveImport(newImport, true, new ArrayList()))
return newImport.getMatchingExport().getExportPackageDescription();
}
if (DEBUG || DEBUG_IMPORTS)
ResolverImpl.log("Failed to resolve dynamic import: " + requestedPackage); //$NON-NLS-1$
return null; // Couldn't resolve the import, so return null
}
public void bundleAdded(BundleDescription bundle) {
if (!initialized)
return;
boolean alreadyThere = false;
for (int i = 0; i < unresolvedBundles.size(); i++) {
ResolverBundle rb = (ResolverBundle) unresolvedBundles.get(i);
if (rb.getBundle() == bundle) {
alreadyThere = true;
}
}
if (!alreadyThere) {
ResolverBundle rb = new ResolverBundle(bundle, this);
bundleMapping.put(bundle, rb);
unresolvedBundles.add(rb);
resolverExports.put(rb.getExportPackages());
resolverBundles.put(rb.getName(), rb);
resolverGenerics.put(rb.getGenericCapabilities());
}
}
public void bundleRemoved(BundleDescription bundle, boolean pending) {
// check if there are any dependants
if (pending)
removalPending.put(new Long(bundle.getBundleId()), bundle);
if (!initialized)
return;
ResolverBundle rb = (ResolverBundle) bundleMapping.get(bundle);
if (rb == null)
return;
if (!pending) {
bundleMapping.remove(bundle);
groupingChecker.removeAllExportConstraints(rb);
}
if (!pending || !bundle.isResolved()) {
resolverExports.remove(rb.getExportPackages());
resolverBundles.remove(rb);
resolverGenerics.remove(rb.getGenericCapabilities());
}
unresolvedBundles.remove(rb);
}
private void unresolveBundle(ResolverBundle bundle, boolean removed) {
if (bundle == null)
return;
// check the removed list if unresolving then remove from the removed list
Object[] removedBundles = removalPending.remove(new Long(bundle.getBundle().getBundleId()));
for (int i = 0; i < removedBundles.length; i++) {
ResolverBundle re = (ResolverBundle) bundleMapping.get(removedBundles[i]);
unresolveBundle(re, true);
state.removeBundleComplete((BundleDescription) removedBundles[i]);
resolverExports.remove(re.getExportPackages());
resolverBundles.remove(re);
resolverGenerics.remove(re.getGenericCapabilities());
bundleMapping.remove(removedBundles[i]);
groupingChecker.removeAllExportConstraints(re);
// the bundle is removed
if (removedBundles[i] == bundle.getBundle())
removed = true;
}
if (!bundle.getBundle().isResolved() && !developmentMode)
return;
// if not removed then add to the list of unresolvedBundles,
// passing false for devmode because we need all fragments detached
setBundleUnresolved(bundle, removed, false);
// Get bundles dependent on 'bundle'
BundleDescription[] dependents = bundle.getBundle().getDependents();
state.resolveBundle(bundle.getBundle(), false, null, null, null, null);
// Unresolve dependents of 'bundle'
for (int i = 0; i < dependents.length; i++)
unresolveBundle((ResolverBundle) bundleMapping.get(dependents[i]), false);
}
public void bundleUpdated(BundleDescription newDescription, BundleDescription existingDescription, boolean pending) {
bundleRemoved(existingDescription, pending);
bundleAdded(newDescription);
}
public void flush() {
resolverExports = null;
resolverBundles = null;
resolverGenerics = null;
unresolvedBundles = null;
bundleMapping = null;
Object[] removed = removalPending.getAllValues();
for (int i = 0; i < removed.length; i++)
state.removeBundleComplete((BundleDescription) removed[i]);
removalPending.clear();
initialized = false;
}
public State getState() {
return state;
}
public void setState(State newState) {
state = newState;
flush();
}
private void setDebugOptions() {
FrameworkDebugOptions options = FrameworkDebugOptions.getDefault();
// may be null if debugging is not enabled
if (options == null)
return;
DEBUG = options.getBooleanOption(OPTION_DEBUG, false);
DEBUG_WIRING = options.getBooleanOption(OPTION_WIRING, false);
DEBUG_IMPORTS = options.getBooleanOption(OPTION_IMPORTS, false);
DEBUG_REQUIRES = options.getBooleanOption(OPTION_REQUIRES, false);
DEBUG_GENERICS = options.getBooleanOption(OPTION_GENERICS, false);
DEBUG_GROUPING = options.getBooleanOption(OPTION_GROUPING, false);
DEBUG_CYCLES = options.getBooleanOption(OPTION_CYCLES, false);
}
// LOGGING METHODS
private void printWirings() {
ResolverImpl.log("****** Result Wirings ******"); //$NON-NLS-1$
Object[] bundles = resolverBundles.getAllValues();
for (int j = 0; j < bundles.length; j++) {
ResolverBundle rb = (ResolverBundle) bundles[j];
if (rb.getBundle().isResolved()) {
continue;
}
ResolverImpl.log(" * WIRING for " + rb); //$NON-NLS-1$
// Require bundles
BundleConstraint[] requireBundles = rb.getRequires();
if (requireBundles.length == 0) {
ResolverImpl.log(" (r) no requires"); //$NON-NLS-1$
} else {
for (int i = 0; i < requireBundles.length; i++) {
if (requireBundles[i].getMatchingBundle() == null) {
ResolverImpl.log(" (r) " + rb.getBundle() + " -> NULL!!!"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
ResolverImpl.log(" (r) " + rb.getBundle() + " -> " + requireBundles[i].getMatchingBundle()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
// Hosts
BundleConstraint hostSpec = rb.getHost();
if (hostSpec != null) {
ResolverBundle[] hosts = hostSpec.getMatchingBundles();
if (hosts != null)
for (int i = 0; i < hosts.length; i++) {
ResolverImpl.log(" (h) " + rb.getBundle() + " -> " + hosts[i].getBundle()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Imports
ResolverImport[] imports = rb.getImportPackages();
if (imports.length == 0) {
ResolverImpl.log(" (w) no imports"); //$NON-NLS-1$
continue;
}
for (int i = 0; i < imports.length; i++) {
if (imports[i].isDynamic() && imports[i].getMatchingExport() == null) {
ResolverImpl.log(" (w) " + imports[i].getBundle() + ":" + imports[i].getName() + " -> DYNAMIC"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} else if (imports[i].isOptional() && imports[i].getMatchingExport() == null) {
ResolverImpl.log(" (w) " + imports[i].getBundle() + ":" + imports[i].getName() + " -> OPTIONAL (could not be wired)"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} else if (imports[i].getMatchingExport() == null) {
ResolverImpl.log(" (w) " + imports[i].getBundle() + ":" + imports[i].getName() + " -> NULL!!!"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} else {
ResolverImpl.log(" (w) " + imports[i].getBundle() + ":" + imports[i].getName() + " -> " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
imports[i].getMatchingExport().getExporter() + ":" + imports[i].getMatchingExport().getName()); //$NON-NLS-1$
}
}
}
}
static void log(String message) {
Debug.println(message);
}
VersionHashMap getResolverExports() {
return resolverExports;
}
public void setSelectionPolicy(Comparator selectionPolicy) {
this.selectionPolicy = selectionPolicy;
}
public Comparator getSelectionPolicy() {
return selectionPolicy;
}
}
| false | true | private boolean resolveBundle(ResolverBundle bundle, ArrayList cycle) {
if (bundle.isFragment())
return false;
if (!bundle.isResolvable()) {
if (DEBUG)
ResolverImpl.log(" - " + bundle + " is unresolvable"); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
if (bundle.getState() == ResolverBundle.RESOLVED) {
// 'bundle' is already resolved so just return
if (DEBUG)
ResolverImpl.log(" - " + bundle + " already resolved"); //$NON-NLS-1$ //$NON-NLS-2$
return true;
} else if (bundle.getState() == ResolverBundle.UNRESOLVED) {
// 'bundle' is UNRESOLVED so move to RESOLVING
bundle.clearWires(true);
setBundleResolving(bundle);
}
boolean failed = false;
if (!failed) {
GenericConstraint[] genericRequires = bundle.getGenericRequires();
for (int i = 0; i < genericRequires.length; i++) {
if (!resolveGenericReq(genericRequires[i], cycle)) {
if (DEBUG || DEBUG_GENERICS)
ResolverImpl.log("** GENERICS " + genericRequires[i].getVersionConstraint().getName() + "[" + genericRequires[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
state.addResolverError(genericRequires[i].getVersionConstraint().getBundle(), ResolverError.MISSING_GENERIC_CAPABILITY, genericRequires[i].getVersionConstraint().toString(), genericRequires[i].getVersionConstraint());
if (genericRequires[i].isFromFragment()) {
if (!developmentMode) // only detach fragments when not in devmode
resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(genericRequires[i].getVersionConstraint().getBundle()), null));
continue;
}
failed = true;
if (!developmentMode)
break;
}
}
}
if (!failed) {
// Iterate thru required bundles of 'bundle' trying to find matching bundles.
BundleConstraint[] requires = bundle.getRequires();
for (int i = 0; i < requires.length; i++) {
if (!resolveRequire(requires[i], cycle)) {
if (DEBUG || DEBUG_REQUIRES)
ResolverImpl.log("** REQUIRE " + requires[i].getVersionConstraint().getName() + "[" + requires[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
state.addResolverError(requires[i].getVersionConstraint().getBundle(), ResolverError.MISSING_REQUIRE_BUNDLE, requires[i].getVersionConstraint().toString(), requires[i].getVersionConstraint());
// If the require has failed to resolve and it is from a fragment, then remove the fragment from the host
if (requires[i].isFromFragment()) {
if (!developmentMode) // only detach fragments when not in devmode
resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(requires[i].getVersionConstraint().getBundle()), requires[i]));
continue;
}
failed = true;
if (!developmentMode) // in dev mode continue to next constraint
break;
}
}
}
if (!failed) {
// Iterate thru imports of 'bundle' trying to find matching exports.
ResolverImport[] imports = bundle.getImportPackages();
for (int i = 0; i < imports.length; i++) {
// Only resolve non-dynamic imports here
if (!imports[i].isDynamic() && !resolveImport(imports[i], true, cycle)) {
if (DEBUG || DEBUG_IMPORTS)
ResolverImpl.log("** IMPORT " + imports[i].getName() + "[" + imports[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// If the import has failed to resolve and it is from a fragment, then remove the fragment from the host
state.addResolverError(imports[i].getVersionConstraint().getBundle(), ResolverError.MISSING_IMPORT_PACKAGE, imports[i].getVersionConstraint().toString(), imports[i].getVersionConstraint());
if (imports[i].isFromFragment()) {
if (!developmentMode) // only detach fragments when not in devmode
resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(imports[i].getBundleDescription()), imports[i]));
continue;
}
failed = true;
if (!developmentMode) // in dev mode continue to next constraint
break;
}
}
}
// check that fragment constraints are met by the constraints that got resolved to the host
checkFragmentConstraints(bundle);
// do some extra checking when in development mode to see if other resolver error occurred
if (developmentMode && !failed && state.getResolverErrors(bundle.getBundle()).length > 0)
failed = true;
// Need to check that all mandatory imports are wired. If they are then
// set the bundle RESOLVED, otherwise set it back to UNRESOLVED
if (failed) {
setBundleUnresolved(bundle, false, developmentMode);
if (DEBUG)
ResolverImpl.log(bundle + " NOT RESOLVED"); //$NON-NLS-1$
} else if (!cycle.contains(bundle)) {
setBundleResolved(bundle);
if (DEBUG)
ResolverImpl.log(bundle + " RESOLVED"); //$NON-NLS-1$
}
if (bundle.getState() == ResolverBundle.UNRESOLVED)
bundle.setResolvable(false); // Set it to unresolvable so we don't attempt to resolve it again in this round
// tell the state what we resolved the constraints to
stateResolveConstraints(bundle);
return bundle.getState() != ResolverBundle.UNRESOLVED;
}
| private boolean resolveBundle(ResolverBundle bundle, ArrayList cycle) {
if (bundle.isFragment())
return false;
if (!bundle.isResolvable()) {
if (DEBUG)
ResolverImpl.log(" - " + bundle + " is unresolvable"); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
if (bundle.getState() == ResolverBundle.RESOLVED) {
// 'bundle' is already resolved so just return
if (DEBUG)
ResolverImpl.log(" - " + bundle + " already resolved"); //$NON-NLS-1$ //$NON-NLS-2$
return true;
} else if (bundle.getState() == ResolverBundle.UNRESOLVED) {
// 'bundle' is UNRESOLVED so move to RESOLVING
bundle.clearWires(true);
setBundleResolving(bundle);
}
boolean failed = false;
if (!failed) {
GenericConstraint[] genericRequires = bundle.getGenericRequires();
for (int i = 0; i < genericRequires.length; i++) {
if (!resolveGenericReq(genericRequires[i], cycle)) {
if (DEBUG || DEBUG_GENERICS)
ResolverImpl.log("** GENERICS " + genericRequires[i].getVersionConstraint().getName() + "[" + genericRequires[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
state.addResolverError(genericRequires[i].getVersionConstraint().getBundle(), ResolverError.MISSING_GENERIC_CAPABILITY, genericRequires[i].getVersionConstraint().toString(), genericRequires[i].getVersionConstraint());
if (genericRequires[i].isFromFragment()) {
if (!developmentMode) // only detach fragments when not in devmode
resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(genericRequires[i].getVersionConstraint().getBundle()), null));
continue;
}
if (!developmentMode) {
// fail fast; otherwise we want to attempt to resolver other constraints in dev mode
failed = true;
break;
}
}
}
}
if (!failed) {
// Iterate thru required bundles of 'bundle' trying to find matching bundles.
BundleConstraint[] requires = bundle.getRequires();
for (int i = 0; i < requires.length; i++) {
if (!resolveRequire(requires[i], cycle)) {
if (DEBUG || DEBUG_REQUIRES)
ResolverImpl.log("** REQUIRE " + requires[i].getVersionConstraint().getName() + "[" + requires[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
state.addResolverError(requires[i].getVersionConstraint().getBundle(), ResolverError.MISSING_REQUIRE_BUNDLE, requires[i].getVersionConstraint().toString(), requires[i].getVersionConstraint());
// If the require has failed to resolve and it is from a fragment, then remove the fragment from the host
if (requires[i].isFromFragment()) {
if (!developmentMode) // only detach fragments when not in devmode
resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(requires[i].getVersionConstraint().getBundle()), requires[i]));
continue;
}
if (!developmentMode) {
// fail fast; otherwise we want to attempt to resolver other constraints in dev mode
failed = true;
break;
}
}
}
}
if (!failed) {
// Iterate thru imports of 'bundle' trying to find matching exports.
ResolverImport[] imports = bundle.getImportPackages();
for (int i = 0; i < imports.length; i++) {
// Only resolve non-dynamic imports here
if (!imports[i].isDynamic() && !resolveImport(imports[i], true, cycle)) {
if (DEBUG || DEBUG_IMPORTS)
ResolverImpl.log("** IMPORT " + imports[i].getName() + "[" + imports[i].getBundleDescription() + "] failed to resolve"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// If the import has failed to resolve and it is from a fragment, then remove the fragment from the host
state.addResolverError(imports[i].getVersionConstraint().getBundle(), ResolverError.MISSING_IMPORT_PACKAGE, imports[i].getVersionConstraint().toString(), imports[i].getVersionConstraint());
if (imports[i].isFromFragment()) {
if (!developmentMode) // only detach fragments when not in devmode
resolverExports.remove(bundle.detachFragment((ResolverBundle) bundleMapping.get(imports[i].getBundleDescription()), imports[i]));
continue;
}
if (!developmentMode) {
// fail fast; otherwise we want to attempt to resolver other constraints in dev mode
failed = true;
break;
}
}
}
}
// check that fragment constraints are met by the constraints that got resolved to the host
checkFragmentConstraints(bundle);
// do some extra checking when in development mode to see if other resolver error occurred
if (developmentMode && !failed && state.getResolverErrors(bundle.getBundle()).length > 0)
failed = true;
// Need to check that all mandatory imports are wired. If they are then
// set the bundle RESOLVED, otherwise set it back to UNRESOLVED
if (failed) {
setBundleUnresolved(bundle, false, developmentMode);
if (DEBUG)
ResolverImpl.log(bundle + " NOT RESOLVED"); //$NON-NLS-1$
} else if (!cycle.contains(bundle)) {
setBundleResolved(bundle);
if (DEBUG)
ResolverImpl.log(bundle + " RESOLVED"); //$NON-NLS-1$
}
if (bundle.getState() == ResolverBundle.UNRESOLVED)
bundle.setResolvable(false); // Set it to unresolvable so we don't attempt to resolve it again in this round
// tell the state what we resolved the constraints to
stateResolveConstraints(bundle);
return bundle.getState() != ResolverBundle.UNRESOLVED;
}
|
diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/update/TestTimestampVersion.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/update/TestTimestampVersion.java
index 6e988bc23..ec7995fc1 100644
--- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/update/TestTimestampVersion.java
+++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/update/TestTimestampVersion.java
@@ -1,94 +1,94 @@
/*
* 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.openjpa.persistence.jdbc.update;
import java.sql.Timestamp;
import javax.persistence.EntityManager;
import org.apache.openjpa.persistence.test.SingleEMFTestCase;
/**
* Tests for update on entity that uses a Timestamp as version.
*
* @see <A HREF="https://issues.apache.org/jira/browse/OPENJPA-1583">OPENJPA-1583</A>
*
* @author Pinaki Poddar
*
*/
public class TestTimestampVersion extends SingleEMFTestCase {
public void setUp() {
super.setUp(CLEAR_TABLES, TimestampedEntity.class, NumericVersionedEntity.class);
}
public void testBulkUpdateOnTimestampedVersion() {
TimestampedEntity pc = new TimestampedEntity();
pc.setName("Original");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(pc);
em.getTransaction().commit();
try {
// delay to ensure the new timestamp exceeds the timer's resolution.
- Thread.sleep(500);
+ Thread.sleep(1000);
} catch (InterruptedException e) {
}
em.getTransaction().begin();
Timestamp oldVersion = pc.getVersion();
String jpql = "UPDATE TimestampedEntity t SET t.name=:newname WHERE t.name=:oldname";
em.createQuery(jpql)
.setParameter("newname", "Updated")
.setParameter("oldname", "Original")
.executeUpdate();
em.getTransaction().commit();
em.getTransaction().begin();
em.refresh(pc);
Timestamp newVersion = pc.getVersion();
assertTrue("Expected newVersion=" + newVersion.toString() + " to be after oldVersion=" + oldVersion.toString(),
newVersion.after(oldVersion));
}
public void testBulkUpdateOnNumericVersion() {
NumericVersionedEntity pc = new NumericVersionedEntity();
pc.setName("Original");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(pc);
em.getTransaction().commit();
em.getTransaction().begin();
int oldVersion = pc.getVersion();
String jpql = "UPDATE NumericVersionedEntity t SET t.name=:newname WHERE t.name=:oldname";
em.createQuery(jpql)
.setParameter("newname", "Updated")
.setParameter("oldname", "Original")
.executeUpdate();
em.getTransaction().commit();
em.getTransaction().begin();
em.refresh(pc);
int newVersion = pc.getVersion();
assertEquals(newVersion, oldVersion+1);
}
}
| true | true | public void testBulkUpdateOnTimestampedVersion() {
TimestampedEntity pc = new TimestampedEntity();
pc.setName("Original");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(pc);
em.getTransaction().commit();
try {
// delay to ensure the new timestamp exceeds the timer's resolution.
Thread.sleep(500);
} catch (InterruptedException e) {
}
em.getTransaction().begin();
Timestamp oldVersion = pc.getVersion();
String jpql = "UPDATE TimestampedEntity t SET t.name=:newname WHERE t.name=:oldname";
em.createQuery(jpql)
.setParameter("newname", "Updated")
.setParameter("oldname", "Original")
.executeUpdate();
em.getTransaction().commit();
em.getTransaction().begin();
em.refresh(pc);
Timestamp newVersion = pc.getVersion();
assertTrue("Expected newVersion=" + newVersion.toString() + " to be after oldVersion=" + oldVersion.toString(),
newVersion.after(oldVersion));
}
| public void testBulkUpdateOnTimestampedVersion() {
TimestampedEntity pc = new TimestampedEntity();
pc.setName("Original");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(pc);
em.getTransaction().commit();
try {
// delay to ensure the new timestamp exceeds the timer's resolution.
Thread.sleep(1000);
} catch (InterruptedException e) {
}
em.getTransaction().begin();
Timestamp oldVersion = pc.getVersion();
String jpql = "UPDATE TimestampedEntity t SET t.name=:newname WHERE t.name=:oldname";
em.createQuery(jpql)
.setParameter("newname", "Updated")
.setParameter("oldname", "Original")
.executeUpdate();
em.getTransaction().commit();
em.getTransaction().begin();
em.refresh(pc);
Timestamp newVersion = pc.getVersion();
assertTrue("Expected newVersion=" + newVersion.toString() + " to be after oldVersion=" + oldVersion.toString(),
newVersion.after(oldVersion));
}
|
diff --git a/tween-engine-demo/src/aurelienribon/tweenengine/tests/swing/App.java b/tween-engine-demo/src/aurelienribon/tweenengine/tests/swing/App.java
index 07137dd..6b40dbc 100644
--- a/tween-engine-demo/src/aurelienribon/tweenengine/tests/swing/App.java
+++ b/tween-engine-demo/src/aurelienribon/tweenengine/tests/swing/App.java
@@ -1,62 +1,62 @@
package aurelienribon.tweenengine.tests.swing;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenManager;
import aurelienribon.tweenengine.equations.Back;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class App {
private final JFrame window;
private final JButton button;
private final TweenManager tweenManager;
public App() {
button = new JButton("Push me!");
button.setLocation(10, 10);
button.setSize(button.getPreferredSize());
button.addMouseListener(buttonMouseListener);
button.addActionListener(buttonActionListener);
window = new JFrame("TweenEngine Swing test");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.setLayout(null);
window.getContentPane().add(button);
window.setVisible(true);
- Tween.registerDefaultAccessor(Component.class, new ComponentTweenAccessor());
+ Tween.registerDefaultAccessor(JButton.class, new ComponentTweenAccessor());
tweenManager = new TweenManager();
SwingTweenThread.start(window.getContentPane(), tweenManager);
}
private final MouseAdapter buttonMouseListener = new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
Random rand = new Random();
int tx = rand.nextInt(window.getContentPane().getWidth() - button.getWidth());
int ty = rand.nextInt(window.getContentPane().getHeight() - button.getHeight());
tweenManager.clear();
Tween.to(button, ComponentTweenAccessor.POSITION, 500)
.target(tx, ty)
.ease(Back.OUT)
.addToManager(tweenManager);
}
};
private final ActionListener buttonActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(window, "Congratulations! I guess you had some luck, or resized the window :)");
}
};
}
| true | true | public App() {
button = new JButton("Push me!");
button.setLocation(10, 10);
button.setSize(button.getPreferredSize());
button.addMouseListener(buttonMouseListener);
button.addActionListener(buttonActionListener);
window = new JFrame("TweenEngine Swing test");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.setLayout(null);
window.getContentPane().add(button);
window.setVisible(true);
Tween.registerDefaultAccessor(Component.class, new ComponentTweenAccessor());
tweenManager = new TweenManager();
SwingTweenThread.start(window.getContentPane(), tweenManager);
}
| public App() {
button = new JButton("Push me!");
button.setLocation(10, 10);
button.setSize(button.getPreferredSize());
button.addMouseListener(buttonMouseListener);
button.addActionListener(buttonActionListener);
window = new JFrame("TweenEngine Swing test");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.setLayout(null);
window.getContentPane().add(button);
window.setVisible(true);
Tween.registerDefaultAccessor(JButton.class, new ComponentTweenAccessor());
tweenManager = new TweenManager();
SwingTweenThread.start(window.getContentPane(), tweenManager);
}
|
diff --git a/modules/org.restlet/src/org/restlet/resource/ClientResource.java b/modules/org.restlet/src/org/restlet/resource/ClientResource.java
index f8c82832d..fe3296868 100644
--- a/modules/org.restlet/src/org/restlet/resource/ClientResource.java
+++ b/modules/org.restlet/src/org/restlet/resource/ClientResource.java
@@ -1,829 +1,830 @@
/**
* Copyright 2005-2009 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.resource;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.restlet.Client;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.Uniform;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.ClientInfo;
import org.restlet.data.Conditions;
import org.restlet.data.Cookie;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Preference;
import org.restlet.data.Protocol;
import org.restlet.data.Range;
import org.restlet.data.Reference;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.representation.Representation;
import org.restlet.service.ConverterService;
import org.restlet.util.Series;
/**
* Client-side resource. Acts like a proxy of a target resource.<br>
* <br>
* Concurrency note: instances of the class are not designed to be shared among
* several threads. If thread-safety is necessary, consider using the
* lower-level {@link Client} class instead.<br>
* <br>
* Note: The current implementation isn't complete and doesn't support the full
* syntax. This is work in progress and should only be used for experimentation.
*
* @author Jerome Louvel
*/
public class ClientResource extends UniformResource {
/** Indicates if redirections are followed. */
private volatile boolean followRedirects;
/** The next Restlet. */
private volatile Uniform next;
/**
* Constructor.
*
* @param context
* The context.
* @param method
* The method to call.
* @param reference
* The target reference.
*/
public ClientResource(Context context, Method method,
Reference reference) {
Request request = new Request(method, reference);
Response response = new Response(request);
if (context == null) {
context = Context.getCurrent();
}
if (context != null) {
this.next = context.getClientDispatcher();
}
this.followRedirects = true;
init(context, request, response);
}
/**
* Constructor.
*
* @param context
* The context.
* @param method
* The method to call.
* @param uri
* The target URI.
*/
public ClientResource(Context context, Method method, String uri) {
this(context, method, new Reference(uri));
}
/**
* Constructor.
*
* @param context
* The context.
* @param method
* The method to call.
* @param uri
* The target URI.
*/
public ClientResource(Context context, Method method, URI uri) {
this(context, method, new Reference(uri));
}
/**
* Constructor.
*
* @param context
* The context.
* @param reference
* The target reference.
*/
public ClientResource(Context context, Reference reference) {
this(context, Method.GET, reference);
}
/**
* Constructor.
*
* @param context
* The current context.
* @param request
* The handled request.
* @param response
* The handled response.
*/
public ClientResource(Context context, Request request,
Response response) {
this.followRedirects = true;
init(context, request, response);
}
/**
* Constructor.
*
* @param context
* The context.
* @param uri
* The target URI.
*/
public ClientResource(Context context, String uri) {
this(context, Method.GET, uri);
}
/**
* Constructor.
*
* @param context
* The context.
* @param uri
* The target URI.
*/
public ClientResource(Context context, URI uri) {
this(context, Method.GET, uri);
}
/**
* Constructor.
*
* @param method
* The method to call.
* @param reference
* The target reference.
*/
public ClientResource(Method method, Reference reference) {
this(Context.getCurrent(), method, reference);
}
/**
* Constructor.
*
* @param method
* The method to call.
* @param uri
* The target URI.
*/
public ClientResource(Method method, String uri) {
this(Context.getCurrent(), method, uri);
}
/**
* Constructor.
*
* @param method
* The method to call.
* @param uri
* The target URI.
*/
public ClientResource(Method method, URI uri) {
this(Context.getCurrent(), method, uri);
}
/**
* Constructor.
*
* @param reference
* The target reference.
*/
public ClientResource(Reference reference) {
this(Context.getCurrent(), null, reference);
}
/**
* Constructor.
*
* @param request
* The handled request.
* @param response
* The handled response.
*/
public ClientResource(Request request, Response response) {
this(Context.getCurrent(), request, response);
}
/**
* Constructor.
*
* @param uri
* The target URI.
*/
public ClientResource(String uri) {
this(Context.getCurrent(), null, uri);
}
/**
* Constructor.
*
* @param uri
* The target URI.
*/
public ClientResource(URI uri) {
this(Context.getCurrent(), null, uri);
}
/**
* Deletes the target resource and all its representations.<br>
* <br>
* If a success status is not returned, then a resource exception is thrown.
*
* @return The optional response entity.
*/
public Representation delete() throws ResourceException {
setMethod(Method.DELETE);
return handle();
}
/**
* Calls the {@link #release()}.
*/
@Override
protected void finalize() throws Throwable {
release();
}
/**
* Represents the resource using content negotiation to select the best
* variant based on the client preferences.<br>
* <br>
* Note that the client preferences will be automatically adjusted, but only
* for this request. If you want to change them once for all, you can use
* the {@link #getClientInfo()} method.<br>
* <br>
* If a success status is not returned, then a resource exception is thrown.
*
* @return The best representation.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3">HTTP
* GET method</a>
*/
public Representation get() throws ResourceException {
setMethod(Method.GET);
return handle();
}
/**
* Represents the resource using a given media type.<br>
* <br>
* Note that the client preferences will be automatically adjusted, but only
* for this request. If you want to change them once for all, you can use
* the {@link #getClientInfo()} method.<br>
* <br>
* If a success status is not returned, then a resource exception is thrown.
*
* @param mediaType
* The media type of the representation to retrieve.
* @return The representation matching the given media type.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3">HTTP
* GET method</a>
*/
public Representation get(MediaType mediaType)
throws ResourceException {
// Save the current client info
ClientInfo currentClientInfo = getClientInfo();
// Create a fresh one for this request
ClientInfo newClientInfo = new ClientInfo();
newClientInfo.getAcceptedMediaTypes().add(
new Preference<MediaType>(mediaType));
setClientInfo(newClientInfo);
Representation result = get();
// Restore the current client info
setClientInfo(currentClientInfo);
return result;
}
/**
* Returns the next Restlet. By default, it is the client dispatcher if a
* context is available.
*
* @return The next Restlet or null.
*/
public Uniform getNext() {
return this.next;
}
/**
* Handles the call by invoking the next handler.
*
* @return The optional response entity.
* @see #getNext()
*/
@Override
public Representation handle() {
Representation result = null;
if (!hasNext()) {
Protocol protocol = (getReference() == null) ? null
: getReference().getSchemeProtocol();
if (protocol != null) {
setNext(new Client(protocol));
}
}
if (hasNext()) {
handle(getRequest(), getResponse(), null);
result = getResponse().getEntity();
} else {
getLogger()
.warning(
"Unable to process the call for a client resource. No next Restlet has been provided.");
}
return result;
}
/**
* Handle the call and follow redirection for safe methods.
*
* @param request
* The request to send.
* @param response
* The response to update.
* @param references
* The references that caused a redirection to prevent infinite
* loops.
*/
private void handle(Request request, Response response,
List<Reference> references) {
// Actually handle the call
getNext().handle(request, response);
// Check for redirections
if (request.getMethod().isSafe()
- && response.getStatus().isRedirection()) {
+ && response.getStatus().isRedirection()
+ && response.getLocationRef() != null) {
Reference newTargetRef = response.getLocationRef();
if ((references != null) && references.contains(newTargetRef)) {
getLogger().warning(
"Infinite redirection loop detected with URI: "
+ newTargetRef);
} else if (request.getEntity() != null
&& !request.isEntityAvailable()) {
getLogger()
.warning(
"Unable to follow the redirection because the request entity isn't available anymore.");
} else {
if (references == null) {
references = new ArrayList<Reference>();
}
// Add to the list of redirection reference
// to prevent infinite loops
references.add(request.getResourceRef());
request.setResourceRef(newTargetRef);
handle(request, response, references);
}
}
}
/**
* Indicates if there is a next Restlet.
*
* @return True if there is a next Restlet.
*/
public boolean hasNext() {
return getNext() != null;
}
/**
* Represents the resource using content negotiation to select the best
* variant based on the client preferences. This method is identical to
* {@link #get()} but doesn't return the actual content of the
* representation, only its metadata.<br>
* <br>
* Note that the client preferences will be automatically adjusted, but only
* for this request. If you want to change them once for all, you can use
* the {@link #getClientInfo()} method.<br>
* <br>
* If a success status is not returned, then a resource exception is thrown.
*
* @return The best representation.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4">HTTP
* HEAD method</a>
*/
public Representation head() throws ResourceException {
setMethod(Method.HEAD);
return handle();
}
/**
* Represents the resource using a given media type. This method is
* identical to {@link #get(MediaType)} but doesn't return the actual
* content of the representation, only its metadata.<br>
* <br>
* Note that the client preferences will be automatically adjusted, but only
* for this request. If you want to change them once for all, you can use
* the {@link #getClientInfo()} method.<br>
* <br>
* If a success status is not returned, then a resource exception is thrown.
*
* @param mediaType
* The media type of the representation to retrieve.
* @return The representation matching the given media type.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4">HTTP
* HEAD method</a>
*/
public Representation head(MediaType mediaType)
throws ResourceException {
// Save the current client info
ClientInfo currentClientInfo = getClientInfo();
// Create a fresh one for this request
ClientInfo newClientInfo = new ClientInfo();
newClientInfo.getAcceptedMediaTypes().add(
new Preference<MediaType>(mediaType));
setClientInfo(newClientInfo);
Representation result = head();
// Restore the current client info
setClientInfo(currentClientInfo);
return result;
}
/**
* Indicates if redirections are followed.
*
* @return True if redirections are followed.
*/
public boolean isFollowRedirects() {
return followRedirects;
}
/**
* Describes the resource using content negotiation to select the best
* variant based on the client preferences.<br>
* <br>
* If a success status is not returned, then a resource exception is thrown.
*
* @return The best description.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2">HTTP
* OPTIONS method</a>
*/
public Representation options() throws ResourceException {
setMethod(Method.HEAD);
return handle();
}
/**
* Describes the resource using a given media type.<br>
* <br>
* If a success status is not returned, then a resource exception is thrown.
*
* @param mediaType
* The media type of the representation to retrieve.
* @return The matched description or null.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2">HTTP
* OPTIONS method</a>
*/
public Representation options(MediaType mediaType)
throws ResourceException {
// Save the current client info
ClientInfo currentClientInfo = getClientInfo();
// Create a fresh one for this request
ClientInfo newClientInfo = new ClientInfo();
newClientInfo.getAcceptedMediaTypes().add(
new Preference<MediaType>(mediaType));
setClientInfo(newClientInfo);
Representation result = options();
// Restore the current client info
setClientInfo(currentClientInfo);
return result;
}
/**
* TODO
*
* @param entity
* @return
* @throws ResourceException
*/
public Object post(Object entity) throws ResourceException {
Object result = null;
ConverterService cs = null;
if (getApplication() != null) {
cs = getApplication().getConverterService();
} else {
cs = new ConverterService();
}
Representation requestEntity = cs.toRepresentation(entity);
Representation responseEntity = post(requestEntity);
if (responseEntity != null) {
try {
result = cs.toObject(responseEntity);
} catch (IOException e) {
throw new ResourceException(e);
}
}
return result;
}
/**
* Posts a representation to the resource at the target URI reference.<br>
* <br>
* If a success status is not returned, then a resource exception is thrown.
*
* @param entity
* The posted entity.
* @return The optional result entity.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5">HTTP
* POST method</a>
*/
public Representation post(Representation entity)
throws ResourceException {
setMethod(Method.POST);
getRequest().setEntity(entity);
return handle();
}
/**
* Creates or updates a resource with the given representation as new state
* to be stored.<br>
* <br>
* If a success status is not returned, then a resource exception is thrown.
*
* @param representation
* The representation to store.
* @return The optional result entity.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6">HTTP
* PUT method</a>
*/
public Representation put(Representation representation)
throws ResourceException {
setMethod(Method.PUT);
getRequest().setEntity(representation);
return handle();
}
/**
* Sets the authentication response sent by a client to an origin server.
*
* @param challengeResponse
* The authentication response sent by a client to an origin
* server.
* @see Request#setChallengeResponse(ChallengeResponse)
*/
public void setChallengeResponse(ChallengeResponse challengeResponse) {
getRequest().setChallengeResponse(challengeResponse);
}
/**
* Sets the authentication response sent by a client to an origin server
* given a scheme, identifier and secret.
*
* @param scheme
* The challenge scheme.
* @param identifier
* The user identifier, such as a login name or an access key.
* @param secret
* The user secret, such as a password or a secret key.
*/
public void setChallengeResponse(ChallengeScheme scheme,
final String identifier, String secret) {
setChallengeResponse(new ChallengeResponse(scheme, identifier,
secret));
}
/**
* Sets the client-specific information.
*
* @param clientInfo
* The client-specific information.
* @see Request#setClientInfo(ClientInfo)
*/
public void setClientInfo(ClientInfo clientInfo) {
getRequest().setClientInfo(clientInfo);
}
/**
* Sets the conditions applying to this request.
*
* @param conditions
* The conditions applying to this request.
* @see Request#setConditions(Conditions)
*/
public void setConditions(Conditions conditions) {
getRequest().setConditions(conditions);
}
/**
* Sets the cookies provided by the client.
*
* @param cookies
* The cookies provided by the client.
* @see Request#setCookies(Series)
*/
public void setCookies(Series<Cookie> cookies) {
getRequest().setCookies(cookies);
}
/**
* Indicates if redirections are followed.
*
* @param followRedirects
* True if redirections are followed.
*/
public void setFollowRedirects(boolean followRedirects) {
this.followRedirects = followRedirects;
}
/**
* Sets the host reference.
*
* @param hostRef
* The host reference.
* @see Request#setHostRef(Reference)
*/
public void setHostRef(Reference hostRef) {
getRequest().setHostRef(hostRef);
}
/**
* Sets the host reference using an URI string.
*
* @param hostUri
* The host URI.
* @see Request#setHostRef(String)
*/
public void setHostRef(String hostUri) {
getRequest().setHostRef(hostUri);
}
/**
* Sets the method called.
*
* @param method
* The method called.
* @see Request#setMethod(Method)
*/
public void setMethod(Method method) {
getRequest().setMethod(method);
}
/**
* Sets the next handler such as a Restlet or a Filter.
*
* In addition, this method will set the context of the next Restlet if it
* is null by passing a reference to its own context.
*
* @param next
* The next handler.
*/
public void setNext(org.restlet.Uniform next) {
if (next instanceof Restlet) {
Restlet nextRestlet = (Restlet) next;
if (nextRestlet.getContext() == null) {
nextRestlet.setContext(getContext());
}
}
this.next = next;
}
/**
* Sets the original reference requested by the client.
*
* @param originalRef
* The original reference.
* @see Request#setOriginalRef(Reference)
*/
public void setOriginalRef(Reference originalRef) {
getRequest().setOriginalRef(originalRef);
}
/**
* Sets the ranges to return from the target resource's representation.
*
* @param ranges
* The ranges.
* @see Request#setRanges(List)
*/
public void setRanges(List<Range> ranges) {
getRequest().setRanges(ranges);
}
/**
* Sets the target resource reference. If the reference is relative, it will
* be resolved as an absolute reference. Also, the context's base reference
* will be reset. Finally, the reference will be normalized to ensure a
* consistent handling of the call.
*
* @param resourceRef
* The resource reference.
* @see Request#setResourceRef(Reference)
*/
public void setReference(Reference resourceRef) {
getRequest().setResourceRef(resourceRef);
}
/**
* Sets the referrer reference if available.
*
* @param referrerRef
* The referrer reference.
* @see Request#setReferrerRef(Reference)
*/
public void setReferrerRef(Reference referrerRef) {
getRequest().setReferrerRef(referrerRef);
}
/**
* Sets the referrer reference if available using an URI string.
*
* @param referrerUri
* The referrer URI.
* @see Request#setReferrerRef(String)
*/
public void setReferrerRef(String referrerUri) {
getRequest().setReferrerRef(referrerUri);
}
/**
* Sets the target resource reference using a Reference. Note that the
* Reference can be either absolute or relative to the context's base
* reference.
*
* @param resourceRef
* The resource Reference.
* @see Request#setResourceRef(Reference)
*/
public void setResourceRef(Reference resourceRef) {
getRequest().setResourceRef(resourceRef);
}
/**
* Sets the target resource reference using an URI string. Note that the URI
* can be either absolute or relative to the context's base reference.
*
* @param resourceUri
* The resource URI.
* @see Request#setResourceRef(String)
*/
public void setResourceRef(String resourceUri) {
getRequest().setResourceRef(resourceUri);
}
}
| true | true | private void handle(Request request, Response response,
List<Reference> references) {
// Actually handle the call
getNext().handle(request, response);
// Check for redirections
if (request.getMethod().isSafe()
&& response.getStatus().isRedirection()) {
Reference newTargetRef = response.getLocationRef();
if ((references != null) && references.contains(newTargetRef)) {
getLogger().warning(
"Infinite redirection loop detected with URI: "
+ newTargetRef);
} else if (request.getEntity() != null
&& !request.isEntityAvailable()) {
getLogger()
.warning(
"Unable to follow the redirection because the request entity isn't available anymore.");
} else {
if (references == null) {
references = new ArrayList<Reference>();
}
// Add to the list of redirection reference
// to prevent infinite loops
references.add(request.getResourceRef());
request.setResourceRef(newTargetRef);
handle(request, response, references);
}
}
}
| private void handle(Request request, Response response,
List<Reference> references) {
// Actually handle the call
getNext().handle(request, response);
// Check for redirections
if (request.getMethod().isSafe()
&& response.getStatus().isRedirection()
&& response.getLocationRef() != null) {
Reference newTargetRef = response.getLocationRef();
if ((references != null) && references.contains(newTargetRef)) {
getLogger().warning(
"Infinite redirection loop detected with URI: "
+ newTargetRef);
} else if (request.getEntity() != null
&& !request.isEntityAvailable()) {
getLogger()
.warning(
"Unable to follow the redirection because the request entity isn't available anymore.");
} else {
if (references == null) {
references = new ArrayList<Reference>();
}
// Add to the list of redirection reference
// to prevent infinite loops
references.add(request.getResourceRef());
request.setResourceRef(newTargetRef);
handle(request, response, references);
}
}
}
|
diff --git a/src/main/java/network/RemCat.java b/src/main/java/network/RemCat.java
index 664e7709..d54aaec1 100755
--- a/src/main/java/network/RemCat.java
+++ b/src/main/java/network/RemCat.java
@@ -1,144 +1,144 @@
import java.io.*;
import java.net.*;
/**
* RemCat - remotely cat (DOS type) a file, using the TFTP protocol.
* Inspired by the "rcat" exercise in Learning Tree Course 363,
* <I>UNIX Network Programming</I>, by Dr. Chris Brown.
*
* Note that the TFTP server is NOT "internationalized"; the name and
* mode in the protocol are defined in terms of ASCII, not UniCode.
*
* @author Chris R. Brown, original C version
* @author Java version by Ian Darwin, [email protected].
*/
public class RemCat {
/** The UDP port number */
public final static int TFTP_PORT = 69;
/** The mode we will use - octet for everything. */
protected final String MODE = "octet";
/** The offset for the code/response as a byte */
protected final int OFFSET_REQUEST = 1;
/** The offset for the packet number as a byte */
protected final int OFFSET_PACKETNUM = 3;
/** Debugging flag */
protected static boolean debug = false;
/** TFTP op-code for a read request */
public final int OP_RRQ = 1,
/** TFTP op-code for a read request */
OP_WRQ = 2,
/** TFTP op-code for a read request */
OP_DATA = 3,
/** TFTP op-code for a read request */
OP_ACK = 4,
/** TFTP op-code for a read request */
OP_ERROR = 5;
protected final static int PACKET_SIZE = 516; // == 2 + 2 + 512
protected String host;
protected InetAddress servAddr;
protected DatagramSocket sock;
protected byte buffer[];
protected DatagramPacket inp, outp;
/** The main program that drives this network client.
* @param argv[0] hostname, running TFTP server
* @param argv[1..n] filename(s), must be at least one
*/
public static void main(String[] argv) throws IOException {
if (argv.length < 2) {
System.err.println("usage: rcat host filename[...]");
System.exit(1);
}
if (debug)
System.err.println("Java RemCat starting");
RemCat rc = new RemCat(argv[0]);
for (int i = 1; i<argv.length; i++) {
if (debug)
System.err.println("-- Starting file " +
argv[0] + ":" + argv[i] + "---");
rc.readFile(argv[i]);
}
}
RemCat(String host) throws IOException {
super();
this.host = host;
servAddr = InetAddress.getByName(host);
sock = new DatagramSocket();
buffer = new byte[PACKET_SIZE];
outp = new DatagramPacket(buffer, PACKET_SIZE, servAddr, TFTP_PORT);
inp = new DatagramPacket(buffer, PACKET_SIZE);
}
/* Build a TFTP Read Request packet. This is messy because the
* fields have variable length. Numbers must be in
* network order, too; fortunately Java just seems
* naturally smart enough :-) to use network byte order.
*/
void readFile(String path) throws IOException {
byte[] bTemp;
buffer[0] = 0;
buffer[OFFSET_REQUEST] = OP_RRQ; // read request
int p = 2; // number of chars into buffer
// Convert filename String to bytes in buffer , using "p" as an
// offset indicator to get all the bits of this request
// in exactly the right spot.
- bTemp = path.getBytes();
+ bTemp = path.getBytes("ISO8859_1"); // i.e., ASCII
System.arraycopy(bTemp, 0, buffer, p, path.length());
p += path.length();
buffer[p++] = 0; // null byte terminates string
// Similarly, convert MODE ("octet") to bytes in buffer
- bTemp = MODE.getBytes();
+ bTemp = MODE.getBytes("ISO8859_1"); // i.e., ASCII
System.arraycopy(bTemp, 0, buffer, p, MODE.length());
p += MODE.length();
buffer[p++] = 0; // null terminate
/* Send Read Request to tftp server */
outp.setLength(p);
sock.send(outp);
/* Loop reading data packets from the server until a short
* packet arrives; this indicates the end of the file.
*/
int len = 0;
do {
sock.receive(inp);
if (debug)
System.err.println(
"Packet # " + Byte.toString(buffer[OFFSET_PACKETNUM])+
"RESPONSE CODE " + Byte.toString(buffer[OFFSET_REQUEST]));
if (buffer[OFFSET_REQUEST] == OP_ERROR) {
System.err.println("rcat ERROR: " +
new String(buffer, 4, inp.getLength()-4));
return;
}
if (debug)
System.err.println("Got packet of size " +
inp.getLength());
/* Print the data from the packet */
System.out.write(buffer, 4, inp.getLength()-4);
/* Ack the packet. The block number we
* want to ack is already in buffer so
* we just change the opcode. The ACK is
* sent to the port number which the server
* just sent the data from, NOT to port
* TFTP_PORT.
*/
buffer[OFFSET_REQUEST] = OP_ACK;
outp.setLength(4);
outp.setPort(inp.getPort());
sock.send(outp);
} while (inp.getLength() == PACKET_SIZE);
if (debug)
System.err.println("** ALL DONE** Leaving loop, last size " +
inp.getLength());
}
}
| false | true | void readFile(String path) throws IOException {
byte[] bTemp;
buffer[0] = 0;
buffer[OFFSET_REQUEST] = OP_RRQ; // read request
int p = 2; // number of chars into buffer
// Convert filename String to bytes in buffer , using "p" as an
// offset indicator to get all the bits of this request
// in exactly the right spot.
bTemp = path.getBytes();
System.arraycopy(bTemp, 0, buffer, p, path.length());
p += path.length();
buffer[p++] = 0; // null byte terminates string
// Similarly, convert MODE ("octet") to bytes in buffer
bTemp = MODE.getBytes();
System.arraycopy(bTemp, 0, buffer, p, MODE.length());
p += MODE.length();
buffer[p++] = 0; // null terminate
/* Send Read Request to tftp server */
outp.setLength(p);
sock.send(outp);
/* Loop reading data packets from the server until a short
* packet arrives; this indicates the end of the file.
*/
int len = 0;
do {
sock.receive(inp);
if (debug)
System.err.println(
"Packet # " + Byte.toString(buffer[OFFSET_PACKETNUM])+
"RESPONSE CODE " + Byte.toString(buffer[OFFSET_REQUEST]));
if (buffer[OFFSET_REQUEST] == OP_ERROR) {
System.err.println("rcat ERROR: " +
new String(buffer, 4, inp.getLength()-4));
return;
}
if (debug)
System.err.println("Got packet of size " +
inp.getLength());
/* Print the data from the packet */
System.out.write(buffer, 4, inp.getLength()-4);
/* Ack the packet. The block number we
* want to ack is already in buffer so
* we just change the opcode. The ACK is
* sent to the port number which the server
* just sent the data from, NOT to port
* TFTP_PORT.
*/
buffer[OFFSET_REQUEST] = OP_ACK;
outp.setLength(4);
outp.setPort(inp.getPort());
sock.send(outp);
} while (inp.getLength() == PACKET_SIZE);
if (debug)
System.err.println("** ALL DONE** Leaving loop, last size " +
inp.getLength());
}
| void readFile(String path) throws IOException {
byte[] bTemp;
buffer[0] = 0;
buffer[OFFSET_REQUEST] = OP_RRQ; // read request
int p = 2; // number of chars into buffer
// Convert filename String to bytes in buffer , using "p" as an
// offset indicator to get all the bits of this request
// in exactly the right spot.
bTemp = path.getBytes("ISO8859_1"); // i.e., ASCII
System.arraycopy(bTemp, 0, buffer, p, path.length());
p += path.length();
buffer[p++] = 0; // null byte terminates string
// Similarly, convert MODE ("octet") to bytes in buffer
bTemp = MODE.getBytes("ISO8859_1"); // i.e., ASCII
System.arraycopy(bTemp, 0, buffer, p, MODE.length());
p += MODE.length();
buffer[p++] = 0; // null terminate
/* Send Read Request to tftp server */
outp.setLength(p);
sock.send(outp);
/* Loop reading data packets from the server until a short
* packet arrives; this indicates the end of the file.
*/
int len = 0;
do {
sock.receive(inp);
if (debug)
System.err.println(
"Packet # " + Byte.toString(buffer[OFFSET_PACKETNUM])+
"RESPONSE CODE " + Byte.toString(buffer[OFFSET_REQUEST]));
if (buffer[OFFSET_REQUEST] == OP_ERROR) {
System.err.println("rcat ERROR: " +
new String(buffer, 4, inp.getLength()-4));
return;
}
if (debug)
System.err.println("Got packet of size " +
inp.getLength());
/* Print the data from the packet */
System.out.write(buffer, 4, inp.getLength()-4);
/* Ack the packet. The block number we
* want to ack is already in buffer so
* we just change the opcode. The ACK is
* sent to the port number which the server
* just sent the data from, NOT to port
* TFTP_PORT.
*/
buffer[OFFSET_REQUEST] = OP_ACK;
outp.setLength(4);
outp.setPort(inp.getPort());
sock.send(outp);
} while (inp.getLength() == PACKET_SIZE);
if (debug)
System.err.println("** ALL DONE** Leaving loop, last size " +
inp.getLength());
}
|
diff --git a/test/unittest/src/edu/columbia/mipl/matops/MatrixOperationTest.java b/test/unittest/src/edu/columbia/mipl/matops/MatrixOperationTest.java
index cf55373..4c9354a 100644
--- a/test/unittest/src/edu/columbia/mipl/matops/MatrixOperationTest.java
+++ b/test/unittest/src/edu/columbia/mipl/matops/MatrixOperationTest.java
@@ -1,362 +1,362 @@
/*
* MIPL: Mining Integrated Programming Language
*
* File: MatrixOperationTest.java
* Author: Jin Hyung Park <[email protected]>
* Reviewer: Young Hoon Jung <[email protected]>
* Description: Matrix Operations Test Unit
*
*/
package edu.columbia.mipl.matops;
import java.util.*;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import edu.columbia.mipl.datastr.*;
import edu.columbia.mipl.matops.*;
import edu.columbia.mipl.builtin.matrix.*;
public class MatrixOperationTest extends TestCase {
double data3x3_1[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
double data3x3_2[] = {2, 4, 6, 2, 4, 6, 2, 4, 6};
double data3x3_3[] = {2.0, 2.0, 0.0, -2.0, 1.0, 1.0, 3.0, 0.0, 1.0};
double data3x3_add_1_2[] = {3, 6, 9, 3, 6, 9, 3, 6, 9};
double data3x3_sub_1_2[] = {-1, -2, -3, -1, -2, -3, -1, -2, -3};
double data3x3_mult_1_2[] = {12, 24, 36, 12, 24, 36, 12, 24, 36};
double data1x3_1[] = {1, 2, 3};
double data3x1_2[] = {1, 2, 3};
double data1x1_mult_1_2[] = {14};
protected MatrixOperations matOpObj;
public static void main(String args[]) {
junit.textui.TestRunner.run (suite());
}
@Override
protected void setUp() {
matOpObj = new DefaultMatrixOperations();
}
public void testMatrixSame() {
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, data3x3_1);
final PrimitiveMatrix mat3x3 = new PrimitiveMatrix((PrimitiveArray) mat3x3_1);
assertTrue(mat3x3.getData().equalsSemantically(mat3x3.getData()));
}
public void testMatrixAdd() {
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray mat3x3_2 = new PrimitiveDoubleArray(3, 3, data3x3_2);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x3_2);
final PrimitiveDoubleArray mat3x3_3_add_1_2 = new PrimitiveDoubleArray(3, 3, data3x3_add_1_2);
final PrimitiveMatrix matR = new PrimitiveMatrix(mat3x3_3_add_1_2);
PrimitiveMatrix mat = matOpObj.add(mat1, mat2);
assertTrue(mat.getData().equalsSemantically(matR.getData()));
}
public void testMatrixSub() {
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray mat3x3_2 = new PrimitiveDoubleArray(3, 3, data3x3_2);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x3_2);
final PrimitiveDoubleArray mat3x3_3_sub_1_2 = new PrimitiveDoubleArray(3, 3, data3x3_sub_1_2);
final PrimitiveMatrix matR = new PrimitiveMatrix(mat3x3_3_sub_1_2);
PrimitiveMatrix mat = matOpObj.sub(mat1, mat2);
assertTrue(mat.getData().equalsSemantically(matR.getData()));
}
public void testMatrixMult_3x3() {
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray mat3x3_2 = new PrimitiveDoubleArray(3, 3, data3x3_2);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x3_2);
final PrimitiveDoubleArray mat3x3_3_mult_1_2 = new PrimitiveDoubleArray(3, 3, data3x3_mult_1_2);
final PrimitiveMatrix matR = new PrimitiveMatrix(mat3x3_3_mult_1_2);
PrimitiveMatrix mat = matOpObj.mult(mat1, mat2);
assertTrue(mat.getData().equalsSemantically(matR.getData()));
}
public void testMatrixMult_1x3_3x1_1x1() {
final PrimitiveDoubleArray mat1x3_1 = new PrimitiveDoubleArray(1, 3, data1x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat1x3_1);
final PrimitiveDoubleArray mat3x1_2 = new PrimitiveDoubleArray(3, 1, data3x1_2);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x1_2);
final PrimitiveDoubleArray mat1x1_3_mult_1_2 = new PrimitiveDoubleArray(1, 1, data1x1_mult_1_2);
final PrimitiveMatrix matR = new PrimitiveMatrix(mat1x1_3_mult_1_2);
PrimitiveMatrix mat = matOpObj.mult(mat1, mat2);
assertTrue(mat.getData().equalsSemantically(matR.getData()));
}
public void testMatrixMult_3x3_by_scalar() {
final double scalar = 2;
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray mat3x3_2 = new PrimitiveDoubleArray(3, 3, data3x3_2);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x3_2);
PrimitiveMatrix mat = matOpObj.mult(mat1, scalar);
assertTrue(mat.getData().equalsSemantically(mat2.getData()));
}
public void testMatrix_Assign() {
double copy_data3x3_1[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray mat3x3_2 = new PrimitiveDoubleArray(3, 3, data3x3_1);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x3_2);
matOpObj.assign(mat1, mat2);
assertTrue(mat1.getData().equalsSemantically(mat2.getData()));
}
public void testMatrix_addAssign() {
double copy_data3x3_1[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
double copy_data3x3_2[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
double copy_data3x3_3[] = {2, 4, 6, 2, 4, 6, 2, 4, 6};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray mat3x3_2 = new PrimitiveDoubleArray(3, 3, copy_data3x3_2);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x3_2);
final PrimitiveDoubleArray mat3x3_3 = new PrimitiveDoubleArray(3, 3, copy_data3x3_3);
final PrimitiveMatrix mat3 = new PrimitiveMatrix(mat3x3_3);
matOpObj.addassign(mat1, mat2);
assertTrue(mat3.getData().equalsSemantically(mat1.getData()));
}
public void testMatrix_subAssign() {
double copy_data3x3_1[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
double copy_data3x3_2[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
double copy_data3x3_3[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray mat3x3_2 = new PrimitiveDoubleArray(3, 3, copy_data3x3_2);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x3_2);
final PrimitiveDoubleArray mat3x3_3 = new PrimitiveDoubleArray(3, 3, copy_data3x3_3);
final PrimitiveMatrix mat3 = new PrimitiveMatrix(mat3x3_3);
matOpObj.subassign(mat1, mat2);
assertTrue(mat3.getData().equalsSemantically(mat1.getData()));
}
public void testMatrix_multAssign() {
double copy_data3x3_1[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
double copy_data3x3_2[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
double copy_data3x3_3[] = {6, 12, 18, 6, 12, 18, 6, 12, 18};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray mat3x3_2 = new PrimitiveDoubleArray(3, 3, copy_data3x3_2);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x3_2);
final PrimitiveDoubleArray mat3x3_3 = new PrimitiveDoubleArray(3, 3, copy_data3x3_3);
final PrimitiveMatrix mat3 = new PrimitiveMatrix(mat3x3_3);
matOpObj.multassign(mat1, mat2);
assertTrue(mat3.getData().equalsSemantically(mat1.getData()));
}
public void testMatrix_cellMultAssign() {
double copy_data3x3_1[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
double copy_data3x3_2[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
double copy_data3x3_3[] = {1, 4, 9, 1, 4, 9, 1, 4, 9};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray mat3x3_2 = new PrimitiveDoubleArray(3, 3, copy_data3x3_2);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x3_2);
final PrimitiveDoubleArray mat3x3_3 = new PrimitiveDoubleArray(3, 3, copy_data3x3_3);
final PrimitiveMatrix mat3 = new PrimitiveMatrix(mat3x3_3);
matOpObj.cellmultassign(mat1, mat2);
assertTrue(mat3.getData().equalsSemantically(mat1.getData()));
}
public void testMatrix_cellDivAssign() {
double copy_data3x3_1[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
double copy_data3x3_2[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
double copy_data3x3_3[] = {1, 1, 1, 1, 1, 1, 1, 1, 1};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray mat3x3_2 = new PrimitiveDoubleArray(3, 3, copy_data3x3_2);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x3_2);
final PrimitiveDoubleArray mat3x3_3 = new PrimitiveDoubleArray(3, 3, copy_data3x3_3);
final PrimitiveMatrix mat3 = new PrimitiveMatrix(mat3x3_3);
matOpObj.celldivassign(mat1, mat2);
assertTrue(mat3.getData().equalsSemantically(mat1.getData()));
}
public void testMatrix_Transpose() {
final PrimitiveDoubleArray mat1x3_1 = new PrimitiveDoubleArray(1, 3, data1x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat1x3_1);
final PrimitiveDoubleArray mat3x1_1 = new PrimitiveDoubleArray(3, 1, data3x1_2);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x1_1);
PrimitiveMatrix mat = matOpObj.transpose(mat1);
assertTrue(mat.getData().equalsSemantically(mat2.getData()));
}
/* There is no Determinant function on MatrixOperations */
/*
public void testMatrix_Determinant() {
double data2x2_1[] = {2, 2, 1, 3};
final PrimitiveDoubleArray mat2x2_1 = new PrimitiveDoubleArray(2, 2, data2x2_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat2x2_1);
double det = matOpObj.determinant(mat1);
assertTrue(det == 4);
}
*/
/* There is no Minor function on MatrixOperations */
/*
public void testMatrix_Minor() {
double copy_data3x3_1[] = {1, 2, 3, 1, 2, 3, 1, 2, 3};
double copy_data2x2_1[] = {1, 3, 1, 3};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray mat2x2_1 = new PrimitiveDoubleArray(2, 2, copy_data2x2_1);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat2x2_1);
// remove 2nd row and 2nd col, so input row and col will be 1, 1
PrimitiveMatrix matI = matOpObj.minor(mat1, 1, 1);
assertTrue(matI.getData().equalsSemantically(mat2.getData()));
}
*/
public void testMatrix_Inverse() {
double copy_data3x3_1[] = {1, -1, 1, 0, 2, -1, 2, 3, 0};
double i_data3x3_1[] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray i_mat3x3 = new PrimitiveDoubleArray(3, 3, i_data3x3_1);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(i_mat3x3);
PrimitiveMatrix matI = matOpObj.inverse(mat1);
PrimitiveMatrix matII = matOpObj.mult(matI, mat1);
assertTrue(matII.getData().equalsSemantically(mat2.getData()));
}
public void testMatrix_div() {
double copy_data3x3_1[] = {1, -1, 1, 0, 2, -1, 2, 3, 0};
double i_data3x3_1[] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray mat3x3_2 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(mat3x3_2);
final PrimitiveDoubleArray i_mat3x3 = new PrimitiveDoubleArray(3, 3, i_data3x3_1);
final PrimitiveMatrix i_mat = new PrimitiveMatrix(i_mat3x3);
/* mat3x3_1 and mat3x3_2 are same matrix,
* so, the division result will be the identity matrix i_mat3x3 */
PrimitiveMatrix matI = matOpObj.div(mat1, mat2);
assertTrue(matI.getData().equalsSemantically(i_mat.getData()));
}
public void testMatrix_sum() {
double copy_data3x3_1[] = {1, -1, 1,
0, 2, -1,
2, 3, 0};
double result = 7;
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
double compare = matOpObj.sum(mat1);
assertTrue(compare == result);
}
public void testMatrix_rowsum() {
double copy_data3x3_1[] = {1, -1, 1,
0, 2, -1,
2, 3, 0};
double result_rowsum[] = {3, 4, 0};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray r_rowsum_a = new PrimitiveDoubleArray(1, 3, result_rowsum);
final PrimitiveMatrix r_rowsum = new PrimitiveMatrix(r_rowsum_a);
PrimitiveMatrix matI = matOpObj.rowsum(mat1);
assertTrue(r_rowsum.getData().equalsSemantically(matI.getData()));
}
public void testMatrix_mean() {
double copy_data3x3_1[] = {1, -1, 1,
0, 2, -1,
2, 3, 0};
double result = 7.0/9;
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
double compare = matOpObj.mean(mat1);
assertTrue(compare == result);
}
public void testMatrix_rowmean() {
double copy_data3x3_1[] = {1, -1, 1,
0, 2, -1,
2, 3, 0};
double result_rowmean[] = {1, 4.0/3, 0};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, copy_data3x3_1);
final PrimitiveMatrix mat1 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray r_rowmean = new PrimitiveDoubleArray(1, 3, result_rowmean);
final PrimitiveMatrix mat2 = new PrimitiveMatrix(r_rowmean);
PrimitiveMatrix matI = matOpObj.rowmean(mat1);
assertTrue(mat2.getData().equalsSemantically(matI.getData()));
}
public void testMatrix_addUnbound() {
double data3x3_1[] = {1, 1, 1, 2, 2, 2, 3, 3, 3,};
double data_unbound_row[] = {1, 1, 1};
double result3x3_1[] = {2, 2, 2, 3, 3, 3, 4, 4, 4};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, data3x3_1);
final PrimitiveMatrix mat3x3 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray unbound_row = new PrimitiveDoubleArray(1, 3, data_unbound_row);
final PrimitiveMatrix mat1x3 = new PrimitiveMatrix(unbound_row);
final UnboundRowMatrix urMat = new UnboundRowMatrix(mat1x3);
final PrimitiveDoubleArray resultData = new PrimitiveDoubleArray(3, 3, result3x3_1);
final PrimitiveMatrix<Double> result3x3 = new PrimitiveMatrix(resultData);
- PrimitiveMatrix resultMat = matOpObj.add(mat1x3, urMat);
+ PrimitiveMatrix resultMat = matOpObj.add(mat3x3, urMat);
assertTrue(resultMat.getData().equalsSemantically(result3x3.getData()));
}
public static Test suite() {
return new TestSuite(MatrixOperationTest.class);
}
}
| true | true | public void testMatrix_addUnbound() {
double data3x3_1[] = {1, 1, 1, 2, 2, 2, 3, 3, 3,};
double data_unbound_row[] = {1, 1, 1};
double result3x3_1[] = {2, 2, 2, 3, 3, 3, 4, 4, 4};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, data3x3_1);
final PrimitiveMatrix mat3x3 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray unbound_row = new PrimitiveDoubleArray(1, 3, data_unbound_row);
final PrimitiveMatrix mat1x3 = new PrimitiveMatrix(unbound_row);
final UnboundRowMatrix urMat = new UnboundRowMatrix(mat1x3);
final PrimitiveDoubleArray resultData = new PrimitiveDoubleArray(3, 3, result3x3_1);
final PrimitiveMatrix<Double> result3x3 = new PrimitiveMatrix(resultData);
PrimitiveMatrix resultMat = matOpObj.add(mat1x3, urMat);
assertTrue(resultMat.getData().equalsSemantically(result3x3.getData()));
}
| public void testMatrix_addUnbound() {
double data3x3_1[] = {1, 1, 1, 2, 2, 2, 3, 3, 3,};
double data_unbound_row[] = {1, 1, 1};
double result3x3_1[] = {2, 2, 2, 3, 3, 3, 4, 4, 4};
final PrimitiveDoubleArray mat3x3_1 = new PrimitiveDoubleArray(3, 3, data3x3_1);
final PrimitiveMatrix mat3x3 = new PrimitiveMatrix(mat3x3_1);
final PrimitiveDoubleArray unbound_row = new PrimitiveDoubleArray(1, 3, data_unbound_row);
final PrimitiveMatrix mat1x3 = new PrimitiveMatrix(unbound_row);
final UnboundRowMatrix urMat = new UnboundRowMatrix(mat1x3);
final PrimitiveDoubleArray resultData = new PrimitiveDoubleArray(3, 3, result3x3_1);
final PrimitiveMatrix<Double> result3x3 = new PrimitiveMatrix(resultData);
PrimitiveMatrix resultMat = matOpObj.add(mat3x3, urMat);
assertTrue(resultMat.getData().equalsSemantically(result3x3.getData()));
}
|
diff --git a/src/uk/ac/aber/dcs/cs221/monstermash/data/Battle.java b/src/uk/ac/aber/dcs/cs221/monstermash/data/Battle.java
index 6131c4b..1e97d27 100644
--- a/src/uk/ac/aber/dcs/cs221/monstermash/data/Battle.java
+++ b/src/uk/ac/aber/dcs/cs221/monstermash/data/Battle.java
@@ -1,111 +1,114 @@
package uk.ac.aber.dcs.cs221.monstermash.data;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import org.json.JSONException;
public class Battle {
private volatile Monster defender = null;
private volatile Monster challenger = null;
private volatile boolean valid = false;
private volatile Monster winner = null;
private volatile List<String> log;
public Battle(Monster defender, Monster challenger) {
this.defender = defender;
this.challenger = challenger;
log = new LinkedList<String>();
if (defender.getHealth() <= 0
|| challenger.getHealth() <= 0) {
return;
}
fight();
valid = true;
}
private void fight() {
class CombatStats {
public int evade,toughness,strength,hitpoints;
public String name;
}
CombatStats[] monsters = new CombatStats[2];
monsters[0] = new CombatStats();
monsters[1] = new CombatStats();
monsters[0].evade = challenger.getEvade();
monsters[0].toughness = challenger.getToughness();
monsters[0].strength = challenger.getStrength();
- monsters[0].hitpoints = challenger.getToughness();
+ monsters[0].hitpoints = monsters[0].toughness>=1? monsters[0].toughness: 1;
monsters[0].name = challenger.getName();
monsters[1].evade = defender.getEvade();
monsters[1].toughness = defender.getToughness();
monsters[1].strength = defender.getStrength();
- monsters[1].hitpoints = defender.getToughness();
+ monsters[1].hitpoints = monsters[1].toughness>=1? monsters[1].toughness: 1;
monsters[1].name = defender.getName();
Random prng = new Random();
boolean challengerWon = false;
while (true) {
// Pick a random attacker.
int attacker = prng.nextBoolean()? 1:0;
int defender = attacker == 1? 0:1;
// The other monster gets a chance to evade.
if (prng.nextInt()%100 < monsters[defender].evade) {
log.add(monsters[attacker].name+" lunged for "+monsters[defender].name+" but missed.");
continue;//The attack misses.
}
// Calculate damage reduction from Toughness.
int resistance = monsters[defender].toughness>99? 99:
monsters[defender].toughness;
resistance = (1-resistance);
- // Calculate random multiplier.
+ // Random multiplier.
double multiplier = Math.abs(prng.nextGaussian() );
+ //Calculate damage
int damage = (int) (monsters[attacker].strength * resistance * multiplier);
+ //Minimum damage is 1.
+ damage = damage>=1? damage: 1;
monsters[defender].hitpoints -= damage;
log.add(monsters[attacker].name+" struck "+monsters[defender].name+" for "+damage+" points of damage!");
//Check to see if the defender was knocked out.
if (monsters[defender].hitpoints < 1) {
log.add(monsters[defender].name+" was killed!");
// Set boolean indicating winner.
if (defender != 0) {
challengerWon = true;
}
break;//End the fight.
}
//Continue until one of the two monsters is killed.
}
//Reap the killed monster.
if (challengerWon) {
this.defender.reap();
this.challenger.checkForInjury(prng);
this.challenger.getOwner().deductCash(-this.defender.worth() );
} else {
this.challenger.reap();
this.defender.checkForInjury(prng);
this.defender.getOwner().deductCash(-this.challenger.worth() );
}
}
public boolean isValid() {
return this.valid;
}
public Monster getWinner() {
return this.winner;
}
public synchronized String[] getLog() {
return log.toArray(new String[1]);
}
}
| false | true | private void fight() {
class CombatStats {
public int evade,toughness,strength,hitpoints;
public String name;
}
CombatStats[] monsters = new CombatStats[2];
monsters[0] = new CombatStats();
monsters[1] = new CombatStats();
monsters[0].evade = challenger.getEvade();
monsters[0].toughness = challenger.getToughness();
monsters[0].strength = challenger.getStrength();
monsters[0].hitpoints = challenger.getToughness();
monsters[0].name = challenger.getName();
monsters[1].evade = defender.getEvade();
monsters[1].toughness = defender.getToughness();
monsters[1].strength = defender.getStrength();
monsters[1].hitpoints = defender.getToughness();
monsters[1].name = defender.getName();
Random prng = new Random();
boolean challengerWon = false;
while (true) {
// Pick a random attacker.
int attacker = prng.nextBoolean()? 1:0;
int defender = attacker == 1? 0:1;
// The other monster gets a chance to evade.
if (prng.nextInt()%100 < monsters[defender].evade) {
log.add(monsters[attacker].name+" lunged for "+monsters[defender].name+" but missed.");
continue;//The attack misses.
}
// Calculate damage reduction from Toughness.
int resistance = monsters[defender].toughness>99? 99:
monsters[defender].toughness;
resistance = (1-resistance);
// Calculate random multiplier.
double multiplier = Math.abs(prng.nextGaussian() );
int damage = (int) (monsters[attacker].strength * resistance * multiplier);
monsters[defender].hitpoints -= damage;
log.add(monsters[attacker].name+" struck "+monsters[defender].name+" for "+damage+" points of damage!");
//Check to see if the defender was knocked out.
if (monsters[defender].hitpoints < 1) {
log.add(monsters[defender].name+" was killed!");
// Set boolean indicating winner.
if (defender != 0) {
challengerWon = true;
}
break;//End the fight.
}
//Continue until one of the two monsters is killed.
}
//Reap the killed monster.
if (challengerWon) {
this.defender.reap();
this.challenger.checkForInjury(prng);
this.challenger.getOwner().deductCash(-this.defender.worth() );
} else {
this.challenger.reap();
this.defender.checkForInjury(prng);
this.defender.getOwner().deductCash(-this.challenger.worth() );
}
}
| private void fight() {
class CombatStats {
public int evade,toughness,strength,hitpoints;
public String name;
}
CombatStats[] monsters = new CombatStats[2];
monsters[0] = new CombatStats();
monsters[1] = new CombatStats();
monsters[0].evade = challenger.getEvade();
monsters[0].toughness = challenger.getToughness();
monsters[0].strength = challenger.getStrength();
monsters[0].hitpoints = monsters[0].toughness>=1? monsters[0].toughness: 1;
monsters[0].name = challenger.getName();
monsters[1].evade = defender.getEvade();
monsters[1].toughness = defender.getToughness();
monsters[1].strength = defender.getStrength();
monsters[1].hitpoints = monsters[1].toughness>=1? monsters[1].toughness: 1;
monsters[1].name = defender.getName();
Random prng = new Random();
boolean challengerWon = false;
while (true) {
// Pick a random attacker.
int attacker = prng.nextBoolean()? 1:0;
int defender = attacker == 1? 0:1;
// The other monster gets a chance to evade.
if (prng.nextInt()%100 < monsters[defender].evade) {
log.add(monsters[attacker].name+" lunged for "+monsters[defender].name+" but missed.");
continue;//The attack misses.
}
// Calculate damage reduction from Toughness.
int resistance = monsters[defender].toughness>99? 99:
monsters[defender].toughness;
resistance = (1-resistance);
// Random multiplier.
double multiplier = Math.abs(prng.nextGaussian() );
//Calculate damage
int damage = (int) (monsters[attacker].strength * resistance * multiplier);
//Minimum damage is 1.
damage = damage>=1? damage: 1;
monsters[defender].hitpoints -= damage;
log.add(monsters[attacker].name+" struck "+monsters[defender].name+" for "+damage+" points of damage!");
//Check to see if the defender was knocked out.
if (monsters[defender].hitpoints < 1) {
log.add(monsters[defender].name+" was killed!");
// Set boolean indicating winner.
if (defender != 0) {
challengerWon = true;
}
break;//End the fight.
}
//Continue until one of the two monsters is killed.
}
//Reap the killed monster.
if (challengerWon) {
this.defender.reap();
this.challenger.checkForInjury(prng);
this.challenger.getOwner().deductCash(-this.defender.worth() );
} else {
this.challenger.reap();
this.defender.checkForInjury(prng);
this.defender.getOwner().deductCash(-this.challenger.worth() );
}
}
|
diff --git a/src/test/java/eu/europeana/portal2/web/util/ControllerUtilTest.java b/src/test/java/eu/europeana/portal2/web/util/ControllerUtilTest.java
index 32d5c500..3bbb43d3 100644
--- a/src/test/java/eu/europeana/portal2/web/util/ControllerUtilTest.java
+++ b/src/test/java/eu/europeana/portal2/web/util/ControllerUtilTest.java
@@ -1,16 +1,16 @@
package eu.europeana.portal2.web.util;
import static org.junit.Assert.*;
import org.junit.Test;
public class ControllerUtilTest {
@Test
public void testClearSeeAlso() {
- String test = "Cranach, Lucas (der Ältere) [Herstellung]";
+ String test = "Cranach, Lucas (der Altere) [Herstellung]";
String expected = "Cranach, Lucas";
assertEquals(expected, ControllerUtil.clearSeeAlso(test));
}
}
| true | true | public void testClearSeeAlso() {
String test = "Cranach, Lucas (der Ältere) [Herstellung]";
String expected = "Cranach, Lucas";
assertEquals(expected, ControllerUtil.clearSeeAlso(test));
}
| public void testClearSeeAlso() {
String test = "Cranach, Lucas (der Altere) [Herstellung]";
String expected = "Cranach, Lucas";
assertEquals(expected, ControllerUtil.clearSeeAlso(test));
}
|
diff --git a/samigo-audio/src/java/org/sakaiproject/tool/assessment/audio/AudioRecorderParams.java b/samigo-audio/src/java/org/sakaiproject/tool/assessment/audio/AudioRecorderParams.java
index 5563f82a9..75267a894 100755
--- a/samigo-audio/src/java/org/sakaiproject/tool/assessment/audio/AudioRecorderParams.java
+++ b/samigo-audio/src/java/org/sakaiproject/tool/assessment/audio/AudioRecorderParams.java
@@ -1,579 +1,579 @@
/**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/sam/tags/sakai_2-2-002/audio/src/java/org/sakaiproject/tool/assessment/audio/AudioRecorderParams.java $
* $Id: AudioRecorderParams.java 9270 2006-05-10 21:38:40Z [email protected] $
***********************************************************************************
*
* Copyright (c) 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.sakaiproject.tool.assessment.audio;
import java.io.Serializable;
import java.applet.Applet;
/**
*
* <p> By default, we turn more things on than we would from an applet
we support runnning as an application, too
</p>
* <p>Description: </p>
* <p>Sakai Project Copyright (c) 2005</p>
* <p> </p>
* @author Ed Smiley <[email protected]>
*
*/
public class AudioRecorderParams implements Serializable
{
private boolean enablePlay = true;
private boolean enableRecord = true;
private boolean enablePause = true;
private boolean enableLoad = false;
private boolean saveAu = true;
private boolean saveWave = true;
private boolean saveAiff = true;
private boolean saveToFile = true;
private boolean saveToUrl = false;
private String fileName = "audio";
private String url = "";
private String compression = "linear";
private int frequency = 8000;
private int bits = 8;
private boolean signed = true;
private boolean bigendian = true;
private boolean stereo = false;
private int maxSeconds = 60;
private int attemptsAllowed = 5;
private String imageUrl="";
// -1 indicate that attemptsRemaining is not set, it should be set when question is loaded the 1st time.
private int attemptsRemaining = -1;
private int currentRecordingLength=0;
/**
* compression algorithms
* btw using "u" for the greek letter "mu"
* perhaps we should be calling this "mu-law" and showing that letter in UI.
*/
public static final String compressionAllowed[] =
{
"ulaw",
"alaw",
"linear",
};
/**
* sampling rates
*/
public static final int frequenciesAllowed[] =
{
8000, 11025, 16000, 22050, 44100,
};
/**
* 8 or 16 bit
*/
public static int bitsAllowed[] =
{
8, 16,
};
/**
* Support runnning as an application. We turn off url and trn off save to
* url. Thsi has to be explicitly turned on.
*
*/
public AudioRecorderParams()
{
// keep all defaults
}
/**
*
* <p>From an applet we set all values that are specified in existing applet
* parameters, the names and properties correspond.
* </p>
* @param applet the applet using these settings
*/
public AudioRecorderParams(Applet applet)
{
// set values from applet parameters
String s = applet.getParameter("enablePlay");
if ("true".equalsIgnoreCase(s))
{
enablePlay = true;
}
else if ("false".equalsIgnoreCase(s))
{
enablePlay = false;
}
s = applet.getParameter("enableRecord");
if ("true".equalsIgnoreCase(s))
{
enableRecord = true;
}
else if ("false".equalsIgnoreCase(s))
{
enableRecord = false;
}
s = applet.getParameter("enablePause");
if ("true".equalsIgnoreCase(s))
{
enablePause = true;
}
else if ("false".equalsIgnoreCase(s))
{
enablePause = false;
}
s = applet.getParameter("enableLoad");
if ("true".equalsIgnoreCase(s))
{
enableLoad = true;
}
else if ("false".equalsIgnoreCase(s))
{
enableLoad = false;
}
s = applet.getParameter("saveAu");
if ("true".equalsIgnoreCase(s))
{
saveAu = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveAu = false;
}
s = applet.getParameter("saveWave");
if ("true".equalsIgnoreCase(s))
{
saveWave = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveWave = false;
}
s = applet.getParameter("saveAiff");
if ("true".equalsIgnoreCase(s))
{
saveAiff = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveAiff = false;
}
s = applet.getParameter("saveToFile");
if ("true".equalsIgnoreCase(s))
{
saveToFile = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveToFile = false;
}
s = applet.getParameter("saveToUrl");
if ("true".equalsIgnoreCase(s))
{
saveToUrl = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveToUrl = false;
}
s = applet.getParameter("fileName");
if (s != null)
{
fileName = s;
}
s = applet.getParameter("url");
if (s != null)
{
url = s;
}
s = applet.getParameter("compression");
if (s != null)
{
for (int i = 0; i < this.compressionAllowed.length; i++)
{
if (compressionAllowed[i].equalsIgnoreCase(s))
{
compression = compressionAllowed[i];
}
}
}
s = applet.getParameter("frequency");
if (s != null)
{
int f = 0;
try
{
f = Integer.parseInt(s);
}
catch (NumberFormatException ex)
{
- // leave
+ System.out.println(ex.getMessage());
}
for (int i = 0; i < this.frequenciesAllowed.length; i++)
{
if (frequenciesAllowed[i] == f)
{
frequency = f;
}
}
}
s = applet.getParameter("bits");
if (s != null)
{
int b = 0;
try
{
b = Integer.parseInt(s);
}
catch (NumberFormatException ex)
{
- // leave
+ System.out.println(ex.getMessage());
}
for (int i = 0; i < this.bitsAllowed.length; i++)
{
if (bitsAllowed[i] == b)
{
bits = b;
}
}
}
s = applet.getParameter("signed");
if ("true".equalsIgnoreCase(s))
{
signed = true;
}
else if ("false".equalsIgnoreCase(s))
{
signed = false;
}
s = applet.getParameter("bigendian");
if ("true".equalsIgnoreCase(s))
{
bigendian = true;
}
else if ("false".equalsIgnoreCase(s))
{
bigendian = false;
}
s = applet.getParameter("stereo");
if ("true".equalsIgnoreCase(s))
{
stereo = true;
}
else if ("false".equalsIgnoreCase(s))
{
stereo = false;
}
s = applet.getParameter("maxSeconds");
if (s != null)
{
try
{
maxSeconds = Integer.parseInt(s);
}
catch (NumberFormatException ex)
{
- // leave
+ System.out.println(ex.getMessage());
}
}
s = applet.getParameter("attemptsAllowed");
if (s != null)
{
try
{
attemptsAllowed = Integer.parseInt(s);
}
catch (NumberFormatException ex1)
{
- // leave
+ System.out.println(ex1.getMessage());
}
}
s = applet.getParameter("attemptsRemaining");
if (s != null)
{
try
{
attemptsRemaining = Integer.parseInt(s);
}
catch (NumberFormatException ex1)
{
- // leave
+ System.out.println(ex1.getMessage());
}
}
s = applet.getParameter("currentRecordingLength");
if (s != null)
{
try
{
currentRecordingLength = Integer.parseInt(s);
}
catch (NumberFormatException ex1)
{
- // leave
+ System.out.println(ex1.getMessage());
}
}
s = applet.getParameter("imageUrl");
if (s != null)
{
imageUrl = s;
}
}
public boolean isBigendian()
{
return bigendian;
}
public int getBits()
{
return bits;
}
public String getCompression()
{
return compression;
}
public boolean isEnableLoad()
{
return enableLoad;
}
public boolean isEnablePause()
{
return enablePause;
}
public boolean isEnablePlay()
{
return enablePlay;
}
public boolean isEnableRecord()
{
return enableRecord;
}
public String getFileName()
{
return fileName;
}
public int getFrequency()
{
return frequency;
}
public int getMaxSeconds()
{
return maxSeconds;
}
public int getCurrentRecordingLength()
{
return currentRecordingLength;
}
public int getAttemptsAllowed()
{
return attemptsAllowed;
}
public int getAttemptsRemaining()
{
return attemptsRemaining;
}
public boolean isSaveAiff()
{
return saveAiff;
}
public boolean isSaveAu()
{
return saveAu;
}
public boolean isSaveToFile()
{
return saveToFile;
}
public boolean isSaveToUrl()
{
return saveToUrl;
}
public boolean isSaveWave()
{
return saveWave;
}
public boolean isSigned()
{
return signed;
}
public boolean isStereo()
{
return stereo;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public void setStereo(boolean stereo)
{
this.stereo = stereo;
}
public void setSigned(boolean signed)
{
this.signed = signed;
}
public void setSaveWave(boolean saveWave)
{
this.saveWave = saveWave;
}
public void setSaveToUrl(boolean saveToUrl)
{
this.saveToUrl = saveToUrl;
}
public void setSaveToFile(boolean saveToFile)
{
this.saveToFile = saveToFile;
}
public void setSaveAu(boolean saveAu)
{
this.saveAu = saveAu;
}
public void setSaveAiff(boolean saveAiff)
{
this.saveAiff = saveAiff;
}
public void setAttemptsAllowed(int attemptsAllowed)
{
this.attemptsAllowed = attemptsAllowed;
}
public void setAttemptsRemaining(int attemptsRemaining)
{
this.attemptsRemaining = attemptsRemaining;
}
public void setMaxSeconds(int maxSeconds)
{
this.maxSeconds = maxSeconds;
}
public void setCurrentRecordingLength(int currentRecordingLength)
{
this.currentRecordingLength = currentRecordingLength;
}
public void setFrequency(int frequency)
{
this.frequency = frequency;
}
public void setFileName(String fileName)
{
this.fileName = fileName;
}
public void setEnableRecord(boolean enableRecord)
{
this.enableRecord = enableRecord;
}
public void setEnablePlay(boolean enablePlay)
{
this.enablePlay = enablePlay;
}
public void setEnablePause(boolean enablePause)
{
this.enablePause = enablePause;
}
public void setEnableLoad(boolean enableLoad)
{
this.enableLoad = enableLoad;
}
public void setCompression(String compression)
{
this.compression = compression;
}
public void setBits(int bits)
{
this.bits = bits;
}
public void setBigendian(boolean bigendian)
{
this.bigendian = bigendian;
}
public String getImageUrl()
{
return imageUrl;
}
public void setImageUrl(String imageUrl)
{
this.imageUrl = imageUrl;
}
}
| false | true | public AudioRecorderParams(Applet applet)
{
// set values from applet parameters
String s = applet.getParameter("enablePlay");
if ("true".equalsIgnoreCase(s))
{
enablePlay = true;
}
else if ("false".equalsIgnoreCase(s))
{
enablePlay = false;
}
s = applet.getParameter("enableRecord");
if ("true".equalsIgnoreCase(s))
{
enableRecord = true;
}
else if ("false".equalsIgnoreCase(s))
{
enableRecord = false;
}
s = applet.getParameter("enablePause");
if ("true".equalsIgnoreCase(s))
{
enablePause = true;
}
else if ("false".equalsIgnoreCase(s))
{
enablePause = false;
}
s = applet.getParameter("enableLoad");
if ("true".equalsIgnoreCase(s))
{
enableLoad = true;
}
else if ("false".equalsIgnoreCase(s))
{
enableLoad = false;
}
s = applet.getParameter("saveAu");
if ("true".equalsIgnoreCase(s))
{
saveAu = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveAu = false;
}
s = applet.getParameter("saveWave");
if ("true".equalsIgnoreCase(s))
{
saveWave = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveWave = false;
}
s = applet.getParameter("saveAiff");
if ("true".equalsIgnoreCase(s))
{
saveAiff = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveAiff = false;
}
s = applet.getParameter("saveToFile");
if ("true".equalsIgnoreCase(s))
{
saveToFile = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveToFile = false;
}
s = applet.getParameter("saveToUrl");
if ("true".equalsIgnoreCase(s))
{
saveToUrl = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveToUrl = false;
}
s = applet.getParameter("fileName");
if (s != null)
{
fileName = s;
}
s = applet.getParameter("url");
if (s != null)
{
url = s;
}
s = applet.getParameter("compression");
if (s != null)
{
for (int i = 0; i < this.compressionAllowed.length; i++)
{
if (compressionAllowed[i].equalsIgnoreCase(s))
{
compression = compressionAllowed[i];
}
}
}
s = applet.getParameter("frequency");
if (s != null)
{
int f = 0;
try
{
f = Integer.parseInt(s);
}
catch (NumberFormatException ex)
{
// leave
}
for (int i = 0; i < this.frequenciesAllowed.length; i++)
{
if (frequenciesAllowed[i] == f)
{
frequency = f;
}
}
}
s = applet.getParameter("bits");
if (s != null)
{
int b = 0;
try
{
b = Integer.parseInt(s);
}
catch (NumberFormatException ex)
{
// leave
}
for (int i = 0; i < this.bitsAllowed.length; i++)
{
if (bitsAllowed[i] == b)
{
bits = b;
}
}
}
s = applet.getParameter("signed");
if ("true".equalsIgnoreCase(s))
{
signed = true;
}
else if ("false".equalsIgnoreCase(s))
{
signed = false;
}
s = applet.getParameter("bigendian");
if ("true".equalsIgnoreCase(s))
{
bigendian = true;
}
else if ("false".equalsIgnoreCase(s))
{
bigendian = false;
}
s = applet.getParameter("stereo");
if ("true".equalsIgnoreCase(s))
{
stereo = true;
}
else if ("false".equalsIgnoreCase(s))
{
stereo = false;
}
s = applet.getParameter("maxSeconds");
if (s != null)
{
try
{
maxSeconds = Integer.parseInt(s);
}
catch (NumberFormatException ex)
{
// leave
}
}
s = applet.getParameter("attemptsAllowed");
if (s != null)
{
try
{
attemptsAllowed = Integer.parseInt(s);
}
catch (NumberFormatException ex1)
{
// leave
}
}
s = applet.getParameter("attemptsRemaining");
if (s != null)
{
try
{
attemptsRemaining = Integer.parseInt(s);
}
catch (NumberFormatException ex1)
{
// leave
}
}
s = applet.getParameter("currentRecordingLength");
if (s != null)
{
try
{
currentRecordingLength = Integer.parseInt(s);
}
catch (NumberFormatException ex1)
{
// leave
}
}
s = applet.getParameter("imageUrl");
if (s != null)
{
imageUrl = s;
}
}
| public AudioRecorderParams(Applet applet)
{
// set values from applet parameters
String s = applet.getParameter("enablePlay");
if ("true".equalsIgnoreCase(s))
{
enablePlay = true;
}
else if ("false".equalsIgnoreCase(s))
{
enablePlay = false;
}
s = applet.getParameter("enableRecord");
if ("true".equalsIgnoreCase(s))
{
enableRecord = true;
}
else if ("false".equalsIgnoreCase(s))
{
enableRecord = false;
}
s = applet.getParameter("enablePause");
if ("true".equalsIgnoreCase(s))
{
enablePause = true;
}
else if ("false".equalsIgnoreCase(s))
{
enablePause = false;
}
s = applet.getParameter("enableLoad");
if ("true".equalsIgnoreCase(s))
{
enableLoad = true;
}
else if ("false".equalsIgnoreCase(s))
{
enableLoad = false;
}
s = applet.getParameter("saveAu");
if ("true".equalsIgnoreCase(s))
{
saveAu = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveAu = false;
}
s = applet.getParameter("saveWave");
if ("true".equalsIgnoreCase(s))
{
saveWave = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveWave = false;
}
s = applet.getParameter("saveAiff");
if ("true".equalsIgnoreCase(s))
{
saveAiff = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveAiff = false;
}
s = applet.getParameter("saveToFile");
if ("true".equalsIgnoreCase(s))
{
saveToFile = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveToFile = false;
}
s = applet.getParameter("saveToUrl");
if ("true".equalsIgnoreCase(s))
{
saveToUrl = true;
}
else if ("false".equalsIgnoreCase(s))
{
saveToUrl = false;
}
s = applet.getParameter("fileName");
if (s != null)
{
fileName = s;
}
s = applet.getParameter("url");
if (s != null)
{
url = s;
}
s = applet.getParameter("compression");
if (s != null)
{
for (int i = 0; i < this.compressionAllowed.length; i++)
{
if (compressionAllowed[i].equalsIgnoreCase(s))
{
compression = compressionAllowed[i];
}
}
}
s = applet.getParameter("frequency");
if (s != null)
{
int f = 0;
try
{
f = Integer.parseInt(s);
}
catch (NumberFormatException ex)
{
System.out.println(ex.getMessage());
}
for (int i = 0; i < this.frequenciesAllowed.length; i++)
{
if (frequenciesAllowed[i] == f)
{
frequency = f;
}
}
}
s = applet.getParameter("bits");
if (s != null)
{
int b = 0;
try
{
b = Integer.parseInt(s);
}
catch (NumberFormatException ex)
{
System.out.println(ex.getMessage());
}
for (int i = 0; i < this.bitsAllowed.length; i++)
{
if (bitsAllowed[i] == b)
{
bits = b;
}
}
}
s = applet.getParameter("signed");
if ("true".equalsIgnoreCase(s))
{
signed = true;
}
else if ("false".equalsIgnoreCase(s))
{
signed = false;
}
s = applet.getParameter("bigendian");
if ("true".equalsIgnoreCase(s))
{
bigendian = true;
}
else if ("false".equalsIgnoreCase(s))
{
bigendian = false;
}
s = applet.getParameter("stereo");
if ("true".equalsIgnoreCase(s))
{
stereo = true;
}
else if ("false".equalsIgnoreCase(s))
{
stereo = false;
}
s = applet.getParameter("maxSeconds");
if (s != null)
{
try
{
maxSeconds = Integer.parseInt(s);
}
catch (NumberFormatException ex)
{
System.out.println(ex.getMessage());
}
}
s = applet.getParameter("attemptsAllowed");
if (s != null)
{
try
{
attemptsAllowed = Integer.parseInt(s);
}
catch (NumberFormatException ex1)
{
System.out.println(ex1.getMessage());
}
}
s = applet.getParameter("attemptsRemaining");
if (s != null)
{
try
{
attemptsRemaining = Integer.parseInt(s);
}
catch (NumberFormatException ex1)
{
System.out.println(ex1.getMessage());
}
}
s = applet.getParameter("currentRecordingLength");
if (s != null)
{
try
{
currentRecordingLength = Integer.parseInt(s);
}
catch (NumberFormatException ex1)
{
System.out.println(ex1.getMessage());
}
}
s = applet.getParameter("imageUrl");
if (s != null)
{
imageUrl = s;
}
}
|
diff --git a/cyklotron-core/src/main/java/net/cyklotron/cms/structure/internal/ProposedDocumentData.java b/cyklotron-core/src/main/java/net/cyklotron/cms/structure/internal/ProposedDocumentData.java
index 99956aa27..a43ac81f6 100644
--- a/cyklotron-core/src/main/java/net/cyklotron/cms/structure/internal/ProposedDocumentData.java
+++ b/cyklotron-core/src/main/java/net/cyklotron/cms/structure/internal/ProposedDocumentData.java
@@ -1,1297 +1,1302 @@
package net.cyklotron.cms.structure.internal;
import static net.cyklotron.cms.documents.DocumentMetadataHelper.cdata;
import static net.cyklotron.cms.documents.DocumentMetadataHelper.doc;
import static net.cyklotron.cms.documents.DocumentMetadataHelper.dom4jToText;
import static net.cyklotron.cms.documents.DocumentMetadataHelper.elm;
import static net.cyklotron.cms.documents.DocumentMetadataHelper.selectFirstText;
import static net.cyklotron.cms.documents.DocumentMetadataHelper.textToDom4j;
import java.awt.image.BufferedImage;
import java.awt.image.ImagingOpException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import org.apache.activemq.util.ByteArrayInputStream;
import org.apache.tika.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.imgscalr.Scalr;
import org.jcontainer.dna.Logger;
import org.objectledge.coral.entity.EntityDoesNotExistException;
import org.objectledge.coral.session.CoralSession;
import org.objectledge.coral.store.Resource;
import org.objectledge.html.HTMLException;
import org.objectledge.html.HTMLService;
import org.objectledge.parameters.Parameters;
import org.objectledge.pipeline.ProcessingException;
import org.objectledge.templating.TemplatingContext;
import org.objectledge.upload.FileUpload;
import org.objectledge.upload.UploadBucket;
import org.objectledge.upload.UploadContainer;
import org.objectledge.upload.UploadLimitExceededException;
import org.objectledge.utils.StringUtils;
import net.cyklotron.cms.CmsNodeResource;
import net.cyklotron.cms.category.CategoryResource;
import net.cyklotron.cms.category.CategoryResourceImpl;
import net.cyklotron.cms.category.CategoryService;
import net.cyklotron.cms.documents.DocumentMetadataHelper;
import net.cyklotron.cms.documents.DocumentNodeResource;
import net.cyklotron.cms.documents.PreferredImageSizes;
import net.cyklotron.cms.files.DirectoryResource;
import net.cyklotron.cms.files.DirectoryResourceImpl;
import net.cyklotron.cms.files.FileResource;
import net.cyklotron.cms.files.FileResourceImpl;
import net.cyklotron.cms.files.FilesService;
import net.cyklotron.cms.related.RelatedService;
import net.cyklotron.cms.structure.NavigationNodeResource;
import net.cyklotron.cms.structure.NavigationNodeResourceImpl;
/**
* Data object used by ProposeDocument view and action.
* <p>
* Feels kind like breaking open door, but I'm not willing to learn formtool just to make one silly
* screen.
* </p>
* <p>
* Not threadsafe, but there should be no need to share this object among thread.
* </p>
*
* @author rafal
*/
public class ProposedDocumentData
{
// component configuration
private boolean calendarTree;
private boolean inheritCategories;
private boolean attachmentsEnabled;
private int attachmentsMaxCount;
private int attachmentsMaxSize;
private String attachmentsAllowedFormats;
private List<String> attachmentFormatList;
private long attachmentDirId;
private boolean attachmentsMultiUpload;
private int attachmentsThumbnailSize;
private String uploadBucketId;
// form data
private String name;
private String title;
private String docAbstract;
private String content;
private String eventPlace;
private String eventStreet;
private String eventPostCode;
private String eventCity;
private String eventProvince;
private String sourceName;
private String sourceUrl;
private String proposerCredentials;
private String proposerEmail;
private String description;
private String editorialNote;
private Date validityStart;
private Date validityEnd;
private Date eventStart;
private Date eventEnd;
private List<OrganizationData> organizations;
private Set<CategoryResource> availableCategories;
private Set<CategoryResource> selectedCategories;
private List<Resource> attachments;
private List<String> attachmentNames;
private List<String> attachmentTypes;
private List<byte[]> attachmentContents;
private List<String> attachmentDescriptions;
private boolean removalRequested;
// validation
private String validationFailure;
private final DateFormat format = DateFormat.getDateTimeInstance();
// origin (node where ProposeDocument screen is embedded)
private NavigationNodeResource origin;
private boolean addDocumentVisualEditor;
private boolean clearOrganizationIfNotMatch;
private String cleanupProfile;
private int imageMaxSize;
private static final String DEFAULT_CLENAUP_PROFILE = "proposeDocument";
protected Logger logger;
public ProposedDocumentData(Parameters configuration, PreferredImageSizes imageSizes,
Logger logger)
{
setConfiguration(configuration, imageSizes);
this.logger = logger;
}
public ProposedDocumentData(Logger logger)
{
this.logger = logger;
// remember to call setConfiguration later
}
public void setConfiguration(Parameters configuration, PreferredImageSizes imageSizes)
{
calendarTree = configuration.getBoolean("calendar_tree", true);
inheritCategories = configuration.getBoolean("inherit_categories", true);
attachmentsEnabled = configuration.getBoolean("attachments_enabled", false);
attachmentsMaxCount = configuration.getInt("attachments_max_count", 0);
attachmentsMaxSize = configuration.getInt("attachments_max_size", 0);
attachmentsAllowedFormats = configuration.get("attachments_allowed_formats",
"jpg gif doc rtf pdf xls");
attachmentFormatList = Arrays.asList(attachmentsAllowedFormats.toLowerCase().split("\\s+"));
attachmentDirId = configuration.getLong("attachments_dir_id", -1L);
attachmentsMultiUpload = configuration.getBoolean("attachments_multi_upload", false);
attachmentsThumbnailSize = configuration.getInt("attachments_thumbnails_size", 64);
addDocumentVisualEditor = configuration.getBoolean("add_document_visual_editor", false);
clearOrganizationIfNotMatch = configuration.getBoolean("clear_org_if_not_match", false);
cleanupProfile = configuration.get("cleanup_profile", DEFAULT_CLENAUP_PROFILE);
imageMaxSize = configuration.getInt("attachemnt_images_max_size", imageSizes.getLarge());
}
public void fromParameters(Parameters parameters, CoralSession coralSession)
throws EntityDoesNotExistException
{
name = stripTags(DocumentMetadataHelper.dec(parameters.get("name", "")));
title = stripTags(DocumentMetadataHelper.dec(parameters.get("title", "")));
docAbstract = stripTags(DocumentMetadataHelper.dec(parameters.get("abstract", "")));
content = parameters.get("content", "");
eventPlace = stripTags(DocumentMetadataHelper.dec(parameters.get("event_place", "")));
eventProvince = stripTags(DocumentMetadataHelper.dec(parameters.get("event_province", "")));
eventPostCode = stripTags(DocumentMetadataHelper.dec(parameters.get("event_postCode", "")));
eventCity = stripTags(DocumentMetadataHelper.dec(parameters.get("event_city", "")));
eventStreet = stripTags(DocumentMetadataHelper.dec(parameters.get("event_street", "")));
organizations = OrganizationData.fromParameters(parameters);
sourceName = stripTags(DocumentMetadataHelper.dec(parameters.get("source_name", "")));
sourceUrl = stripTags(DocumentMetadataHelper.dec(parameters.get("source_url", "")));
proposerCredentials = stripTags(DocumentMetadataHelper.dec(parameters.get("proposer_credentials", "")));
proposerEmail = stripTags(DocumentMetadataHelper.dec(parameters.get("proposer_email", "")));
description = stripTags(DocumentMetadataHelper.dec(parameters.get("description", "")));
editorialNote = stripTags(DocumentMetadataHelper.dec(parameters.get("editorial_note", "")));
validityStart = getDate(parameters, "validity_start");
validityEnd = getDate(parameters, "validity_end");
eventStart = getDate(parameters, "event_start");
eventEnd = getDate(parameters, "event_end");
selectedCategories = new HashSet<CategoryResource>();
for(long categoryId : parameters.getLongs("selected_categories"))
{
if(categoryId != -1)
{
selectedCategories.add(CategoryResourceImpl.getCategoryResource(coralSession,
categoryId));
}
}
availableCategories = new HashSet<CategoryResource>();
for(long categoryId : parameters.getLongs("available_categories"))
{
availableCategories.add(CategoryResourceImpl.getCategoryResource(coralSession,
categoryId));
}
if(attachmentsEnabled)
{
attachmentDescriptions = new ArrayList<String>(attachmentsMaxCount);
for(int i = 1; i <= attachmentsMaxCount; i++)
{
attachmentDescriptions.add(stripTags(DocumentMetadataHelper.dec(parameters.get("attachment_description_"
+ i, ""))));
}
attachments = new ArrayList<Resource>(attachmentsMaxCount);
for(int i = 1; i <= attachmentsMaxCount; i++)
{
long fileId = parameters.getLong("attachment_id_" + i, -1);
if(fileId != -1)
{
attachments.add(FileResourceImpl.getFileResource(coralSession, fileId));
}
}
uploadBucketId = parameters.get("upload_bucket_id", "");
attachmentContents = new ArrayList<>(attachmentsMaxCount);
attachmentTypes = new ArrayList<>(attachmentsMaxCount);
attachmentNames = new ArrayList<>(attachmentsMaxCount);
}
}
/**
* Transfers the data into the templating context.
* <p>
* This is needed to keep the exiting templates working
* </p>
*
* @param templatingContext
*/
public void toTemplatingContext(TemplatingContext templatingContext)
{
templatingContext.put("name", DocumentMetadataHelper.enc(name));
templatingContext.put("title", DocumentMetadataHelper.enc(title));
templatingContext.put("abstract", DocumentMetadataHelper.enc(docAbstract));
templatingContext.put("content", DocumentMetadataHelper.enc(content));
templatingContext.put("event_place", DocumentMetadataHelper.enc(eventPlace));
templatingContext.put("event_province", DocumentMetadataHelper.enc(eventProvince));
templatingContext.put("event_postCode", DocumentMetadataHelper.enc(eventPostCode));
templatingContext.put("event_city", DocumentMetadataHelper.enc(eventCity));
templatingContext.put("event_street", DocumentMetadataHelper.enc(eventStreet));
OrganizationData.toTemplatingContext(organizations, templatingContext);
templatingContext.put("source_name", DocumentMetadataHelper.enc(sourceName));
templatingContext.put("source_url", DocumentMetadataHelper.enc(sourceUrl));
templatingContext.put("proposer_credentials", DocumentMetadataHelper.enc(proposerCredentials));
templatingContext.put("proposer_email", DocumentMetadataHelper.enc(proposerEmail));
templatingContext.put("description", DocumentMetadataHelper.enc(description));
setDate(templatingContext, "validity_start", validityStart);
setDate(templatingContext, "validity_end", validityEnd);
setDate(templatingContext, "event_start", eventStart);
setDate(templatingContext, "event_end", eventEnd);
templatingContext.put("selected_categories", selectedCategories);
if(attachmentsEnabled)
{
templatingContext.put("attachments_enabled", attachmentsEnabled);
templatingContext.put("attachments_max_count", attachmentsMaxCount);
int remaining = attachmentsMaxCount - attachments.size();
remaining = remaining >= 0 ? remaining : 0;
templatingContext.put("attachments_remaining_count", remaining);
templatingContext.put("attachments_max_size", attachmentsMaxSize);
templatingContext.put("attachments_allowed_formats", attachmentsAllowedFormats);
templatingContext.put("attachments_multi_upload", attachmentsMultiUpload);
templatingContext.put("attachments_thumbnails_size", attachmentsThumbnailSize);
templatingContext.put("current_attachments", attachments);
// fill up with empty strings to make template logic more simple
while(attachmentDescriptions.size() < attachmentsMaxCount)
{
attachmentDescriptions.add("");
}
templatingContext.put("attachment_descriptions", DocumentMetadataHelper.enc(attachmentDescriptions));
templatingContext.put("upload_bucket_id", uploadBucketId);
}
templatingContext.put("editorial_note", DocumentMetadataHelper.enc(editorialNote));
templatingContext.put("add_document_visual_editor", addDocumentVisualEditor);
templatingContext.put("clear_org_if_not_match", clearOrganizationIfNotMatch);
}
public void fromNode(DocumentNodeResource node, CategoryService categoryService,
RelatedService relatedService, CoralSession coralSession)
{
// calendarTree
// inheritCategories
name = stripTags(node.getName());
title = stripTags(node.getTitle());
docAbstract = stripTags(node.getAbstract());
content = node.getContent();
description = stripTags(node.getDescription());
validityStart = node.getValidityStart();
validityEnd = node.getValidityEnd();
eventPlace = stripTags(node.getEventPlace());
eventStart = node.getEventStart();
eventEnd = node.getEventEnd();
try
{
Document metaDom = textToDom4j(node.getMeta());
eventProvince = stripTags(selectFirstText(metaDom, "/meta/event/address/province"));
eventPostCode = stripTags(selectFirstText(metaDom, "/meta/event/address/postcode"));
eventCity = stripTags(selectFirstText(metaDom, "/meta/event/address/city"));
eventStreet = stripTags(selectFirstText(metaDom, "/meta/event/address/street"));
organizations = OrganizationData.fromMeta(metaDom, "/meta/organizations");
sourceName = stripTags(selectFirstText(metaDom, "/meta/sources/source/name"));
sourceUrl = stripTags(selectFirstText(metaDom, "/meta/sources/source/url"));
proposerCredentials = stripTags(selectFirstText(metaDom, "/meta/authors/author/name"));
proposerEmail = stripTags(selectFirstText(metaDom, "/meta/authors/author/e-mail"));
}
catch(HTMLException e)
{
throw new RuntimeException("malformed metadada in resource " + node.getIdString(), e);
}
selectedCategories = new HashSet<CategoryResource>(Arrays.asList(categoryService
.getCategories(coralSession, node, false)));
if(attachmentsEnabled)
{
List<Resource> resources = new ArrayList<Resource>(Arrays.asList(relatedService
.getRelatedTo(coralSession, node, node.getRelatedResourcesSequence(), null)));
attachments = new ArrayList<Resource>(attachmentsMaxCount);
attachmentDescriptions = new ArrayList<String>(attachmentsMaxCount);
if(node.isThumbnailDefined())
{
attachments.add(node.getThumbnail());
attachmentDescriptions.add(stripTags(node.getThumbnail().getDescription()));
}
for(Resource attachment : resources)
{
if(attachment instanceof FileResource)
{
attachments.add(attachment);
attachmentDescriptions.add(stripTags(((CmsNodeResource)attachment)
.getDescription()));
}
}
}
}
public void toNode(DocumentNodeResource node)
{
// set attributes to new node
node.setDescription(description);
if(addDocumentVisualEditor)
{
node.setContent(content);
}
else
{
node.setContent(makePara(stripTags(content)));
}
node.setAbstract(docAbstract);
node.setValidityStart(validityStart);
node.setValidityEnd(validityEnd);
node.setEventStart(eventStart);
node.setEventEnd(eventEnd);
node.setEventPlace(eventPlace);
Document doc = doc(getMetaElm());
node.setMeta(dom4jToText(doc));
node.setOrganizationIds(OrganizationData.getOrganizationIds(organizations));
}
private Element getMetaElm()
{
return elm("meta", elm("authors", elm("author", elm("name", proposerCredentials), elm(
"e-mail", proposerEmail))), elm("sources", elm("source", elm("name", sourceName), elm(
"url", sourceUrl))), elm("editor"), elm("event", elm("address", elm("street",
eventStreet), elm("postcode", eventPostCode), elm("city", eventCity), elm("province",
eventProvince))), OrganizationData.toMeta(organizations));
}
public void fromProposal(DocumentNodeResource node, CoralSession coralSession)
{
try
{
Document proposalDom = textToDom4j(node.getProposedContent());
name = DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/name"));
title = DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/title"));
docAbstract = DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/abstract"));
// DECODE HTML
content = DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/content"));
description = DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/description"));
validityStart = text2date(DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/validity/start")));
validityEnd = text2date(DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/validity/end")));
eventPlace = DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/event/place"));
eventProvince = DocumentMetadataHelper.dec(selectFirstText(proposalDom,
"/document/meta/event/address/province"));
eventPostCode = DocumentMetadataHelper.dec(selectFirstText(proposalDom,
"/document/meta/event/address/postcode"));
eventCity = DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/meta/event/address/city"));
eventStreet = DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/meta/event/address/street"));
eventStart = text2date(DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/event/start")));
eventEnd = text2date(DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/event/end")));
organizations = OrganizationData.fromMeta(proposalDom, "/document/meta/organizations");
sourceName = DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/meta/sources/source/name"));
sourceUrl = DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/meta/sources/source/url"));
proposerCredentials = DocumentMetadataHelper.dec(selectFirstText(proposalDom,
"/document/meta/authors/author/name"));
proposerEmail = DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/meta/authors/author/e-mail"));
selectedCategories = new HashSet<CategoryResource>();
for(Element categoryNode : (List<Element>)proposalDom
.selectNodes("/document/categories/category/ref"))
{
long categoryId = Long.parseLong(categoryNode.getTextTrim());
try
{
selectedCategories.add(CategoryResourceImpl.getCategoryResource(coralSession,
categoryId));
}
catch(EntityDoesNotExistException e)
{
logger.error("Category resource " + categoryId + " assigned to document node #"
+ node.getId() + " error. " + e.getMessage());
}
}
attachments = new ArrayList<Resource>();
attachmentDescriptions = new ArrayList<String>();
for(Element attachmentNode : (List<Element>)proposalDom
.selectNodes("/document/attachments/attachment"))
{
long fileId = Long.parseLong(attachmentNode.elementTextTrim("ref"));
try
{
attachments.add(FileResourceImpl.getFileResource(coralSession, fileId));
attachmentDescriptions.add(DocumentMetadataHelper.dec(attachmentNode.elementText("description")));
}
catch(EntityDoesNotExistException e)
{
logger.error("File resource #" + fileId + " attached to document node #"
+ node.getId() + " error. " + e.getMessage());
}
}
removalRequested = selectFirstText(proposalDom, "/document/request").equals("remove");
long originId = Long.parseLong(selectFirstText(proposalDom, "/document/origin/ref"));
origin = NavigationNodeResourceImpl.getNavigationNodeResource(coralSession, originId);
editorialNote = DocumentMetadataHelper.dec(selectFirstText(proposalDom, "/document/editorial/note"));
}
catch(HTMLException e)
{
throw new RuntimeException("malformed proposed changes descriptor in document #"
+ node.getIdString(), e);
}
catch(EntityDoesNotExistException e)
{
throw new RuntimeException(
"invalid resource id in proposed changes descriptor in document #"
+ node.getIdString(), e);
}
}
public void toProposal(DocumentNodeResource node)
{
Element categoriesElm = elm("categories");
for(CategoryResource category : selectedCategories)
{
categoriesElm.add(elm("category", elm("ref", category.getIdString())));
}
Element attachmentsElm = elm("attachments");
if(attachmentsEnabled)
{
Iterator<Resource> attachmentIterator = attachments.iterator();
Iterator<String> descriptionIterator = attachmentDescriptions.iterator();
while(attachmentIterator.hasNext())
{
attachmentsElm.add(elm("attachment", elm("ref", attachmentIterator.next()
.getIdString()), elm("description", descriptionIterator.next())));
}
}
Document doc = doc(elm(
"document",
elm("request", removalRequested ? "remove" : "update"),
elm("origin", elm("ref", origin.getIdString())),
elm("name", name),
elm("title", title),
elm("abstract", cdata(docAbstract)),
elm("content", cdata(content)),
elm("description", description),
elm("editorial", elm("note", editorialNote)),
elm("validity", elm("start", date2text(validityStart)),
elm("end", date2text(validityEnd))),
elm("event", elm("place", eventPlace), elm("start", date2text(eventStart)),
elm("end", date2text(eventEnd))), getMetaElm(), categoriesElm, attachmentsElm));
node.setProposedContent(dom4jToText(doc));
}
private static Date text2date(String text)
{
if(text.equals("undefined"))
{
return null;
}
else
{
return new Date(Long.parseLong(text));
}
}
private static String date2text(Date date)
{
if(date == null)
{
return "undefined";
}
else
{
return Long.toString(date.getTime());
}
}
// validation
public boolean isValid(HTMLService htmlService)
{
if(name.equals(""))
{
setValidationFailure("navi_name_empty");
return false;
}
if(title.equals(""))
{
setValidationFailure("navi_title_empty");
return false;
}
if(proposerCredentials.equals(""))
{
setValidationFailure("proposer_credentials_empty");
return false;
}
try
{
StringWriter errorWriter = new StringWriter();
Document contentDom = htmlService.textToDom4j(content, errorWriter, cleanupProfile);
if(contentDom == null)
{
setValidationFailure("invalid_html");
return false;
}
else
{
htmlService.collapseSubsequentBreaksInParas(contentDom);
htmlService.trimBreaksFromParas(contentDom);
htmlService.removeEmptyParas(contentDom);
StringWriter contentWriter = new StringWriter();
htmlService.dom4jToText(contentDom, contentWriter, true);
content = contentWriter.toString();
}
}
catch(HTMLException e)
{
setValidationFailure("invalid_html");
return false;
}
return true;
}
public boolean isFileUploadValid(CoralSession coralSession, Parameters parameters,
FileUpload fileUpload, FilesService filesService)
throws ProcessingException
{
boolean valid = true;
if(attachmentsEnabled)
{
// check if attachment_dir_id is configured, points to a directory, and user has write
// rights
try
{
DirectoryResource dir = DirectoryResourceImpl.getDirectoryResource(coralSession,
attachmentDirId);
if(!dir.canAddChild(coralSession, coralSession.getUserSubject()))
{
validationFailure = "attachment_dir_misconfigured";
valid = false;
}
}
catch(Exception e)
{
validationFailure = "attachment_dir_misconfigured";
valid = false;
}
if(valid)
{
if(attachmentsMultiUpload)
{
UploadBucket bucket = fileUpload.getBucket(uploadBucketId);
if(bucket != null)
{
List<UploadContainer> containers = new ArrayList<>(bucket.getContainers());
// sort containers by id
Collections.sort(containers, new Comparator<UploadContainer>()
{
@Override
public int compare(UploadContainer o1, UploadContainer o2)
{
return Integer.parseInt(o1.getName())
- Integer.parseInt(o2.getName());
}
});
Iterator<UploadContainer> contIter = containers.iterator();
int i = attachments.size();
fileCheck: while(contIter.hasNext() && i < attachmentsMaxCount)
{
UploadContainer container = contIter.next();
String description = parameters.get(
"attachment_description_" + container.getName(), "");
attachmentDescriptions.set(i, description);
if(!isAttachmentValid(i, container, filesService))
{
valid = false;
break fileCheck;
}
i++;
}
}
else
{
- validationFailure = "attachement_async_upload_failed";
- valid = false;
- logger.error("missing or invalid bucket id: " + uploadBucketId);
+ int uploadedFilesCount = parameters.getInt("upload_bucket_size", -1);
+ logger.error("missing or invalid bucket id: " + uploadBucketId + " with "
+ + uploadedFilesCount + " uploaded files reported by browser");
+ if(uploadedFilesCount != 0)
+ {
+ validationFailure = "attachement_async_upload_failed";
+ valid = false;
+ }
}
}
else
{
fileCheck: for(int i = attachments.size(); i < attachmentsMaxCount; i++)
{
try
{
UploadContainer uploadedFile = fileUpload.getContainer("attachment_" + (i + 1));
if(uploadedFile != null)
{
if(!isAttachmentValid(i, uploadedFile, filesService))
{
valid = false;
break fileCheck;
}
}
}
catch(UploadLimitExceededException e)
{
validationFailure = "upload_size_exceeded"; // i18n
valid = false;
break fileCheck;
}
}
}
}
}
return valid;
}
private boolean isAttachmentValid(int index, UploadContainer uploadedFile,
FilesService filesService)
{
if(uploadedFile.getSize() > attachmentsMaxSize * 1024)
{
validationFailure = "attachment_size_exceeded";
return false;
}
String fileName = uploadedFile.getFileName();
String fileExt = fileName.substring(fileName.lastIndexOf('.') + 1).trim().toLowerCase();
if(!attachmentFormatList.contains(fileExt))
{
validationFailure = "attachment_type_not_allowed";
return false;
}
try
{
byte[] srcBytes = IOUtils.toByteArray(uploadedFile.getInputStream());
final ByteArrayInputStream is = new ByteArrayInputStream(srcBytes);
String contentType = filesService.detectMimeType(is, uploadedFile.getFileName());
byte[] targetBytes = srcBytes;
if(imageMaxSize != 0 && contentType.startsWith("image/"))
{
is.reset();
BufferedImage srcImage;
try
{
srcImage = ImageIO.read(is);
}
catch(Exception e)
{
throw new IIOException("image reading error", e);
}
BufferedImage targetImage = null;
try
{
if(srcImage.getWidth() > imageMaxSize || srcImage.getHeight() > imageMaxSize)
{
targetImage = Scalr.resize(srcImage, Scalr.Method.AUTOMATIC,
Scalr.Mode.AUTOMATIC, imageMaxSize, imageMaxSize);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(targetImage, "jpeg", baos);
baos.flush();
targetBytes = baos.toByteArray();
contentType = "image/jpeg";
}
}
finally
{
srcImage.flush();
if(targetImage != null)
{
targetImage.flush();
}
}
}
add(attachmentContents, index, targetBytes);
add(attachmentTypes, index, contentType);
add(attachmentNames, index,
ProposedDocumentData.getAttachmentName(uploadedFile.getFileName(), index));
return true;
}
catch(ImagingOpException | IllegalArgumentException e)
{
validationFailure = "image_resize_failed";
}
catch(IIOException e)
{
validationFailure = "image_format_error";
}
catch(IOException e)
{
validationFailure = "attachment_processing_error";
}
return false;
}
public void releaseUploadBucket(FileUpload fileUpload)
{
if(attachmentsMultiUpload && uploadBucketId != null && uploadBucketId.trim().length() > 0)
{
UploadBucket bucket = fileUpload.getBucket(uploadBucketId);
if(bucket != null)
{
fileUpload.releaseBucket(bucket, "after use");
}
}
}
// adds element at the specified position filling unused leading position with nulls if
// necessary
private <T> void add(List<T> list, int i, T item)
{
while(list.size() < i)
{
list.add(null);
}
list.add(i, item);
}
// getters for configuration
public boolean isAttachmentsEnabled()
{
return attachmentsEnabled;
}
public int getAttachmentsMaxCount()
{
return attachmentsMaxCount;
}
// getters
public String getName()
{
return name;
}
public String getTitle()
{
return title;
}
public String getAbstract()
{
return docAbstract;
}
public String getContent()
{
return content;
}
public String getEventPlace()
{
return eventPlace;
}
public String getEventProvince()
{
return eventProvince;
}
public String getEventPostCode()
{
return eventPostCode;
}
public String getEventCity()
{
return eventCity;
}
public String getEventStreet()
{
return eventStreet;
}
public Date getEventStart()
{
return eventStart;
}
public Date getEventEnd()
{
return eventEnd;
}
public Date getValidityStart()
{
return validityStart;
}
public Date getValidityEnd()
{
return validityEnd;
}
public List<OrganizationData> getOrganizations()
{
return organizations;
}
public String getSourceName()
{
return sourceName;
}
public String getSourceUrl()
{
return sourceUrl;
}
public String getProposerCredentials()
{
return proposerCredentials;
}
public String getProposerEmail()
{
return proposerEmail;
}
public String getDescription()
{
return description;
}
public String getEditorialNote()
{
return editorialNote;
}
public boolean isCalendarTree()
{
return calendarTree;
}
public boolean isInheritCategories()
{
return inheritCategories;
}
public Set<CategoryResource> getSelectedCategories()
{
return selectedCategories;
}
public Set<CategoryResource> getAvailableCategories()
{
return availableCategories;
}
// attachments
public DirectoryResource getAttachmenDirectory(CoralSession coralSession)
throws EntityDoesNotExistException
{
return DirectoryResourceImpl.getDirectoryResource(coralSession, attachmentDirId);
}
public String getAttachmentDescription(int index)
{
if(index >= 0 && index < attachmentDescriptions.size())
{
return attachmentDescriptions.get(index);
}
else
{
return "";
}
}
public String getAttachmentDescription(Resource file)
{
return getAttachmentDescription(attachments.indexOf(file));
}
public List<String> getAttachmentDescriptions()
{
return attachmentDescriptions;
}
public byte[] getAttachmentContents(int index)
{
return attachmentContents.get(index);
}
public String getAttachmentType(int index)
{
return attachmentTypes.get(index);
}
public String getAttachmentName(int index)
{
return attachmentNames.get(index);
}
public int getNewAttachmentsCount()
{
return attachmentContents.size();
}
public List<Resource> getCurrentAttachments()
{
return attachments;
}
public void setTitle(String title)
{
this.title = title;
}
public void setDocAbstract(String docAbstract)
{
this.docAbstract = docAbstract;
}
public void setContent(String content)
{
this.content = content;
}
public void setEventPlace(String eventPlace)
{
this.eventPlace = eventPlace;
}
public void setEventProvince(String eventProvince)
{
this.eventProvince = eventProvince;
}
public void setEventPostCode(String eventPostCode)
{
this.eventPostCode = eventPostCode;
}
public void setEventCity(String eventCity)
{
this.eventCity = eventCity;
}
public void setEventStreet(String eventStreet)
{
this.eventStreet = eventStreet;
}
public void setSourceName(String sourceName)
{
this.sourceName = sourceName;
}
public void setSourceUrl(String sourceUrl)
{
this.sourceUrl = sourceUrl;
}
public void setProposerCredentials(String proposerCredentials)
{
this.proposerCredentials = proposerCredentials;
}
public void setProposerEmail(String proposerEmail)
{
this.proposerEmail = proposerEmail;
}
public void setDescription(String description)
{
this.description = description;
}
public void setValidityStart(Date validityStart)
{
this.validityStart = validityStart;
}
public void setValidityEnd(Date validityEnd)
{
this.validityEnd = validityEnd;
}
public void setEventStart(Date eventStart)
{
this.eventStart = eventStart;
}
public void setEventEnd(Date eventEnd)
{
this.eventEnd = eventEnd;
}
public void setOrganizations(List<OrganizationData> organizations)
{
this.organizations = organizations;
}
public void setSelectedCategories(Set<CategoryResource> selectedCategories)
{
this.selectedCategories = selectedCategories;
}
public void setAttachments(List<Resource> attachments)
{
this.attachments = new ArrayList<Resource>(attachmentsMaxCount);
attachmentDescriptions = new ArrayList<String>(attachmentsMaxCount);
for(Resource attachment : attachments)
{
if(attachment instanceof FileResource)
{
this.attachments.add(attachment);
attachmentDescriptions.add(((CmsNodeResource)attachment).getDescription());
}
}
}
public void addAttachment(FileResource file)
{
attachments.add(file);
attachmentDescriptions.add(file.getDescription());
}
public FileResource removeAttachment(long fileId, CoralSession coralSession)
throws EntityDoesNotExistException
{
FileResource file = FileResourceImpl.getFileResource(coralSession, fileId);
int index = attachments.indexOf(file);
attachments.remove(index);
attachmentDescriptions.remove(index);
return file;
}
public boolean isRemovalRequested()
{
return removalRequested;
}
public void setRemovalRequested(boolean removalRequested)
{
this.removalRequested = removalRequested;
}
public NavigationNodeResource getOrigin()
{
return origin;
}
public void setOrigin(NavigationNodeResource origin)
{
this.origin = origin;
}
public void setEditorialNote(String editorialNote)
{
this.editorialNote = editorialNote;
}
// utitily
public void setValidationFailure(String validationFailure)
{
this.validationFailure = validationFailure;
}
public String getValidationFailure()
{
return validationFailure;
}
private Date getDate(Parameters parameters, String key)
{
if(parameters.isDefined(key) && parameters.get(key).trim().length() > 0)
{
return parameters.getDate(key);
}
else
{
return null;
}
}
/**
* Filters document content according to 'proposeDocument' cleanup profile. This method is
* called when creating change proposal from document to avoid showing document author any
* markup they could not edit using the restricted editor.
*
* @param htmlService HTML Service.
*/
public String cleanupContent(String content, HTMLService htmlService)
throws ProcessingException
{
if(content == null || content.trim().length() == 0)
{
return "";
}
try
{
StringWriter errorWriter = new StringWriter();
Document contentDom = htmlService.textToDom4j(content, errorWriter, cleanupProfile);
if(contentDom == null)
{
throw new ProcessingException("HTML processing failure");
}
else
{
StringWriter contentWriter = new StringWriter();
htmlService.dom4jToText(contentDom, contentWriter, true);
return contentWriter.toString();
}
}
catch(HTMLException e)
{
throw new ProcessingException("HTML processing failure", e);
}
}
public void cleanupContent(HTMLService htmlService)
throws ProcessingException
{
content = cleanupContent(content, htmlService);
}
private void setDate(TemplatingContext templatingContext, String key, Date value)
{
if(value != null)
{
templatingContext.put(key, value.getTime());
}
}
private String formatDate(Date date)
{
if(date != null)
{
return format.format(date);
}
else
{
return "Undefined";
}
}
/**
* Strips HTML tags from the input string.
*/
public static String stripTags(String s)
{
return s == null ? s : s.replaceAll("<[^>]*?>", " ");
}
/**
* Converts newline into HTML paragraphs.
*/
public static String makePara(String content)
{
content = content.replaceAll("\r\n", "\n");
content = content.replaceAll("\n+", "</p>\n<p>");
content = "<p>" + content + "</p>";
content = content.replaceAll("<p>\\s*</p>", "");
return content;
}
public static String getAttachmentName(String fileName, int index)
{
StringBuilder buff = new StringBuilder();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
buff.append(df.format(new Date())); // timestamp
buff.append("_"); // separator
buff.append(index); // form field or upload bucket slot index
buff.append("_"); // separator
fileName = StringUtils.iso1toUtf8(fileName);
fileName = StringUtils.unaccentLatinChars(fileName); // unaccent accented latin characters
fileName = fileName.replaceAll("[^A-Za-z0-9-_.]+", "_"); // squash everything except
// alphanumerics and allowed
// punctuation
fileName = fileName.replaceAll("_{2,}", "_"); // contract sequences of multiple _
buff.append(fileName);
return buff.toString();
}
public void logProposal(Logger logger, DocumentNodeResource node)
{
// build proposals log
StringBuilder proposalsDump = new StringBuilder();
proposalsDump.append("----------------------------------\n");
proposalsDump.append("Document id: ").append(node.getIdString()).append("\n");
proposalsDump.append("Document path: ").append(node.getPath()).append("\n");
proposalsDump.append("Created: ").append(node.getCreationTime()).append("\n");
proposalsDump.append("Created by: ").append(node.getCreatedBy().getName()).append("\n");
proposalsDump.append("Document title: ").append(title).append("\n");
proposalsDump.append("Event Place: ").append(eventPlace).append("\n");
proposalsDump.append("Event Province: ").append(eventProvince).append("\n");
proposalsDump.append("Event Post Code: ").append(eventPostCode).append("\n");
proposalsDump.append("Event City: ").append(eventCity).append("\n");
proposalsDump.append("Event Street: ").append(eventStreet).append("\n");
proposalsDump.append("Event start: ").append(formatDate(eventStart)).append("\n");
proposalsDump.append("Event end: ").append(formatDate(eventEnd)).append("\n");
proposalsDump.append("Document validity start: ").append(formatDate(validityStart)).append(
"\n");
proposalsDump.append("Document validity end: ").append(formatDate(validityEnd))
.append("\n");
OrganizationData.dump(organizations, proposalsDump);
proposalsDump.append("Source name: ").append(sourceName).append("\n");
proposalsDump.append("Source URL: ").append(sourceUrl).append("\n");
proposalsDump.append("Proposer credentials: ").append(proposerCredentials).append("\n");
proposalsDump.append("Proposer email: ").append(proposerEmail).append("\n");
proposalsDump.append("Administrative description: ").append(proposerEmail).append("\n");
proposalsDump.append("Content: \n").append(content).append("\n");
logger.debug(proposalsDump.toString());
}
}
| true | true | public boolean isFileUploadValid(CoralSession coralSession, Parameters parameters,
FileUpload fileUpload, FilesService filesService)
throws ProcessingException
{
boolean valid = true;
if(attachmentsEnabled)
{
// check if attachment_dir_id is configured, points to a directory, and user has write
// rights
try
{
DirectoryResource dir = DirectoryResourceImpl.getDirectoryResource(coralSession,
attachmentDirId);
if(!dir.canAddChild(coralSession, coralSession.getUserSubject()))
{
validationFailure = "attachment_dir_misconfigured";
valid = false;
}
}
catch(Exception e)
{
validationFailure = "attachment_dir_misconfigured";
valid = false;
}
if(valid)
{
if(attachmentsMultiUpload)
{
UploadBucket bucket = fileUpload.getBucket(uploadBucketId);
if(bucket != null)
{
List<UploadContainer> containers = new ArrayList<>(bucket.getContainers());
// sort containers by id
Collections.sort(containers, new Comparator<UploadContainer>()
{
@Override
public int compare(UploadContainer o1, UploadContainer o2)
{
return Integer.parseInt(o1.getName())
- Integer.parseInt(o2.getName());
}
});
Iterator<UploadContainer> contIter = containers.iterator();
int i = attachments.size();
fileCheck: while(contIter.hasNext() && i < attachmentsMaxCount)
{
UploadContainer container = contIter.next();
String description = parameters.get(
"attachment_description_" + container.getName(), "");
attachmentDescriptions.set(i, description);
if(!isAttachmentValid(i, container, filesService))
{
valid = false;
break fileCheck;
}
i++;
}
}
else
{
validationFailure = "attachement_async_upload_failed";
valid = false;
logger.error("missing or invalid bucket id: " + uploadBucketId);
}
}
else
{
fileCheck: for(int i = attachments.size(); i < attachmentsMaxCount; i++)
{
try
{
UploadContainer uploadedFile = fileUpload.getContainer("attachment_" + (i + 1));
if(uploadedFile != null)
{
if(!isAttachmentValid(i, uploadedFile, filesService))
{
valid = false;
break fileCheck;
}
}
}
catch(UploadLimitExceededException e)
{
validationFailure = "upload_size_exceeded"; // i18n
valid = false;
break fileCheck;
}
}
}
}
}
return valid;
}
| public boolean isFileUploadValid(CoralSession coralSession, Parameters parameters,
FileUpload fileUpload, FilesService filesService)
throws ProcessingException
{
boolean valid = true;
if(attachmentsEnabled)
{
// check if attachment_dir_id is configured, points to a directory, and user has write
// rights
try
{
DirectoryResource dir = DirectoryResourceImpl.getDirectoryResource(coralSession,
attachmentDirId);
if(!dir.canAddChild(coralSession, coralSession.getUserSubject()))
{
validationFailure = "attachment_dir_misconfigured";
valid = false;
}
}
catch(Exception e)
{
validationFailure = "attachment_dir_misconfigured";
valid = false;
}
if(valid)
{
if(attachmentsMultiUpload)
{
UploadBucket bucket = fileUpload.getBucket(uploadBucketId);
if(bucket != null)
{
List<UploadContainer> containers = new ArrayList<>(bucket.getContainers());
// sort containers by id
Collections.sort(containers, new Comparator<UploadContainer>()
{
@Override
public int compare(UploadContainer o1, UploadContainer o2)
{
return Integer.parseInt(o1.getName())
- Integer.parseInt(o2.getName());
}
});
Iterator<UploadContainer> contIter = containers.iterator();
int i = attachments.size();
fileCheck: while(contIter.hasNext() && i < attachmentsMaxCount)
{
UploadContainer container = contIter.next();
String description = parameters.get(
"attachment_description_" + container.getName(), "");
attachmentDescriptions.set(i, description);
if(!isAttachmentValid(i, container, filesService))
{
valid = false;
break fileCheck;
}
i++;
}
}
else
{
int uploadedFilesCount = parameters.getInt("upload_bucket_size", -1);
logger.error("missing or invalid bucket id: " + uploadBucketId + " with "
+ uploadedFilesCount + " uploaded files reported by browser");
if(uploadedFilesCount != 0)
{
validationFailure = "attachement_async_upload_failed";
valid = false;
}
}
}
else
{
fileCheck: for(int i = attachments.size(); i < attachmentsMaxCount; i++)
{
try
{
UploadContainer uploadedFile = fileUpload.getContainer("attachment_" + (i + 1));
if(uploadedFile != null)
{
if(!isAttachmentValid(i, uploadedFile, filesService))
{
valid = false;
break fileCheck;
}
}
}
catch(UploadLimitExceededException e)
{
validationFailure = "upload_size_exceeded"; // i18n
valid = false;
break fileCheck;
}
}
}
}
}
return valid;
}
|
diff --git a/src/main/java/net/recommenders/evaluation/strategy/StrategyRunner.java b/src/main/java/net/recommenders/evaluation/strategy/StrategyRunner.java
index 57e9ae9..ca76228 100644
--- a/src/main/java/net/recommenders/evaluation/strategy/StrategyRunner.java
+++ b/src/main/java/net/recommenders/evaluation/strategy/StrategyRunner.java
@@ -1,115 +1,115 @@
package net.recommenders.evaluation.strategy;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import net.recommenders.evaluation.core.DataModel;
import net.recommenders.evaluation.parser.SimpleParser;
import net.recommenders.evaluation.strategy.EvaluationStrategy.Pair;
/**
*
* @author Alejandro
*/
public class StrategyRunner {
public static final String TRAINING_FILE = "split.training.file";
public static final String TEST_FILE = "split.test.file";
public static final String INPUT_FILE = "recommendation.file";
public static final String OUTPUT_FORMAT = "output.format";
public static final String OUTPUT_FILE = "output.file.ranking";
public static final String GROUNDTRUTH_FILE = "output.file.groundtruth";
public static final String STRATEGY = "strategy.class";
public static final String RELEVANCE_THRESHOLD = "strategy.relevance.threshold";
public static final String KOREN_N = "strategy.koren.N";
public static final String KOREN_SEED = "strategy.koren.seed";
public static void main(String[] args) throws Exception {
String propertyFile = System.getProperty("propertyFile");
final Properties properties = new Properties();
try {
properties.load(new FileInputStream(propertyFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
run(properties);
}
public static void run(Properties properties) throws IOException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException {
// read splits
System.out.println("Parsing started: training file");
File trainingFile = new File(properties.getProperty(TRAINING_FILE));
DataModel<Long, Long> trainingModel = new SimpleParser().parseData(trainingFile);
System.out.println("Parsing finished: training file");
System.out.println("Parsing started: test file");
File testFile = new File(properties.getProperty(TEST_FILE));
DataModel<Long, Long> testModel = new SimpleParser().parseData(testFile);
System.out.println("Parsing finished: test file");
// read other parameters
File inputFile = new File(properties.getProperty(INPUT_FILE));
File rankingFile = new File(properties.getProperty(OUTPUT_FILE));
File groundtruthFile = new File(properties.getProperty(GROUNDTRUTH_FILE));
EvaluationStrategy.OUTPUT_FORMAT format = properties.getProperty(OUTPUT_FORMAT).equals(EvaluationStrategy.OUTPUT_FORMAT.TRECEVAL.toString()) ? EvaluationStrategy.OUTPUT_FORMAT.TRECEVAL : EvaluationStrategy.OUTPUT_FORMAT.SIMPLE;
Double threshold = Double.parseDouble(properties.getProperty(RELEVANCE_THRESHOLD));
String strategyClassName = properties.getProperty(STRATEGY);
Class<?> strategyClass = Class.forName(strategyClassName);
// get strategy
EvaluationStrategy<Long, Long> strategy = null;
- if (strategyClassName.contains("Movielens")) {
+ if (strategyClassName.contains("Koren")) {
Integer N = Integer.parseInt(properties.getProperty(KOREN_N));
Long seed = Long.parseLong(properties.getProperty(KOREN_SEED));
strategy = new Koren(trainingModel, testModel, N, threshold, seed);
} else {
- strategy = (EvaluationStrategy<Long, Long>) strategyClass.getConstructor(DataModel.class, DataModel.class, double.class).newInstance(trainingFile, testFile, threshold);
+ strategy = (EvaluationStrategy<Long, Long>) strategyClass.getConstructor(DataModel.class, DataModel.class, double.class).newInstance(trainingModel, testModel, threshold);
}
// read recommendations: user \t item \t score
final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations = new HashMap<Long, List<Pair<Long, Double>>>();
BufferedReader in = new BufferedReader(new FileReader(inputFile));
String line = null;
while ((line = in.readLine()) != null) {
String[] toks = line.split("\t");
Long user = Long.parseLong(toks[0]);
Long item = Long.parseLong(toks[1]);
Double score = Double.parseDouble(toks[2]);
List<Pair<Long, Double>> userRec = mapUserRecommendations.get(user);
if (userRec == null) {
userRec = new ArrayList<Pair<Long, Double>>();
mapUserRecommendations.put(user, userRec);
}
userRec.add(new Pair<Long, Double>(item, score));
}
in.close();
// generate output
PrintStream outRanking = new PrintStream(rankingFile);
PrintStream outGroundtruth = new PrintStream(groundtruthFile);
for (Long user : testModel.getUsers()) {
final List<Pair<Long, Double>> allScoredItems = mapUserRecommendations.get(user);
final Set<Long> items = strategy.getCandidateItemsToRank(user);
final List<Pair<Long, Double>> scoredItems = new ArrayList<Pair<Long, Double>>();
for (Pair<Long, Double> scoredItem : allScoredItems) {
if (items.contains(scoredItem.getFirst())) {
scoredItems.add(scoredItem);
}
}
strategy.printRanking(user, scoredItems, outRanking, format);
strategy.printGroundtruth(user, outGroundtruth, format);
}
outRanking.close();
outGroundtruth.close();
}
}
| false | true | public static void run(Properties properties) throws IOException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException {
// read splits
System.out.println("Parsing started: training file");
File trainingFile = new File(properties.getProperty(TRAINING_FILE));
DataModel<Long, Long> trainingModel = new SimpleParser().parseData(trainingFile);
System.out.println("Parsing finished: training file");
System.out.println("Parsing started: test file");
File testFile = new File(properties.getProperty(TEST_FILE));
DataModel<Long, Long> testModel = new SimpleParser().parseData(testFile);
System.out.println("Parsing finished: test file");
// read other parameters
File inputFile = new File(properties.getProperty(INPUT_FILE));
File rankingFile = new File(properties.getProperty(OUTPUT_FILE));
File groundtruthFile = new File(properties.getProperty(GROUNDTRUTH_FILE));
EvaluationStrategy.OUTPUT_FORMAT format = properties.getProperty(OUTPUT_FORMAT).equals(EvaluationStrategy.OUTPUT_FORMAT.TRECEVAL.toString()) ? EvaluationStrategy.OUTPUT_FORMAT.TRECEVAL : EvaluationStrategy.OUTPUT_FORMAT.SIMPLE;
Double threshold = Double.parseDouble(properties.getProperty(RELEVANCE_THRESHOLD));
String strategyClassName = properties.getProperty(STRATEGY);
Class<?> strategyClass = Class.forName(strategyClassName);
// get strategy
EvaluationStrategy<Long, Long> strategy = null;
if (strategyClassName.contains("Movielens")) {
Integer N = Integer.parseInt(properties.getProperty(KOREN_N));
Long seed = Long.parseLong(properties.getProperty(KOREN_SEED));
strategy = new Koren(trainingModel, testModel, N, threshold, seed);
} else {
strategy = (EvaluationStrategy<Long, Long>) strategyClass.getConstructor(DataModel.class, DataModel.class, double.class).newInstance(trainingFile, testFile, threshold);
}
// read recommendations: user \t item \t score
final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations = new HashMap<Long, List<Pair<Long, Double>>>();
BufferedReader in = new BufferedReader(new FileReader(inputFile));
String line = null;
while ((line = in.readLine()) != null) {
String[] toks = line.split("\t");
Long user = Long.parseLong(toks[0]);
Long item = Long.parseLong(toks[1]);
Double score = Double.parseDouble(toks[2]);
List<Pair<Long, Double>> userRec = mapUserRecommendations.get(user);
if (userRec == null) {
userRec = new ArrayList<Pair<Long, Double>>();
mapUserRecommendations.put(user, userRec);
}
userRec.add(new Pair<Long, Double>(item, score));
}
in.close();
// generate output
PrintStream outRanking = new PrintStream(rankingFile);
PrintStream outGroundtruth = new PrintStream(groundtruthFile);
for (Long user : testModel.getUsers()) {
final List<Pair<Long, Double>> allScoredItems = mapUserRecommendations.get(user);
final Set<Long> items = strategy.getCandidateItemsToRank(user);
final List<Pair<Long, Double>> scoredItems = new ArrayList<Pair<Long, Double>>();
for (Pair<Long, Double> scoredItem : allScoredItems) {
if (items.contains(scoredItem.getFirst())) {
scoredItems.add(scoredItem);
}
}
strategy.printRanking(user, scoredItems, outRanking, format);
strategy.printGroundtruth(user, outGroundtruth, format);
}
outRanking.close();
outGroundtruth.close();
}
| public static void run(Properties properties) throws IOException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, NoSuchMethodException, SecurityException {
// read splits
System.out.println("Parsing started: training file");
File trainingFile = new File(properties.getProperty(TRAINING_FILE));
DataModel<Long, Long> trainingModel = new SimpleParser().parseData(trainingFile);
System.out.println("Parsing finished: training file");
System.out.println("Parsing started: test file");
File testFile = new File(properties.getProperty(TEST_FILE));
DataModel<Long, Long> testModel = new SimpleParser().parseData(testFile);
System.out.println("Parsing finished: test file");
// read other parameters
File inputFile = new File(properties.getProperty(INPUT_FILE));
File rankingFile = new File(properties.getProperty(OUTPUT_FILE));
File groundtruthFile = new File(properties.getProperty(GROUNDTRUTH_FILE));
EvaluationStrategy.OUTPUT_FORMAT format = properties.getProperty(OUTPUT_FORMAT).equals(EvaluationStrategy.OUTPUT_FORMAT.TRECEVAL.toString()) ? EvaluationStrategy.OUTPUT_FORMAT.TRECEVAL : EvaluationStrategy.OUTPUT_FORMAT.SIMPLE;
Double threshold = Double.parseDouble(properties.getProperty(RELEVANCE_THRESHOLD));
String strategyClassName = properties.getProperty(STRATEGY);
Class<?> strategyClass = Class.forName(strategyClassName);
// get strategy
EvaluationStrategy<Long, Long> strategy = null;
if (strategyClassName.contains("Koren")) {
Integer N = Integer.parseInt(properties.getProperty(KOREN_N));
Long seed = Long.parseLong(properties.getProperty(KOREN_SEED));
strategy = new Koren(trainingModel, testModel, N, threshold, seed);
} else {
strategy = (EvaluationStrategy<Long, Long>) strategyClass.getConstructor(DataModel.class, DataModel.class, double.class).newInstance(trainingModel, testModel, threshold);
}
// read recommendations: user \t item \t score
final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations = new HashMap<Long, List<Pair<Long, Double>>>();
BufferedReader in = new BufferedReader(new FileReader(inputFile));
String line = null;
while ((line = in.readLine()) != null) {
String[] toks = line.split("\t");
Long user = Long.parseLong(toks[0]);
Long item = Long.parseLong(toks[1]);
Double score = Double.parseDouble(toks[2]);
List<Pair<Long, Double>> userRec = mapUserRecommendations.get(user);
if (userRec == null) {
userRec = new ArrayList<Pair<Long, Double>>();
mapUserRecommendations.put(user, userRec);
}
userRec.add(new Pair<Long, Double>(item, score));
}
in.close();
// generate output
PrintStream outRanking = new PrintStream(rankingFile);
PrintStream outGroundtruth = new PrintStream(groundtruthFile);
for (Long user : testModel.getUsers()) {
final List<Pair<Long, Double>> allScoredItems = mapUserRecommendations.get(user);
final Set<Long> items = strategy.getCandidateItemsToRank(user);
final List<Pair<Long, Double>> scoredItems = new ArrayList<Pair<Long, Double>>();
for (Pair<Long, Double> scoredItem : allScoredItems) {
if (items.contains(scoredItem.getFirst())) {
scoredItems.add(scoredItem);
}
}
strategy.printRanking(user, scoredItems, outRanking, format);
strategy.printGroundtruth(user, outGroundtruth, format);
}
outRanking.close();
outGroundtruth.close();
}
|
diff --git a/src/org/apache/xerces/validators/common/XMLValidator.java b/src/org/apache/xerces/validators/common/XMLValidator.java
index c340d484..15ab5892 100644
--- a/src/org/apache/xerces/validators/common/XMLValidator.java
+++ b/src/org/apache/xerces/validators/common/XMLValidator.java
@@ -1,3531 +1,3536 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999,2000 The Apache Software Foundation. All rights
* reserved.
*
* 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 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 "Xerces" 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 (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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.validators.common;
import org.apache.xerces.framework.XMLAttrList;
import org.apache.xerces.framework.XMLContentSpec;
import org.apache.xerces.framework.XMLDocumentHandler;
import org.apache.xerces.framework.XMLDocumentScanner;
import org.apache.xerces.framework.XMLErrorReporter;
import org.apache.xerces.readers.DefaultEntityHandler;
import org.apache.xerces.readers.XMLEntityHandler;
import org.apache.xerces.utils.ChunkyCharArray;
import org.apache.xerces.utils.Hash2intTable;
import org.apache.xerces.utils.NamespacesScope;
import org.apache.xerces.utils.QName;
import org.apache.xerces.utils.StringPool;
import org.apache.xerces.utils.XMLCharacterProperties;
import org.apache.xerces.utils.XMLMessages;
import org.apache.xerces.utils.ImplementationMessages;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.EntityResolver;
import org.xml.sax.Locator;
import org.xml.sax.helpers.LocatorImpl;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.xerces.validators.dtd.DTDGrammar;
import org.apache.xerces.validators.schema.EquivClassComparator;
import org.apache.xerces.validators.schema.SchemaGrammar;
import org.apache.xerces.validators.schema.SchemaMessageProvider;
import org.apache.xerces.validators.schema.SchemaSymbols;
import org.apache.xerces.validators.schema.TraverseSchema;
import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl;
import org.apache.xerces.validators.datatype.DatatypeValidator;
import org.apache.xerces.validators.datatype.InvalidDatatypeValueException;
import org.apache.xerces.validators.datatype.StateMessageDatatype;
import org.apache.xerces.validators.datatype.IDREFDatatypeValidator;
import org.apache.xerces.validators.datatype.IDDatatypeValidator;
import org.apache.xerces.validators.datatype.ENTITYDatatypeValidator;
/**
* This class is the super all-in-one validator used by the parser.
*
* @version $Id$
*/
public final class XMLValidator
implements DefaultEntityHandler.EventHandler,
XMLEntityHandler.CharDataHandler,
XMLDocumentScanner.EventHandler,
NamespacesScope.NamespacesHandler {
//
// Constants
//
// debugging
private static final boolean PRINT_EXCEPTION_STACK_TRACE = false;
private static final boolean DEBUG_PRINT_ATTRIBUTES = false;
private static final boolean DEBUG_PRINT_CONTENT = false;
private static final boolean DEBUG_SCHEMA_VALIDATION = false;
private static final boolean DEBUG_ELEMENT_CHILDREN = false;
// Chunk size constants
private static final int CHUNK_SHIFT = 8; // 2^8 = 256
private static final int CHUNK_SIZE = (1 << CHUNK_SHIFT);
private static final int CHUNK_MASK = CHUNK_SIZE - 1;
private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k
private Hashtable fIdDefs = null;
private StateMessageDatatype fStoreIDRef = new StateMessageDatatype() {
private Hashtable fIdDefs;
public Object getDatatypeObject(){
return(Object) fIdDefs;
}
public int getDatatypeState(){
return IDREFDatatypeValidator.IDREF_STORE;
}
public void setDatatypeObject( Object data ){
fIdDefs = (Hashtable) data;
}
};
private StateMessageDatatype fResetID = new StateMessageDatatype() {
public Object getDatatypeObject(){
return(Object) null;
}
public int getDatatypeState(){
return IDDatatypeValidator.ID_CLEAR;
}
public void setDatatypeObject( Object data ){
}
};
private StateMessageDatatype fResetIDRef = new StateMessageDatatype() {
public Object getDatatypeObject(){
return(Object) null;
}
public int getDatatypeState(){
return IDREFDatatypeValidator.IDREF_CLEAR;
}
public void setDatatypeObject( Object data ){
}
};
private StateMessageDatatype fValidateIDRef = new StateMessageDatatype() {
public Object getDatatypeObject(){
return(Object) null;
}
public int getDatatypeState(){
return IDREFDatatypeValidator.IDREF_VALIDATE;
}
public void setDatatypeObject( Object data ){
}
};
private StateMessageDatatype fValidateENTITYMsg = new StateMessageDatatype() {
private Object packagedMessage = null;
public Object getDatatypeObject(){
return packagedMessage;
}
public int getDatatypeState(){
return ENTITYDatatypeValidator.ENTITY_INITIALIZE;//No state
}
public void setDatatypeObject( Object data ){
packagedMessage = data;// Set Entity Handler
}
};
/*
private StateMessageDatatype fValidateNOTATIONMsg = new StateMessageDatatype() {
private Object packagedMessage = null;
public Object getDatatypeObject(){
return packagedMessage;
}
public int getDatatypeState(){
return NOTATIONDatatypeValidator.ENTITY_INITIALIZE;//No state
}
public void setDatatypeObject( Object data ){
packagedMessage = data;// Set Entity Handler
}
};
*/
//
// Data
//
// REVISIT: The data should be regrouped and re-organized so that
// it's easier to find a meaningful field.
// debugging
// private static boolean DEBUG = false;
// other
// attribute validators
private AttributeValidator fAttValidatorNOTATION = new AttValidatorNOTATION();
private AttributeValidator fAttValidatorENUMERATION = new AttValidatorENUMERATION();
private AttributeValidator fAttValidatorDATATYPE = null;
// Package access for use by AttributeValidator classes.
StringPool fStringPool = null;
boolean fValidating = false;
boolean fInElementContent = false;
int fStandaloneReader = -1;
// settings
private boolean fValidationEnabled = false;
private boolean fDynamicValidation = false;
private boolean fSchemaValidation = true;
private boolean fValidationEnabledByDynamic = false;
private boolean fDynamicDisabledByValidation = false;
private boolean fWarningOnDuplicateAttDef = false;
private boolean fWarningOnUndeclaredElements = false;
private boolean fLoadDTDGrammar = true;
// declarations
private int fDeclaration[];
private XMLErrorReporter fErrorReporter = null;
private DefaultEntityHandler fEntityHandler = null;
private QName fCurrentElement = new QName();
private ContentLeafNameTypeVector[] fContentLeafStack = new ContentLeafNameTypeVector[8];
private int[] fValidationFlagStack = new int[8];
private int[] fScopeStack = new int[8];
private int[] fGrammarNameSpaceIndexStack = new int[8];
private int[] fElementEntityStack = new int[8];
private int[] fElementIndexStack = new int[8];
private int[] fContentSpecTypeStack = new int[8];
private static final int sizeQNameParts = 8;
private QName[] fElementQNamePartsStack = new QName[sizeQNameParts];
private QName[] fElementChildren = new QName[32];
private int fElementChildrenLength = 0;
private int[] fElementChildrenOffsetStack = new int[32];
private int fElementDepth = -1;
private boolean fNamespacesEnabled = false;
private NamespacesScope fNamespacesScope = null;
private int fNamespacesPrefix = -1;
private QName fRootElement = new QName();
private int fAttrListHandle = -1;
private int fCurrentElementEntity = -1;
private int fCurrentElementIndex = -1;
private int fCurrentContentSpecType = -1;
private boolean fSeenDoctypeDecl = false;
private final int TOP_LEVEL_SCOPE = -1;
private int fCurrentScope = TOP_LEVEL_SCOPE;
private int fCurrentSchemaURI = -1;
private int fEmptyURI = - 1;
private int fXsiPrefix = - 1;
private int fXsiURI = -2;
private int fXsiTypeAttValue = -1;
private DatatypeValidator fXsiTypeValidator = null;
private Grammar fGrammar = null;
private int fGrammarNameSpaceIndex = -1;
private GrammarResolver fGrammarResolver = null;
// state and stuff
private boolean fScanningDTD = false;
private XMLDocumentScanner fDocumentScanner = null;
private boolean fCalledStartDocument = false;
private XMLDocumentHandler fDocumentHandler = null;
private XMLDocumentHandler.DTDHandler fDTDHandler = null;
private boolean fSeenRootElement = false;
private XMLAttrList fAttrList = null;
private int fXMLLang = -1;
private LocatorImpl fAttrNameLocator = null;
private boolean fCheckedForSchema = false;
private boolean fDeclsAreExternal = false;
private StringPool.CharArrayRange fCurrentElementCharArrayRange = null;
private char[] fCharRefData = null;
private boolean fSendCharDataAsCharArray = false;
private boolean fBufferDatatype = false;
private StringBuffer fDatatypeBuffer = new StringBuffer();
private QName fTempQName = new QName();
private XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl();
private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl();
private XMLElementDecl fTempElementDecl = new XMLElementDecl();
private boolean fGrammarIsDTDGrammar = false;
private boolean fGrammarIsSchemaGrammar = false;
private boolean fNeedValidationOff = false;
// symbols
private int fEMPTYSymbol = -1;
private int fANYSymbol = -1;
private int fMIXEDSymbol = -1;
private int fCHILDRENSymbol = -1;
private int fCDATASymbol = -1;
private int fIDSymbol = -1;
private int fIDREFSymbol = -1;
private int fIDREFSSymbol = -1;
private int fENTITYSymbol = -1;
private int fENTITIESSymbol = -1;
private int fNMTOKENSymbol = -1;
private int fNMTOKENSSymbol = -1;
private int fNOTATIONSymbol = -1;
private int fENUMERATIONSymbol = -1;
private int fREQUIREDSymbol = -1;
private int fFIXEDSymbol = -1;
private int fDATATYPESymbol = -1;
private int fEpsilonIndex = -1;
//Datatype Registry
private DatatypeValidatorFactoryImpl fDataTypeReg =
DatatypeValidatorFactoryImpl.getDatatypeRegistry();
private DatatypeValidator fValID = this.fDataTypeReg.getDatatypeValidator("ID" );
private DatatypeValidator fValIDRef = this.fDataTypeReg.getDatatypeValidator("IDREF" );
private DatatypeValidator fValIDRefs = this.fDataTypeReg.getDatatypeValidator("IDREFS" );
private DatatypeValidator fValENTITY = this.fDataTypeReg.getDatatypeValidator("ENTITY" );
private DatatypeValidator fValENTITIES = this.fDataTypeReg.getDatatypeValidator("ENTITIES" );
private DatatypeValidator fValNMTOKEN = this.fDataTypeReg.getDatatypeValidator("NMTOKEN");
private DatatypeValidator fValNMTOKENS = this.fDataTypeReg.getDatatypeValidator("NMTOKENS");
private DatatypeValidator fValNOTATION = this.fDataTypeReg.getDatatypeValidator("NOTATION" );
//
// Constructors
//
/** Constructs an XML validator. */
public XMLValidator(StringPool stringPool,
XMLErrorReporter errorReporter,
DefaultEntityHandler entityHandler,
XMLDocumentScanner documentScanner) {
// keep references
fStringPool = stringPool;
fErrorReporter = errorReporter;
fEntityHandler = entityHandler;
fDocumentScanner = documentScanner;
fEmptyURI = fStringPool.addSymbol("");
fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI);
// initialize
fAttrList = new XMLAttrList(fStringPool);
entityHandler.setEventHandler(this);
entityHandler.setCharDataHandler(this);
fDocumentScanner.setEventHandler(this);
for (int i = 0; i < sizeQNameParts; i++) {
fElementQNamePartsStack[i] = new QName();
}
init();
} // <init>(StringPool,XMLErrorReporter,DefaultEntityHandler,XMLDocumentScanner)
public void setGrammarResolver(GrammarResolver grammarResolver){
fGrammarResolver = grammarResolver;
}
//
// Public methods
//
// initialization
/** Set char data processing preference and handlers. */
public void initHandlers(boolean sendCharDataAsCharArray,
XMLDocumentHandler docHandler,
XMLDocumentHandler.DTDHandler dtdHandler) {
fSendCharDataAsCharArray = sendCharDataAsCharArray;
fEntityHandler.setSendCharDataAsCharArray(fSendCharDataAsCharArray);
fDocumentHandler = docHandler;
fDTDHandler = dtdHandler;
} // initHandlers(boolean,XMLDocumentHandler,XMLDocumentHandler.DTDHandler)
/** Reset or copy. */
public void resetOrCopy(StringPool stringPool) throws Exception {
fAttrList = new XMLAttrList(stringPool);
resetCommon(stringPool);
}
/** Reset. */
public void reset(StringPool stringPool) throws Exception {
fAttrList.reset(stringPool);
resetCommon(stringPool);
}
// settings
/**
* Turning on validation/dynamic turns on validation if it is off, and
* this is remembered. Turning off validation DISABLES validation/dynamic
* if it is on. Turning off validation/dynamic DOES NOT turn off
* validation if it was explicitly turned on, only if it was turned on
* BECAUSE OF the call to turn validation/dynamic on. Turning on
* validation will REENABLE and turn validation/dynamic back on if it
* was disabled by a call that turned off validation while
* validation/dynamic was enabled.
*/
public void setValidationEnabled(boolean flag) throws Exception {
fValidationEnabled = flag;
fValidationEnabledByDynamic = false;
if (fValidationEnabled) {
if (fDynamicDisabledByValidation) {
fDynamicValidation = true;
fDynamicDisabledByValidation = false;
}
} else if (fDynamicValidation) {
fDynamicValidation = false;
fDynamicDisabledByValidation = true;
}
fValidating = fValidationEnabled;
}
/** Returns true if validation is enabled. */
public boolean getValidationEnabled() {
return fValidationEnabled;
}
/** Sets whether Schema support is on/off. */
public void setSchemaValidationEnabled(boolean flag) {
fSchemaValidation = flag;
}
/** Returns true if Schema support is on. */
public boolean getSchemaValidationEnabled() {
return fSchemaValidation;
}
/** Sets whether validation is dynamic. */
public void setDynamicValidationEnabled(boolean flag) throws Exception {
fDynamicValidation = flag;
fDynamicDisabledByValidation = false;
if (!fDynamicValidation) {
if (fValidationEnabledByDynamic) {
fValidationEnabled = false;
fValidationEnabledByDynamic = false;
}
} else if (!fValidationEnabled) {
fValidationEnabled = true;
fValidationEnabledByDynamic = true;
}
fValidating = fValidationEnabled;
}
/** Returns true if validation is dynamic. */
public boolean getDynamicValidationEnabled() {
return fDynamicValidation;
}
/** Sets fLoadDTDGrammar when validation is off **/
public void setLoadDTDGrammar(boolean loadDG){
if (fValidating) {
fLoadDTDGrammar = true;
} else {
fLoadDTDGrammar = loadDG;
}
}
/** Returns fLoadDTDGrammar **/
public boolean getLoadDTDGrammar() {
return fLoadDTDGrammar;
}
/** Sets whether namespaces are enabled. */
public void setNamespacesEnabled(boolean flag) {
fNamespacesEnabled = flag;
}
/** Returns true if namespaces are enabled. */
public boolean getNamespacesEnabled() {
return fNamespacesEnabled;
}
/** Sets whether duplicate attribute definitions signal a warning. */
public void setWarningOnDuplicateAttDef(boolean flag) {
fWarningOnDuplicateAttDef = flag;
}
/** Returns true if duplicate attribute definitions signal a warning. */
public boolean getWarningOnDuplicateAttDef() {
return fWarningOnDuplicateAttDef;
}
/** Sets whether undeclared elements signal a warning. */
public void setWarningOnUndeclaredElements(boolean flag) {
fWarningOnUndeclaredElements = flag;
}
/** Returns true if undeclared elements signal a warning. */
public boolean getWarningOnUndeclaredElements() {
return fWarningOnUndeclaredElements;
}
//
// DefaultEntityHandler.EventHandler methods
//
/** Start entity reference. */
public void startEntityReference(int entityName, int entityType, int entityContext) throws Exception {
fDocumentHandler.startEntityReference(entityName, entityType, entityContext);
}
/** End entity reference. */
public void endEntityReference(int entityName, int entityType, int entityContext) throws Exception {
fDocumentHandler.endEntityReference(entityName, entityType, entityContext);
}
/** Send end of input notification. */
public void sendEndOfInputNotifications(int entityName, boolean moreToFollow) throws Exception {
fDocumentScanner.endOfInput(entityName, moreToFollow);
/***
if (fScanningDTD) {
fDTDImporter.sendEndOfInputNotifications(entityName, moreToFollow);
}
/***/
}
/** Send reader change notifications. */
public void sendReaderChangeNotifications(XMLEntityHandler.EntityReader reader, int readerId) throws Exception {
fDocumentScanner.readerChange(reader, readerId);
/***
if (fScanningDTD) {
fDTDImporter.sendReaderChangeNotifications(reader, readerId);
}
/***/
}
/** External entity standalone check. */
public boolean externalEntityStandaloneCheck() {
return(fStandaloneReader != -1 && fValidating);
}
/** Return true if validating. */
public boolean getValidating() {
return fValidating;
}
//
// XMLEntityHandler.CharDataHandler methods
//
/** Process characters. */
public void processCharacters(char[] chars, int offset, int length) throws Exception {
if (fValidating) {
if (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) {
charDataInContent();
}
if (fBufferDatatype) {
fDatatypeBuffer.append(chars, offset, length);
}
}
fDocumentHandler.characters(chars, offset, length);
}
/** Process characters. */
public void processCharacters(int data) throws Exception {
if (fValidating) {
if (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) {
charDataInContent();
}
if (fBufferDatatype) {
fDatatypeBuffer.append(fStringPool.toString(data));
}
}
fDocumentHandler.characters(data);
}
/** Process whitespace. */
public void processWhitespace(char[] chars, int offset, int length)
throws Exception {
if (fInElementContent) {
if (fStandaloneReader != -1 && fValidating && getElementDeclIsExternal(fCurrentElementIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION);
}
fDocumentHandler.ignorableWhitespace(chars, offset, length);
} else {
if (fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) {
charDataInContent();
}
fDocumentHandler.characters(chars, offset, length);
}
} // processWhitespace(char[],int,int)
/** Process whitespace. */
public void processWhitespace(int data) throws Exception {
if (fInElementContent) {
if (fStandaloneReader != -1 && fValidating && getElementDeclIsExternal(fCurrentElementIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION);
}
fDocumentHandler.ignorableWhitespace(data);
} else {
if (fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) {
charDataInContent();
}
fDocumentHandler.characters(data);
}
} // processWhitespace(int)
//
// XMLDocumentScanner.EventHandler methods
//
/** Scans element type. */
public void scanElementType(XMLEntityHandler.EntityReader entityReader,
char fastchar, QName element) throws Exception {
if (!fNamespacesEnabled) {
element.clear();
element.localpart = entityReader.scanName(fastchar);
element.rawname = element.localpart;
} else {
entityReader.scanQName(fastchar, element);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
}
} // scanElementType(XMLEntityHandler.EntityReader,char,QName)
/** Scans expected element type. */
public boolean scanExpectedElementType(XMLEntityHandler.EntityReader entityReader,
char fastchar, QName element)
throws Exception {
if (fCurrentElementCharArrayRange == null) {
fCurrentElementCharArrayRange = fStringPool.createCharArrayRange();
}
fStringPool.getCharArrayRange(fCurrentElement.rawname, fCurrentElementCharArrayRange);
return entityReader.scanExpectedName(fastchar, fCurrentElementCharArrayRange);
} // scanExpectedElementType(XMLEntityHandler.EntityReader,char,QName)
/** Scans attribute name. */
public void scanAttributeName(XMLEntityHandler.EntityReader entityReader,
QName element, QName attribute)
throws Exception {
if (!fSeenRootElement) {
fSeenRootElement = true;
rootElementSpecified(element);
fStringPool.resetShuffleCount();
}
if (!fNamespacesEnabled) {
attribute.clear();
attribute.localpart = entityReader.scanName('=');
attribute.rawname = attribute.localpart;
} else {
entityReader.scanQName('=', attribute);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
}
} // scanAttributeName(XMLEntityHandler.EntityReader,QName,QName)
/** Call start document. */
public void callStartDocument() throws Exception {
if (!fCalledStartDocument) {
fDocumentHandler.startDocument();
fCalledStartDocument = true;
}
}
/** Call end document. */
public void callEndDocument() throws Exception {
if (fCalledStartDocument) {
fDocumentHandler.endDocument();
}
}
/** Call XML declaration. */
public void callXMLDecl(int version, int encoding, int standalone) throws Exception {
fDocumentHandler.xmlDecl(version, encoding, standalone);
}
public void callStandaloneIsYes() throws Exception {
// standalone = "yes". said XMLDocumentScanner.
fStandaloneReader = fEntityHandler.getReaderId() ;
}
/** Call text declaration. */
public void callTextDecl(int version, int encoding) throws Exception {
fDocumentHandler.textDecl(version, encoding);
}
/**
* Signal the scanning of an element name in a start element tag.
*
* @param element Element name scanned.
*/
public void element(QName element) throws Exception {
fAttrListHandle = -1;
}
/**
* Signal the scanning of an attribute associated to the previous
* start element tag.
*
* @param element Element name scanned.
* @param attrName Attribute name scanned.
* @param attrValue The string pool index of the attribute value.
*/
public boolean attribute(QName element, QName attrName, int attrValue) throws Exception {
if (fAttrListHandle == -1) {
fAttrListHandle = fAttrList.startAttrList();
}
// if fAttrList.addAttr returns -1, indicates duplicate att in start tag of an element.
// specified: true, search : true
return fAttrList.addAttr(attrName, attrValue, fCDATASymbol, true, true) == -1;
}
/** Call start element. */
public void callStartElement(QName element) throws Exception {
if ( DEBUG_SCHEMA_VALIDATION )
System.out.println("\n=======StartElement : " + fStringPool.toString(element.localpart));
//
// Check after all specified attrs are scanned
// (1) report error for REQUIRED attrs that are missing (V_TAGc)
// (2) add default attrs (FIXED and NOT_FIXED)
//
if (!fSeenRootElement) {
fSeenRootElement = true;
rootElementSpecified(element);
fStringPool.resetShuffleCount();
}
if (fGrammar != null && fGrammarIsDTDGrammar) {
fAttrListHandle = addDTDDefaultAttributes(element, fAttrList, fAttrListHandle, fValidating, fStandaloneReader != -1);
}
fCheckedForSchema = true;
if (fNamespacesEnabled) {
bindNamespacesToElementAndAttributes(element, fAttrList);
}
validateElementAndAttributes(element, fAttrList);
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
}
fDocumentHandler.startElement(element, fAttrList, fAttrListHandle);
fAttrListHandle = -1;
//before we increment the element depth, add this element's QName to its enclosing element 's children list
fElementDepth++;
//if (fElementDepth >= 0) {
if (fValidating) {
// push current length onto stack
if (fElementChildrenOffsetStack.length < fElementDepth) {
int newarray[] = new int[fElementChildrenOffsetStack.length * 2];
System.arraycopy(fElementChildrenOffsetStack, 0, newarray, 0, fElementChildrenOffsetStack.length);
fElementChildrenOffsetStack = newarray;
}
fElementChildrenOffsetStack[fElementDepth] = fElementChildrenLength;
// add this element to children
if (fElementChildren.length <= fElementChildrenLength) {
QName[] newarray = new QName[fElementChildrenLength * 2];
System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length);
fElementChildren = newarray;
}
QName qname = fElementChildren[fElementChildrenLength];
if (qname == null) {
for (int i = fElementChildrenLength; i < fElementChildren.length; i++) {
fElementChildren[i] = new QName();
}
qname = fElementChildren[fElementChildrenLength];
}
qname.setValues(element);
fElementChildrenLength++;
if (DEBUG_ELEMENT_CHILDREN) {
printChildren();
printStack();
}
}
// One more level of depth
//fElementDepth++;
ensureStackCapacity(fElementDepth);
fCurrentElement.setValues(element);
fCurrentElementEntity = fEntityHandler.getReaderId();
fElementQNamePartsStack[fElementDepth].setValues(fCurrentElement);
fElementEntityStack[fElementDepth] = fCurrentElementEntity;
fElementIndexStack[fElementDepth] = fCurrentElementIndex;
fContentSpecTypeStack[fElementDepth] = fCurrentContentSpecType;
if (fNeedValidationOff) {
fValidating = false;
fNeedValidationOff = false;
}
if (fValidating && fGrammarIsSchemaGrammar) {
pushContentLeafStack();
}
fValidationFlagStack[fElementDepth] = fValidating ? 0 : -1;
fScopeStack[fElementDepth] = fCurrentScope;
fGrammarNameSpaceIndexStack[fElementDepth] = fGrammarNameSpaceIndex;
} // callStartElement(QName)
private void pushContentLeafStack() throws Exception {
int contentType = getContentSpecType(fCurrentElementIndex);
if ( contentType == XMLElementDecl.TYPE_CHILDREN) {
XMLContentModel cm = getElementContentModel(fCurrentElementIndex);
ContentLeafNameTypeVector cv = cm.getContentLeafNameTypeVector();
if (cm != null) {
fContentLeafStack[fElementDepth] = cv;
}
}
}
private void ensureStackCapacity ( int newElementDepth) {
if (newElementDepth == fElementQNamePartsStack.length ) {
int[] newStack = new int[newElementDepth * 2];
System.arraycopy(fScopeStack, 0, newStack, 0, newElementDepth);
fScopeStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fGrammarNameSpaceIndexStack, 0, newStack, 0, newElementDepth);
fGrammarNameSpaceIndexStack = newStack;
QName[] newStackOfQueue = new QName[newElementDepth * 2];
System.arraycopy(this.fElementQNamePartsStack, 0, newStackOfQueue, 0, newElementDepth );
fElementQNamePartsStack = newStackOfQueue;
QName qname = fElementQNamePartsStack[newElementDepth];
if (qname == null) {
for (int i = newElementDepth; i < fElementQNamePartsStack.length; i++) {
fElementQNamePartsStack[i] = new QName();
}
}
newStack = new int[newElementDepth * 2];
System.arraycopy(fElementEntityStack, 0, newStack, 0, newElementDepth);
fElementEntityStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fElementIndexStack, 0, newStack, 0, newElementDepth);
fElementIndexStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, newElementDepth);
fContentSpecTypeStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fValidationFlagStack, 0, newStack, 0, newElementDepth);
fValidationFlagStack = newStack;
ContentLeafNameTypeVector[] newStackV = new ContentLeafNameTypeVector[newElementDepth * 2];
System.arraycopy(fContentLeafStack, 0, newStackV, 0, newElementDepth);
fContentLeafStack = newStackV;
}
}
/** Call end element. */
public void callEndElement(int readerId) throws Exception {
if ( DEBUG_SCHEMA_VALIDATION )
System.out.println("=======EndElement : " + fStringPool.toString(fCurrentElement.localpart)+"\n");
int prefixIndex = fCurrentElement.prefix;
int elementType = fCurrentElement.rawname;
if (fCurrentElementEntity != readerId) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ELEMENT_ENTITY_MISMATCH,
XMLMessages.P78_NOT_WELLFORMED,
new Object[] { fStringPool.toString(elementType)},
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
fElementDepth--;
if (fValidating) {
int elementIndex = fCurrentElementIndex;
if (elementIndex != -1 && fCurrentContentSpecType != -1) {
QName children[] = fElementChildren;
int childrenOffset = fElementChildrenOffsetStack[fElementDepth + 1] + 1;
int childrenLength = fElementChildrenLength - childrenOffset;
if (DEBUG_ELEMENT_CHILDREN) {
System.out.println("endElement("+fStringPool.toString(fCurrentElement.rawname)+')');
System.out.println("fCurrentContentSpecType : " + fCurrentContentSpecType );
System.out.print("offset: ");
System.out.print(childrenOffset);
System.out.print(", length: ");
System.out.print(childrenLength);
System.out.println();
printChildren();
printStack();
}
int result = checkContent(elementIndex,
children, childrenOffset, childrenLength);
if ( DEBUG_SCHEMA_VALIDATION )
System.out.println("!!!!!!!!In XMLValidator, the return value from checkContent : " + result);
if (result != -1) {
int majorCode = result != childrenLength ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE;
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
if (fTempElementDecl.type == XMLElementDecl.TYPE_EMPTY) {
reportRecoverableXMLError(majorCode,
0,
fStringPool.toString(elementType),
"EMPTY");
} else
reportRecoverableXMLError(majorCode,
0,
fStringPool.toString(elementType),
XMLContentSpec.toString(fGrammar, fStringPool, fTempElementDecl.contentSpecIndex));
}
}
fElementChildrenLength = fElementChildrenOffsetStack[fElementDepth + 1] + 1;
}
fDocumentHandler.endElement(fCurrentElement);
if (fNamespacesEnabled) {
fNamespacesScope.decreaseDepth();
}
// now pop this element off the top of the element stack
//if (fElementDepth-- < 0) {
if (fElementDepth < -1) {
throw new RuntimeException("FWK008 Element stack underflow");
}
if (fElementDepth < 0) {
fCurrentElement.clear();
fCurrentElementEntity = -1;
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
//
// Check after document is fully parsed
// (1) check that there was an element with a matching id for every
// IDREF and IDREFS attr (V_IDREF0)
//
if (fValidating ) {
try {
this.fValIDRef.validate( null, this.fValidateIDRef );
this.fValIDRefs.validate( null, this.fValidateIDRef );
} catch ( InvalidDatatypeValueException ex ) {
reportRecoverableXMLError( ex.getMajorCode(), ex.getMinorCode(),
ex.getMessage() );
}
}
try {//Reset datatypes state
this.fValID.validate( null, this.fResetID );
this.fValIDRef.validate(null, this.fResetIDRef );
this.fValIDRefs.validate(null, this.fResetIDRef );
} catch ( InvalidDatatypeValueException ex ) {
System.err.println("Error re-Initializing: ID,IDRef,IDRefs pools" );
}
return;
}
//restore enclosing element to all the "current" variables
// REVISIT: Validation. This information needs to be stored.
fCurrentElement.prefix = -1;
if (fNamespacesEnabled) { //If Namespace enable then localName != rawName
fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].localpart;
} else {//REVISIT - jeffreyr - This is so we still do old behavior when namespace is off
fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].rawname;
}
fCurrentElement.rawname = fElementQNamePartsStack[fElementDepth].rawname;
fCurrentElement.uri = fElementQNamePartsStack[fElementDepth].uri;
fCurrentElement.prefix = fElementQNamePartsStack[fElementDepth].prefix;
fCurrentElementEntity = fElementEntityStack[fElementDepth];
fCurrentElementIndex = fElementIndexStack[fElementDepth];
fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth];
fValidating = fValidationFlagStack[fElementDepth] == 0 ? true : false;
fCurrentScope = fScopeStack[fElementDepth];
//if ( DEBUG_SCHEMA_VALIDATION ) {
/****
System.out.println("+++++ currentElement : " + fStringPool.toString(elementType)+
"\n fCurrentElementIndex : " + fCurrentElementIndex +
"\n fCurrentScope : " + fCurrentScope +
"\n fCurrentContentSpecType : " + fCurrentContentSpecType +
"\n++++++++++++++++++++++++++++++++++++++++++++++++" );
/****/
//}
// if enclosing element's Schema is different, need to switch "context"
if ( fGrammarNameSpaceIndex != fGrammarNameSpaceIndexStack[fElementDepth] ) {
fGrammarNameSpaceIndex = fGrammarNameSpaceIndexStack[fElementDepth];
if ( fValidating && fGrammarIsSchemaGrammar )
if ( !switchGrammar(fGrammarNameSpaceIndex) ) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 1: " + fStringPool.toString(fGrammarNameSpaceIndex)
+ " , can not found");
}
}
if (fValidating) {
fBufferDatatype = false;
}
fInElementContent = (fCurrentContentSpecType == XMLElementDecl.TYPE_CHILDREN);
} // callEndElement(int)
/** Call start CDATA section. */
public void callStartCDATA() throws Exception {
fDocumentHandler.startCDATA();
}
/** Call end CDATA section. */
public void callEndCDATA() throws Exception {
fDocumentHandler.endCDATA();
}
/** Call characters. */
public void callCharacters(int ch) throws Exception {
if (fCharRefData == null) {
fCharRefData = new char[2];
}
int count = (ch < 0x10000) ? 1 : 2;
if (count == 1) {
fCharRefData[0] = (char)ch;
} else {
fCharRefData[0] = (char)(((ch-0x00010000)>>10)+0xd800);
fCharRefData[1] = (char)(((ch-0x00010000)&0x3ff)+0xdc00);
}
if (fValidating && (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY)) {
charDataInContent();
}
if (fValidating) {
if (fBufferDatatype) {
fDatatypeBuffer.append(fCharRefData,0,1);
}
}
if (fSendCharDataAsCharArray) {
fDocumentHandler.characters(fCharRefData, 0, count);
} else {
int index = fStringPool.addString(new String(fCharRefData, 0, count));
fDocumentHandler.characters(index);
}
} // callCharacters(int)
/** Call processing instruction. */
public void callProcessingInstruction(int target, int data) throws Exception {
fDocumentHandler.processingInstruction(target, data);
}
/** Call comment. */
public void callComment(int comment) throws Exception {
fDocumentHandler.comment(comment);
}
//
// NamespacesScope.NamespacesHandler methods
//
/** Start a new namespace declaration scope. */
public void startNamespaceDeclScope(int prefix, int uri) throws Exception {
fDocumentHandler.startNamespaceDeclScope(prefix, uri);
}
/** End a namespace declaration scope. */
public void endNamespaceDeclScope(int prefix) throws Exception {
fDocumentHandler.endNamespaceDeclScope(prefix);
}
// attributes
// other
/** Sets the root element. */
public void setRootElementType(QName rootElement) {
fRootElement.setValues(rootElement);
}
/**
* Returns true if the element declaration is external.
* <p>
* <strong>Note:</strong> This method is primarilly useful for
* DTDs with internal and external subsets.
*/
private boolean getElementDeclIsExternal(int elementIndex) {
/*if (elementIndex < 0 || elementIndex >= fElementCount) {
return false;
}
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
return (fElementDeclIsExternal[chunk][index] != 0);
*/
if (fGrammarIsDTDGrammar ) {
return((DTDGrammar) fGrammar).getElementDeclIsExternal(elementIndex);
}
return false;
}
/** Returns the content spec type for an element index. */
public int getContentSpecType(int elementIndex) {
int contentSpecType = -1;
if ( elementIndex > -1) {
if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) {
contentSpecType = fTempElementDecl.type;
}
}
return contentSpecType;
}
/** Returns the content spec handle for an element index. */
public int getContentSpecHandle(int elementIndex) {
int contentSpecHandle = -1;
if ( elementIndex > -1) {
if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) {
contentSpecHandle = fTempElementDecl.contentSpecIndex;
}
}
return contentSpecHandle;
}
//
// Protected methods
//
// error reporting
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode)
throws Exception {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
null,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
int stringIndex1)
throws Exception {
Object[] args = { fStringPool.toString(stringIndex1)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,int)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1) throws Exception {
Object[] args = { string1};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
int stringIndex1, int stringIndex2)
throws Exception {
Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,int,int)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1, String string2)
throws Exception {
Object[] args = { string1, string2};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String,String)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1, String string2,
String string3) throws Exception {
Object[] args = { string1, string2, string3};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String,String,String)
// content spec
/**
* Returns information about which elements can be placed at a particular point
* in the passed element's content model.
* <p>
* Note that the incoming content model to test must be valid at least up to
* the insertion point. If not, then -1 will be returned and the info object
* will not have been filled in.
* <p>
* If, on return, the info.isValidEOC flag is set, then the 'insert after'
* elemement is a valid end of content, i.e. nothing needs to be inserted
* after it to make the parent element's content model valid.
*
* @param elementIndex The index within the <code>ElementDeclPool</code> of the
* element which is being querying.
* @param fullyValid Only return elements that can be inserted and still
* maintain the validity of subsequent elements past the
* insertion point (if any). If the insertion point is at
* the end, and this is true, then only elements that can
* be legal final states will be returned.
* @param info An object that contains the required input data for the method,
* and which will contain the output information if successful.
*
* @return The value -1 if fully valid, else the 0 based index of the child
* that first failed before the insertion point. If the value
* returned is equal to the number of children, then the specified
* children are valid but additional content is required to reach a
* valid ending state.
*
* @exception Exception Thrown on error.
*
* @see InsertableElementsInfo
*/
protected int whatCanGoHere(int elementIndex, boolean fullyValid,
InsertableElementsInfo info) throws Exception {
//
// Do some basic sanity checking on the info packet. First, make sure
// that insertAt is not greater than the child count. It can be equal,
// which means to get appendable elements, but not greater. Or, if
// the current children array is null, that's bad too.
//
// Since the current children array must have a blank spot for where
// the insert is going to be, the child count must always be at least
// one.
//
// Make sure that the child count is not larger than the current children
// array. It can be equal, which means get appendable elements, but not
// greater.
//
if (info.insertAt > info.childCount || info.curChildren == null ||
info.childCount < 1 || info.childCount > info.curChildren.length) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
ImplementationMessages.VAL_WCGHI,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
int retVal = 0;
try {
// Get the content model for this element
final XMLContentModel cmElem = getElementContentModel(elementIndex);
// And delegate this call to it
retVal = cmElem.whatCanGoHere(fullyValid, info);
} catch (CMException excToCatch) {
// REVISIT - Translate caught error to the protected error handler interface
int majorCode = excToCatch.getErrorCode();
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
majorCode,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
throw excToCatch;
}
return retVal;
} // whatCanGoHere(int,boolean,InsertableElementsInfo):int
// attribute information
/** Protected for use by AttributeValidator classes. */
protected boolean getAttDefIsExternal(QName element, QName attribute) {
int attDefIndex = getAttDef(element, attribute);
if (fGrammarIsDTDGrammar ) {
return((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attDefIndex);
}
return false;
}
//
// Private methods
//
// other
/** Returns true if using a standalone reader. */
private boolean usingStandaloneReader() {
return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader;
}
/** Returns a locator implementation. */
private LocatorImpl getLocatorImpl(LocatorImpl fillin) {
Locator here = fErrorReporter.getLocator();
if (fillin == null)
return new LocatorImpl(here);
fillin.setPublicId(here.getPublicId());
fillin.setSystemId(here.getSystemId());
fillin.setLineNumber(here.getLineNumber());
fillin.setColumnNumber(here.getColumnNumber());
return fillin;
} // getLocatorImpl(LocatorImpl):LocatorImpl
// initialization
/** Reset pool. */
private void poolReset() {
try {
//System.out.println("We reset" );
this.fValID.validate( null, this.fResetID );
this.fValIDRef.validate(null, this.fResetIDRef );
this.fValIDRefs.validate(null, this.fResetIDRef );
} catch ( InvalidDatatypeValueException ex ) {
System.err.println("Error re-Initializing: ID,IDRef,IDRefs pools" );
}
} // poolReset()
/** Reset common. */
private void resetCommon(StringPool stringPool) throws Exception {
fStringPool = stringPool;
fValidating = fValidationEnabled;
fValidationEnabledByDynamic = false;
fDynamicDisabledByValidation = false;
poolReset();
fCalledStartDocument = false;
fStandaloneReader = -1;
fElementChildrenLength = 0;
fElementDepth = -1;
fSeenRootElement = false;
fSeenDoctypeDecl = false;
fNamespacesScope = null;
fNamespacesPrefix = -1;
fRootElement.clear();
fAttrListHandle = -1;
fCheckedForSchema = false;
fCurrentScope = TOP_LEVEL_SCOPE;
fCurrentSchemaURI = -1;
fEmptyURI = - 1;
fXsiPrefix = - 1;
fXsiTypeValidator = null;
fGrammar = null;
fGrammarNameSpaceIndex = -1;
//fGrammarResolver = null;
if (fGrammarResolver != null) {
fGrammarResolver.clearGrammarResolver();
}
fGrammarIsDTDGrammar = false;
fGrammarIsSchemaGrammar = false;
init();
} // resetCommon(StringPool)
/** Initialize. */
private void init() {
fEmptyURI = fStringPool.addSymbol("");
fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI);
fEMPTYSymbol = fStringPool.addSymbol("EMPTY");
fANYSymbol = fStringPool.addSymbol("ANY");
fMIXEDSymbol = fStringPool.addSymbol("MIXED");
fCHILDRENSymbol = fStringPool.addSymbol("CHILDREN");
fCDATASymbol = fStringPool.addSymbol("CDATA");
fIDSymbol = fStringPool.addSymbol("ID");
fIDREFSymbol = fStringPool.addSymbol("IDREF");
fIDREFSSymbol = fStringPool.addSymbol("IDREFS");
fENTITYSymbol = fStringPool.addSymbol("ENTITY");
fENTITIESSymbol = fStringPool.addSymbol("ENTITIES");
fNMTOKENSymbol = fStringPool.addSymbol("NMTOKEN");
fNMTOKENSSymbol = fStringPool.addSymbol("NMTOKENS");
fNOTATIONSymbol = fStringPool.addSymbol("NOTATION");
fENUMERATIONSymbol = fStringPool.addSymbol("ENUMERATION");
fREQUIREDSymbol = fStringPool.addSymbol("#REQUIRED");
fFIXEDSymbol = fStringPool.addSymbol("#FIXED");
fDATATYPESymbol = fStringPool.addSymbol("<<datatype>>");
fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>");
fXMLLang = fStringPool.addSymbol("xml:lang");
try {//Initialize ENTITIES and ENTITY Validators
Object[] packageArgsEntityVal = { (Object) this.fEntityHandler,
(Object) this.fStringPool};
fValidateENTITYMsg.setDatatypeObject( (Object ) packageArgsEntityVal);
fValENTITIES.validate( null, fValidateENTITYMsg );
fValENTITY.validate( null, fValidateENTITYMsg );
} catch ( InvalidDatatypeValueException ex ) {
System.err.println("Error: " + ex.getLocalizedMessage() );//Should not happen
}
} // init()
// other
// default attribute
/** addDefaultAttributes. */
private int addDefaultAttributes(int elementIndex, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception {
//System.out.println("XMLValidator#addDefaultAttributes");
//System.out.print(" ");
//fGrammar.printAttributes(elementIndex);
//
// Check after all specified attrs are scanned
// (1) report error for REQUIRED attrs that are missing (V_TAGc)
// (2) check that FIXED attrs have matching value (V_TAGd)
// (3) add default attrs (FIXED and NOT_FIXED)
//
fGrammar.getElementDecl(elementIndex,fTempElementDecl);
int elementNameIndex = fTempElementDecl.name.localpart;
int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex);
int firstCheck = attrIndex;
int lastCheck = -1;
while (attlistIndex != -1) {
fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl);
int attPrefix = fTempAttDecl.name.prefix;
int attName = fTempAttDecl.name.localpart;
int attType = attributeTypeName(fTempAttDecl);
int attDefType =fTempAttDecl.defaultType;
int attValue = -1 ;
if (fTempAttDecl.defaultValue != null ) {
attValue = fStringPool.addSymbol(fTempAttDecl.defaultValue);
}
boolean specified = false;
boolean required = attDefType == XMLAttributeDecl.DEFAULT_TYPE_REQUIRED;
if (firstCheck != -1) {
boolean cdata = attType == fCDATASymbol;
if (!cdata || required || attValue != -1) {
int i = attrList.getFirstAttr(firstCheck);
while (i != -1 && (lastCheck == -1 || i <= lastCheck)) {
if ( (fGrammarIsDTDGrammar && (attrList.getAttrName(i) == fTempAttDecl.name.rawname)) ||
( fStringPool.equalNames(attrList.getAttrLocalpart(i), attName)
&& fStringPool.equalNames(attrList.getAttrURI(i), fTempAttDecl.name.uri) ) ) {
if (validationEnabled && attDefType == XMLAttributeDecl.DEFAULT_TYPE_FIXED) {
int alistValue = attrList.getAttValue(i);
if (alistValue != attValue &&
!fStringPool.toString(alistValue).equals(fStringPool.toString(attValue))) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName),
fStringPool.toString(alistValue),
fStringPool.toString(attValue)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_FIXED_ATTVALUE_INVALID,
XMLMessages.VC_FIXED_ATTRIBUTE_DEFAULT,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
specified = true;
break;
}
i = attrList.getNextAttr(i);
}
}
}
if (!specified) {
if (required) {
if (validationEnabled) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_REQUIRED_ATTRIBUTE_NOT_SPECIFIED,
XMLMessages.VC_REQUIRED_ATTRIBUTE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
} else if (attValue != -1) {
if (validationEnabled && standalone )
if ( fGrammarIsDTDGrammar
&& ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attlistIndex) ) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_DEFAULTED_ATTRIBUTE_NOT_SPECIFIED,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
if (attType == fIDREFSymbol) {
this.fValIDRef.validate( fStringPool.toString(attValue), this.fStoreIDRef );
} else if (attType == fIDREFSSymbol) {
this.fValIDRefs.validate( fStringPool.toString(attValue), this.fStoreIDRef );
}
if (attrIndex == -1) {
attrIndex = attrList.startAttrList();
}
// REVISIT: Validation. What should the prefix be?
fTempQName.setValues(attPrefix, attName, attName, fTempAttDecl.name.uri);
int newAttr = attrList.addAttr(fTempQName,
attValue, attType,
false, false);
if (lastCheck == -1) {
lastCheck = newAttr;
}
}
}
attlistIndex = fGrammar.getNextAttributeDeclIndex(attlistIndex);
}
return attrIndex;
} // addDefaultAttributes(int,XMLAttrList,int,boolean,boolean):int
/** addDTDDefaultAttributes. */
private int addDTDDefaultAttributes(QName element, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception {
//
// Check after all specified attrs are scanned
// (1) report error for REQUIRED attrs that are missing (V_TAGc)
// (2) check that FIXED attrs have matching value (V_TAGd)
// (3) add default attrs (FIXED and NOT_FIXED)
//
int elementIndex = fGrammar.getElementDeclIndex(element, -1);
if (elementIndex == -1) {
return attrIndex;
}
fGrammar.getElementDecl(elementIndex,fTempElementDecl);
int elementNameIndex = fTempElementDecl.name.rawname;
int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex);
int firstCheck = attrIndex;
int lastCheck = -1;
while (attlistIndex != -1) {
fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl);
// TO DO: For ericye Debug only
/***
if (fTempAttDecl != null) {
XMLElementDecl element = new XMLElementDecl();
fGrammar.getElementDecl(elementIndex, element);
System.out.println("element: "+fStringPool.toString(element.name.localpart));
System.out.println("attlistIndex " + attlistIndex + "\n"+
"attName : '"+fStringPool.toString(fTempAttDecl.name.localpart) + "'\n"
+ "attType : "+fTempAttDecl.type + "\n"
+ "attDefaultType : "+fTempAttDecl.defaultType + "\n"
+ "attDefaultValue : '"+fTempAttDecl.defaultValue + "'\n"
+ attrList.getLength() +"\n"
);
}
/***/
int attPrefix = fTempAttDecl.name.prefix;
int attName = fTempAttDecl.name.rawname;
int attLocalpart = fTempAttDecl.name.localpart;
int attType = attributeTypeName(fTempAttDecl);
int attDefType =fTempAttDecl.defaultType;
int attValue = -1 ;
if (fTempAttDecl.defaultValue != null ) {
attValue = fStringPool.addSymbol(fTempAttDecl.defaultValue);
}
boolean specified = false;
boolean required = attDefType == XMLAttributeDecl.DEFAULT_TYPE_REQUIRED;
/****
if (fValidating && fGrammar != null && fGrammarIsDTDGrammar && attValue != -1) {
normalizeAttValue(null, fTempAttDecl.name,
attValue,attType,fTempAttDecl.list,
fTempAttDecl.enumeration);
}
/****/
if (firstCheck != -1) {
boolean cdata = attType == fCDATASymbol;
if (!cdata || required || attValue != -1) {
int i = attrList.getFirstAttr(firstCheck);
while (i != -1 && (lastCheck == -1 || i <= lastCheck)) {
if ( attrList.getAttrName(i) == fTempAttDecl.name.rawname ) {
if (validationEnabled && attDefType == XMLAttributeDecl.DEFAULT_TYPE_FIXED) {
int alistValue = attrList.getAttValue(i);
if (alistValue != attValue &&
!fStringPool.toString(alistValue).equals(fStringPool.toString(attValue))) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName),
fStringPool.toString(alistValue),
fStringPool.toString(attValue)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_FIXED_ATTVALUE_INVALID,
XMLMessages.VC_FIXED_ATTRIBUTE_DEFAULT,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
specified = true;
break;
}
i = attrList.getNextAttr(i);
}
}
}
if (!specified) {
if (required) {
if (validationEnabled) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_REQUIRED_ATTRIBUTE_NOT_SPECIFIED,
XMLMessages.VC_REQUIRED_ATTRIBUTE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
} else if (attValue != -1) {
if (validationEnabled && standalone )
if ( fGrammarIsDTDGrammar
&& ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attlistIndex) ) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_DEFAULTED_ATTRIBUTE_NOT_SPECIFIED,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
if (attType == fIDREFSymbol) {
this.fValIDRef.validate( fStringPool.toString(attValue), this.fStoreIDRef );
} else if (attType == fIDREFSSymbol) {
this.fValIDRefs.validate( fStringPool.toString(attValue), this.fStoreIDRef );
}
if (attrIndex == -1) {
attrIndex = attrList.startAttrList();
}
fTempQName.setValues(attPrefix, attLocalpart, attName, fTempAttDecl.name.uri);
int newAttr = attrList.addAttr(fTempQName,
attValue, attType,
false, false);
if (lastCheck == -1) {
lastCheck = newAttr;
}
}
}
attlistIndex = fGrammar.getNextAttributeDeclIndex(attlistIndex);
}
return attrIndex;
} // addDTDDefaultAttributes(int,XMLAttrList,int,boolean,boolean):int
// content models
/** Queries the content model for the specified element index. */
private XMLContentModel getElementContentModel(int elementIndex) throws CMException {
XMLContentModel contentModel = null;
if ( elementIndex > -1) {
if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) {
contentModel = fGrammar.getElementContentModel(elementIndex);
}
}
//return fGrammar.getElementContentModel(elementIndex);
return contentModel;
}
// query attribute information
/** Returns an attribute definition for an element type. */
// this is only used by DTD validation.
private int getAttDef(QName element, QName attribute) {
if (fGrammar != null) {
int scope = fCurrentScope;
if (element.uri > -1) {
scope = TOP_LEVEL_SCOPE;
}
int elementIndex = fGrammar.getElementDeclIndex(element,scope);
if (elementIndex == -1) {
return -1;
}
int attDefIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex);
while (attDefIndex != -1) {
fGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl);
if (fTempAttributeDecl.name.localpart == attribute.localpart &&
fTempAttributeDecl.name.uri == attribute.uri ) {
return attDefIndex;
}
attDefIndex = fGrammar.getNextAttributeDeclIndex(attDefIndex);
}
}
return -1;
} // getAttDef(QName,QName)
/** Returns an attribute definition for an element type. */
private int getAttDefByElementIndex(int elementIndex, QName attribute) {
if (fGrammar != null && elementIndex > -1) {
if (elementIndex == -1) {
return -1;
}
int attDefIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex);
while (attDefIndex != -1) {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
if (fGrammarIsDTDGrammar) {
if (fTempAttDecl.name.rawname == attribute.rawname )
return attDefIndex;
} else
if (fTempAttDecl.name.localpart == attribute.localpart &&
fTempAttDecl.name.uri == attribute.uri ) {
return attDefIndex;
}
if (fGrammarIsSchemaGrammar) {
if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return attDefIndex;
} else if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL) {
if (attribute.uri == -1) {
return attDefIndex;
}
} else if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
if (attribute.uri != fTempAttDecl.name.uri) {
return attDefIndex;
}
} else if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LIST) {
if (fStringPool.stringInList(fTempAttDecl.enumeration, attribute.uri)) {
return attDefIndex;
}
}
}
attDefIndex = fGrammar.getNextAttributeDeclIndex(attDefIndex);
}
}
return -1;
} // getAttDef(QName,QName)
// validation
/** Root element specified. */
private void rootElementSpecified(QName rootElement) throws Exception {
// this is what it used to be
//if (fDynamicValidation && !fSeenDoctypeDecl) {
//fValidating = false;
//}
if ( fLoadDTDGrammar )
// initialize the grammar to be the default one,
// it definitely should be a DTD Grammar at this case;
if (fGrammar == null) {
fGrammar = fGrammarResolver.getGrammar("");
//TO DO, for ericye debug only
if (fGrammar == null && DEBUG_SCHEMA_VALIDATION) {
System.out.println("Oops! no grammar is found for validation");
}
if (fDynamicValidation && fGrammar==null) {
fValidating = false;
}
if (fGrammar != null) {
if (fGrammar instanceof DTDGrammar) {
fGrammarIsDTDGrammar = true;
fGrammarIsSchemaGrammar = false;
} else if ( fGrammar instanceof SchemaGrammar ) {
fGrammarIsSchemaGrammar = true;
fGrammarIsDTDGrammar = false;
}
fGrammarNameSpaceIndex = fEmptyURI;
}
}
if (fValidating) {
if ( fGrammarIsDTDGrammar &&
((DTDGrammar) fGrammar).getRootElementQName(fRootElement) ) {
String root1 = fStringPool.toString(fRootElement.rawname);
String root2 = fStringPool.toString(rootElement.rawname);
if (!root1.equals(root2)) {
reportRecoverableXMLError(XMLMessages.MSG_ROOT_ELEMENT_TYPE,
XMLMessages.VC_ROOT_ELEMENT_TYPE,
fRootElement.rawname,
rootElement.rawname);
}
}
}
if (fNamespacesEnabled) {
if (fNamespacesScope == null) {
fNamespacesScope = new NamespacesScope(this);
fNamespacesPrefix = fStringPool.addSymbol("xmlns");
fNamespacesScope.setNamespaceForPrefix(fNamespacesPrefix, -1);
int xmlSymbol = fStringPool.addSymbol("xml");
int xmlNamespace = fStringPool.addSymbol("http://www.w3.org/XML/1998/namespace");
fNamespacesScope.setNamespaceForPrefix(xmlSymbol, xmlNamespace);
}
}
} // rootElementSpecified(QName)
/** Switchs to correct validating symbol tables when Schema changes.*/
private boolean switchGrammar(int newGrammarNameSpaceIndex) throws Exception {
Grammar tempGrammar = fGrammarResolver.getGrammar(fStringPool.toString(newGrammarNameSpaceIndex));
if (tempGrammar == null) {
// This is a case where namespaces is on with a DTD grammar.
tempGrammar = fGrammarResolver.getGrammar("");
}
if (tempGrammar == null) {
return false;
} else {
fGrammar = tempGrammar;
if (fGrammar instanceof DTDGrammar) {
fGrammarIsDTDGrammar = true;
fGrammarIsSchemaGrammar = false;
} else if ( fGrammar instanceof SchemaGrammar ) {
fGrammarIsSchemaGrammar = true;
fGrammarIsDTDGrammar = false;
}
return true;
}
}
/** Binds namespaces to the element and attributes. */
private void bindNamespacesToElementAndAttributes(QName element,
XMLAttrList attrList)
throws Exception {
fNamespacesScope.increaseDepth();
//Vector schemaCandidateURIs = null;
Hashtable locationUriPairs = null;
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
int attPrefix = attrList.getAttrPrefix(index);
if (fStringPool.equalNames(attName, fXMLLang)) {
/***
// NOTE: This check is done in the validateElementsAndAttributes
// method.
fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index));
/***/
} else if (fStringPool.equalNames(attName, fNamespacesPrefix)) {
int uri = fStringPool.addSymbol(attrList.getAttValue(index));
fNamespacesScope.setNamespaceForPrefix(StringPool.EMPTY_STRING, uri);
} else {
if (attPrefix == fNamespacesPrefix) {
int nsPrefix = attrList.getAttrLocalpart(index);
int uri = fStringPool.addSymbol(attrList.getAttValue(index));
fNamespacesScope.setNamespaceForPrefix(nsPrefix, uri);
if (fValidating && fSchemaValidation) {
boolean seeXsi = false;
String attrValue = fStringPool.toString(attrList.getAttValue(index));
if (attrValue.equals(SchemaSymbols.URI_XSI)) {
fXsiPrefix = nsPrefix;
seeXsi = true;
}
if (!seeXsi) {
/***
if (schemaCandidateURIs == null) {
schemaCandidateURIs = new Vector();
}
schemaCandidateURIs.addElement( fStringPool.toString(uri) );
/***/
}
}
}
}
index = attrList.getNextAttr(index);
}
// if validating, walk through the list again to deal with "xsi:...."
if (fValidating && fSchemaValidation) {
fXsiTypeAttValue = -1;
index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
int attPrefix = attrList.getAttrPrefix(index);
if (fStringPool.equalNames(attName, fNamespacesPrefix)) {
// REVISIT
} else {
if ( DEBUG_SCHEMA_VALIDATION ) {
System.out.println("deal with XSI");
System.out.println("before find XSI: "+fStringPool.toString(attPrefix)
+","+fStringPool.toString(fXsiPrefix) );
}
if ( fXsiPrefix != -1 && attPrefix == fXsiPrefix ) {
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("find XSI: "+fStringPool.toString(attPrefix)
+","+fStringPool.toString(attName) );
}
int localpart = attrList.getAttrLocalpart(index);
if (localpart == fStringPool.addSymbol(SchemaSymbols.XSI_SCHEMALOCACTION)) {
if (locationUriPairs == null) {
locationUriPairs = new Hashtable();
}
parseSchemaLocation(fStringPool.toString(attrList.getAttValue(index)), locationUriPairs);
} else if (localpart == fStringPool.addSymbol(SchemaSymbols.XSI_NONAMESPACESCHEMALOCACTION)) {
if (locationUriPairs == null) {
locationUriPairs = new Hashtable();
}
locationUriPairs.put(fStringPool.toString(attrList.getAttValue(index)), "");
if (fNamespacesScope != null) {
//bind prefix "" to URI "" in this case
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol(""));
}
} else if (localpart == fStringPool.addSymbol(SchemaSymbols.XSI_TYPE)) {
fXsiTypeAttValue = attrList.getAttValue(index);
}
// REVISIT: should we break here?
//break;
}
}
index = attrList.getNextAttr(index);
}
// try to resolve all the grammars here
if (locationUriPairs != null) {
Enumeration locations = locationUriPairs.keys();
while (locations.hasMoreElements()) {
String loc = (String) locations.nextElement();
String uri = (String) locationUriPairs.get(loc);
resolveSchemaGrammar( loc, uri);
//schemaCandidateURIs.removeElement(uri);
}
}
//TO DO: This should be a feature that can be turned on or off
/*****
for (int i=0; i< schemaCandidateURIs.size(); i++) {
String uri = (String) schemaCandidateURIs.elementAt(i);
resolveSchemaGrammar(uri);
}
/*****/
}
}
// bind element to URI
int prefix = element.prefix != -1 ? element.prefix : 0;
int uri = fNamespacesScope.getNamespaceForPrefix(prefix);
if (element.prefix != -1 || uri != -1) {
element.uri = uri;
if (element.uri == -1) {
Object[] args = { fStringPool.toString(element.prefix)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = attrList.getAttrPrefix(index);
if (attPrefix != fNamespacesPrefix) {
if (attPrefix != -1 ) {
int attrUri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (attrUri == -1) {
Object[] args = { fStringPool.toString(attPrefix)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
attrList.setAttrURI(index, attrUri);
}
}
}
index = attrList.getNextAttr(index);
}
}
} // bindNamespacesToElementAndAttributes(QName,XMLAttrList)
void parseSchemaLocation(String schemaLocationStr, Hashtable locationUriPairs){
if (locationUriPairs != null) {
StringTokenizer tokenizer = new StringTokenizer(schemaLocationStr, " \n\t\r", false);
int tokenTotal = tokenizer.countTokens();
if (tokenTotal % 2 != 0 ) {
// TO DO: report warning - malformed schemaLocation string
} else {
while (tokenizer.hasMoreTokens()) {
String uri = tokenizer.nextToken();
String location = tokenizer.nextToken();
locationUriPairs.put(location, uri);
}
}
} else {
// TO DO: should report internal error here
}
}// parseSchemaLocaltion(String, Hashtable)
private void resolveSchemaGrammar( String loc, String uri) throws Exception {
SchemaGrammar grammar = (SchemaGrammar) fGrammarResolver.getGrammar(uri);
if (grammar == null) {
DOMParser parser = new DOMParser();
parser.setEntityResolver( new Resolver(fEntityHandler) );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
} catch ( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
} catch ( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
// expand it before passing it to the parser
InputSource source = null;
EntityResolver currentER = parser.getEntityResolver();
if (currentER != null) {
source = currentER.resolveEntity("", loc);
}
if (source == null) {
loc = fEntityHandler.expandSystemId(loc);
source = new InputSource(loc);
}
try {
parser.parse( source );
} catch ( IOException e ) {
e.printStackTrace();
} catch ( SAXException e ) {
//System.out.println("loc = "+loc);
//e.printStackTrace();
reportRecoverableXMLError( XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR, e.getMessage() );
}
Document document = parser.getDocument(); //Our Grammar
TraverseSchema tst = null;
try {
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("I am geting the Schema Document");
}
Element root = document.getDocumentElement();// This is what we pass to TraverserSchema
if (root == null) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Can't get back Schema document's root element :" + loc);
} else {
if (uri == null || !uri.equals(root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE)) ) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Schema in " + loc + " has a different target namespace " +
"from the one specified in the instance document :" + uri);
}
grammar = new SchemaGrammar();
grammar.setGrammarDocument(document);
tst = new TraverseSchema( root, fStringPool, (SchemaGrammar)grammar, fGrammarResolver, fErrorReporter, source.getSystemId());
fGrammarResolver.putGrammar(document.getDocumentElement().getAttribute("targetNamespace"), grammar);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
private void resolveSchemaGrammar(String uri) throws Exception{
resolveSchemaGrammar(uri, uri);
}
static class Resolver implements EntityResolver {
//
// Constants
//
private static final String SYSTEM[] = {
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/structures.dtd",
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/datatypes.dtd",
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/versionInfo.ent",
};
private static final String PATH[] = {
"structures.dtd",
"datatypes.dtd",
"versionInfo.ent",
};
//
// Data
//
private DefaultEntityHandler fEntityHandler;
//
// Constructors
//
public Resolver(DefaultEntityHandler handler) {
fEntityHandler = handler;
}
//
// EntityResolver methods
//
public InputSource resolveEntity(String publicId, String systemId)
throws IOException, SAXException {
// looking for the schema DTDs?
for (int i = 0; i < SYSTEM.length; i++) {
if (systemId.equals(SYSTEM[i])) {
InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i]));
source.setPublicId(publicId);
source.setSystemId(systemId);
return source;
}
}
// first try to resolve using user's entity resolver
EntityResolver resolver = fEntityHandler.getEntityResolver();
if (resolver != null) {
InputSource source = resolver.resolveEntity(publicId, systemId);
if (source != null) {
return source;
}
}
// use default resolution
return new InputSource(fEntityHandler.expandSystemId(systemId));
} // resolveEntity(String,String):InputSource
} // class Resolver
static class ErrorHandler implements org.xml.sax.ErrorHandler {
/** Warning. */
public void warning(SAXParseException ex) {
System.err.println("[Warning] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Error. */
public void error(SAXParseException ex) {
System.err.println("[Error] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Fatal error. */
public void fatalError(SAXParseException ex) {
System.err.println("[Fatal Error] "+
getLocationString(ex)+": "+
ex.getMessage());
//throw ex;
}
//
// Private methods
//
/** Returns a string of the location. */
private String getLocationString(SAXParseException ex) {
StringBuffer str = new StringBuffer();
String systemId_ = ex.getSystemId();
if (systemId_ != null) {
int index = systemId_.lastIndexOf('/');
if (index != -1)
systemId_ = systemId_.substring(index + 1);
str.append(systemId_);
}
str.append(':');
str.append(ex.getLineNumber());
str.append(':');
str.append(ex.getColumnNumber());
return str.toString();
} // getLocationString(SAXParseException):String
}
private int attributeTypeName(XMLAttributeDecl attrDecl) {
switch (attrDecl.type) {
case XMLAttributeDecl.TYPE_ENTITY: {
return attrDecl.list ? fENTITIESSymbol : fENTITYSymbol;
}
case XMLAttributeDecl.TYPE_ENUMERATION: {
String enumeration = fStringPool.stringListAsString(attrDecl.enumeration);
return fStringPool.addString(enumeration);
}
case XMLAttributeDecl.TYPE_ID: {
return fIDSymbol;
}
case XMLAttributeDecl.TYPE_IDREF: {
return attrDecl.list ? fIDREFSSymbol : fIDREFSymbol;
}
case XMLAttributeDecl.TYPE_NMTOKEN: {
return attrDecl.list ? fNMTOKENSSymbol : fNMTOKENSSymbol;
}
case XMLAttributeDecl.TYPE_NOTATION: {
return fNOTATIONSymbol;
}
}
return fCDATASymbol;
}
/** Validates element and attributes. */
private void validateElementAndAttributes(QName element,
XMLAttrList attrList)
throws Exception {
if ((fElementDepth >= 0 && fValidationFlagStack[fElementDepth] != 0 )||
(fGrammar == null && !fValidating && !fNamespacesEnabled) ) {
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
if (fStringPool.equalNames(fAttrList.getAttrName(index), fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(fAttrList.getAttValue(index));
break;
}
index = fAttrList.getNextAttr(index);
}
}
return;
}
int elementIndex = -1;
int contentSpecType = -1;
boolean skipThisOne = false;
boolean laxThisOne = false;
if ( fGrammarIsSchemaGrammar && fContentLeafStack[fElementDepth] != null ) {
ContentLeafNameTypeVector cv = fContentLeafStack[fElementDepth];
QName[] fElemMap = cv.leafNames;
for (int i=0; i<cv.leafCount; i++) {
int type = cv.leafTypes[i] ;
//System.out.println("******* see a ANY_OTHER_SKIP, "+type+","+element+","+fElemMap[i]+"\n*******");
if (type == XMLContentSpec.CONTENTSPECNODE_LEAF) {
if (fElemMap[i].uri==element.uri
&& fElemMap[i].localpart == element.localpart)
break;
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL) {
if (element.uri == -1) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER) {
if (fElemMap[i].uri != element.uri) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_SKIP) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_SKIP) {
if (element.uri == -1) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP) {
if (fElemMap[i].uri != element.uri) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LAX) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
laxThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_LAX) {
if (element.uri == -1) {
laxThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX) {
if (fElemMap[i].uri != element.uri) {
laxThisOne = true;
break;
}
}
}
}
if (skipThisOne) {
fNeedValidationOff = true;
} else {
//REVISIT: is this the right place to check on if the Schema has changed?
if ( fNamespacesEnabled && fValidating && element.uri != fGrammarNameSpaceIndex && element.uri != -1 ) {
fGrammarNameSpaceIndex = element.uri;
boolean success = switchGrammar(fGrammarNameSpaceIndex);
if (!success && !laxThisOne) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 2: " + fStringPool.toString(fGrammarNameSpaceIndex)
+ " , can not found");
}
}
if ( fGrammar != null ) {
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("*******Lookup element: uri: " + fStringPool.toString(element.uri)+
"localpart: '" + fStringPool.toString(element.localpart)
+"' and scope : " + fCurrentScope+"\n");
}
elementIndex = fGrammar.getElementDeclIndex(element,fCurrentScope);
if (elementIndex == -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element, TOP_LEVEL_SCOPE);
}
if (elementIndex == -1) {
// if validating based on a Schema, try to resolve the element again by searching in its type's ancestor types
if (fGrammarIsSchemaGrammar && fCurrentElementIndex != -1) {
TraverseSchema.ComplexTypeInfo baseTypeInfo = null;
baseTypeInfo = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(fCurrentElementIndex);
int aGrammarNSIndex = fGrammarNameSpaceIndex;
while (baseTypeInfo != null) {
elementIndex = fGrammar.getElementDeclIndex(element, baseTypeInfo.scopeDefined);
if (elementIndex > -1 ) {
// update the current Grammar NS index if resolving element succeed.
fGrammarNameSpaceIndex = aGrammarNSIndex;
break;
}
baseTypeInfo = baseTypeInfo.baseComplexTypeInfo;
- String baseTName = baseTypeInfo.typeName;
- if (!baseTName.startsWith("#")) {
- int comma = baseTName.indexOf(',');
- aGrammarNSIndex = fStringPool.addSymbol(baseTName.substring(0,comma).trim());
- if (aGrammarNSIndex != fGrammarNameSpaceIndex) {
- if ( !switchGrammar(aGrammarNSIndex) ) {
- break; //exit the loop in this case
+ if (baseTypeInfo != null) {
+ String baseTName = baseTypeInfo.typeName;
+ if (!baseTName.startsWith("#")) {
+ int comma = baseTName.indexOf(',');
+ aGrammarNSIndex = fStringPool.addSymbol(baseTName.substring(0,comma).trim());
+ if (aGrammarNSIndex != fGrammarNameSpaceIndex) {
+ if ( !switchGrammar(aGrammarNSIndex) ) {
+ break; //exit the loop in this case
+ }
}
}
}
}
+ if (elementIndex == -1) {
+ switchGrammar(fGrammarNameSpaceIndex);
+ }
}
//if still can't resolve it, try TOP_LEVEL_SCOPE AGAIN
/****
if ( element.uri == -1 && elementIndex == -1
&& fNamespacesScope != null
&& fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING) != -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE);
// REVISIT:
// this is a hack to handle the situation where namespace prefix "" is bound to nothing, and there
// is a "noNamespaceSchemaLocation" specified, and element
element.uri = StringPool.EMPTY_STRING;
}
/****/
/****/
if (elementIndex == -1) {
if (laxThisOne) {
fNeedValidationOff = true;
} else
if (DEBUG_SCHEMA_VALIDATION)
System.out.println("!!! can not find elementDecl in the grammar, " +
" the element localpart: " + element.localpart +
"["+fStringPool.toString(element.localpart) +"]" +
" the element uri: " + element.uri +
"["+fStringPool.toString(element.uri) +"]" +
" and the current enclosing scope: " + fCurrentScope );
}
/****/
}
if (DEBUG_SCHEMA_VALIDATION) {
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
System.out.println("elementIndex: " + elementIndex+" \n and itsName : '"
+ fStringPool.toString(fTempElementDecl.name.localpart)
+"' \n its ContentType:" + fTempElementDecl.type
+"\n its ContentSpecIndex : " + fTempElementDecl.contentSpecIndex +"\n"+
" and the current enclosing scope: " + fCurrentScope);
}
}
contentSpecType = getContentSpecType(elementIndex);
if (fGrammarIsSchemaGrammar && elementIndex != -1) {
// handle "xsi:type" right here
if (fXsiTypeAttValue > -1) {
String xsiType = fStringPool.toString(fXsiTypeAttValue);
int colonP = xsiType.indexOf(":");
String prefix = "";
String localpart = xsiType;
if (colonP > -1) {
prefix = xsiType.substring(0,colonP);
localpart = xsiType.substring(colonP+1);
}
String uri = "";
int uriIndex = -1;
if (fNamespacesScope != null) {
uriIndex = fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix));
if (uriIndex > -1) {
uri = fStringPool.toString(uriIndex);
if (uriIndex != fGrammarNameSpaceIndex) {
fGrammarNameSpaceIndex = fCurrentSchemaURI = uriIndex;
boolean success = switchGrammar(fCurrentSchemaURI);
if (!success && !fNeedValidationOff) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 3: "
+ fStringPool.toString(fCurrentSchemaURI)
+ " , can not found");
}
}
}
}
Hashtable complexRegistry = ((SchemaGrammar)fGrammar).getComplexTypeRegistry();
DatatypeValidatorFactoryImpl dataTypeReg = ((SchemaGrammar)fGrammar).getDatatypeRegistry();
if (complexRegistry==null || dataTypeReg == null) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
fErrorReporter.getLocator().getSystemId()
+" line"+fErrorReporter.getLocator().getLineNumber()
+", canot resolve xsi:type = " + xsiType+" ---2");
} else {
TraverseSchema.ComplexTypeInfo typeInfo =
(TraverseSchema.ComplexTypeInfo) complexRegistry.get(uri+","+localpart);
//TO DO:
// here need to check if this substitution is legal based on the current active grammar,
// this should be easy, cause we already saved final, block and base type information in
// the SchemaGrammar.
if (typeInfo==null) {
if (uri.length() == 0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) ) {
fXsiTypeValidator = dataTypeReg.getDatatypeValidator(localpart);
} else
fXsiTypeValidator = dataTypeReg.getDatatypeValidator(uri+","+localpart);
if ( fXsiTypeValidator == null )
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"unresolved type : "+uri+","+localpart
+" found in xsi:type handling");
} else
elementIndex = typeInfo.templateElementIndex;
}
fXsiTypeAttValue = -1;
}
//Change the current scope to be the one defined by this element.
fCurrentScope = ((SchemaGrammar) fGrammar).getElementDefinedScope(elementIndex);
// here need to check if we need to switch Grammar by asking SchemaGrammar whether
// this element actually is of a type in another Schema.
String anotherSchemaURI = ((SchemaGrammar)fGrammar).getElementFromAnotherSchemaURI(elementIndex);
if (anotherSchemaURI != null) {
//before switch Grammar, set the elementIndex to be the template elementIndex of its type
if (contentSpecType != -1
&& contentSpecType != XMLElementDecl.TYPE_EMPTY ) {
TraverseSchema.ComplexTypeInfo typeInfo = ((SchemaGrammar) fGrammar).getElementComplexTypeInfo(elementIndex);
if (typeInfo != null) {
elementIndex = typeInfo.templateElementIndex;
}
}
// now switch the grammar
fGrammarNameSpaceIndex = fCurrentSchemaURI = fStringPool.addSymbol(anotherSchemaURI);
boolean success = switchGrammar(fCurrentSchemaURI);
if (!success && !fNeedValidationOff) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 4: "
+ fStringPool.toString(fCurrentSchemaURI)
+ " , can not found");
}
}
}
if (contentSpecType == -1 && fValidating && !fNeedValidationOff ) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
element.rawname);
}
if (fGrammar != null && fGrammarIsSchemaGrammar && elementIndex != -1) {
fAttrListHandle = addDefaultAttributes(elementIndex, attrList, fAttrListHandle, fValidating, fStandaloneReader != -1);
}
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
}
if (DEBUG_PRINT_ATTRIBUTES) {
String elementStr = fStringPool.toString(element.rawname);
System.out.print("startElement: <" + elementStr);
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
// REVISIT: Validation. Do we need to recheck for the xml:lang
// attribute? It was already checked above -- perhaps
// this is to check values that are defaulted in? If
// so, this check could move to the attribute decl
// callback so we can check the default value before
// it is used.
if (fAttrListHandle != -1 && !fNeedValidationOff ) {
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attrNameIndex = attrList.getAttrName(index);
if (fStringPool.equalNames(attrNameIndex, fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index));
// break;
}
// here, we validate every "user-defined" attributes
int _xmlns = fStringPool.addSymbol("xmlns");
if (attrNameIndex != _xmlns && attrList.getAttrPrefix(index) != _xmlns)
if (fGrammar != null) {
fAttrNameLocator = getLocatorImpl(fAttrNameLocator);
fTempQName.setValues(attrList.getAttrPrefix(index),
attrList.getAttrLocalpart(index),
attrList.getAttrName(index),
attrList.getAttrURI(index) );
int attDefIndex = getAttDefByElementIndex(elementIndex, fTempQName);
if (fTempQName.uri != fXsiURI)
if (attDefIndex == -1 ) {
if (fValidating) {
// REVISIT - cache the elem/attr tuple so that we only give
// this error once for each unique occurrence
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index))};
/*****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/******/
}
} else {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
int attributeType = attributeTypeName(fTempAttDecl);
attrList.setAttType(index, attributeType);
if (fValidating) {
if (fGrammarIsDTDGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ENTITY ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ENUMERATION ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NMTOKEN ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NOTATION)
) {
validateDTDattribute(element, attrList.getAttValue(index), fTempAttDecl);
}
// check to see if this attribute matched an attribute wildcard
else if ( fGrammarIsSchemaGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_ANY
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LIST
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER) ) {
if (fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_SKIP) {
// attribute should just be bypassed,
} else if ( fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_STRICT
|| fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_LAX) {
boolean reportError = false;
boolean processContentStrict =
fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_STRICT;
if (fTempQName.uri == -1) {
if (processContentStrict) {
reportError = true;
}
} else {
Grammar aGrammar =
fGrammarResolver.getGrammar(fStringPool.toString(fTempQName.uri));
if (aGrammar == null || !(aGrammar instanceof SchemaGrammar) ) {
if (processContentStrict) {
reportError = true;
}
} else {
SchemaGrammar sGrammar = (SchemaGrammar) aGrammar;
Hashtable attRegistry = sGrammar.getAttirubteDeclRegistry();
if (attRegistry == null) {
if (processContentStrict) {
reportError = true;
}
} else {
XMLAttributeDecl attDecl = (XMLAttributeDecl) attRegistry.get(fStringPool.toString(fTempQName.localpart));
if (attDecl == null) {
if (processContentStrict) {
reportError = true;
}
} else {
DatatypeValidator attDV = attDecl.datatypeValidator;
if (attDV == null) {
if (processContentStrict) {
reportError = true;
}
} else {
try {
String unTrimValue = fStringPool.toString(attrList.getAttValue(index));
String value = unTrimValue.trim();
if (attDecl.type == XMLAttributeDecl.TYPE_ID ) {
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
}
if (attDecl.type == XMLAttributeDecl.TYPE_IDREF ) {
attDV.validate(value, this.fStoreIDRef );
} else
attDV.validate(unTrimValue, null );
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
}
}
}
}
if (reportError) {
Object[] args = { fStringPool.toString(element.rawname),
"ANY---"+fStringPool.toString(attrList.getAttrName(index))};
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} else if (fTempAttDecl.datatypeValidator == null) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index))};
System.out.println("[Error] Datatypevalidator for attribute " + fStringPool.toString(attrList.getAttrName(index))
+ " not found in element type " + fStringPool.toString(element.rawname));
//REVISIT : is this the right message?
/****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/****/
} else {
try {
String unTrimValue = fStringPool.toString(attrList.getAttValue(index));
String value = unTrimValue.trim();
if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ) {
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
} else if (fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ) {
fTempAttDecl.datatypeValidator.validate(value, this.fStoreIDRef );
} else {
fTempAttDecl.datatypeValidator.validate(unTrimValue, null );
}
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} // end of if (fValidating)
} // end of if (attDefIndex == -1) else
}// end of if (fGrammar != null)
index = fAttrList.getNextAttr(index);
}
}
}
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = attrList.getAttrPrefix(index);
if (attPrefix != fNamespacesPrefix) {
if (attPrefix != -1) {
int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (uri == -1) {
Object[] args = { fStringPool.toString(attPrefix)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
attrList.setAttrURI(index, uri);
}
}
}
index = attrList.getNextAttr(index);
}
}
fCurrentElementIndex = elementIndex;
fCurrentContentSpecType = contentSpecType;
if (fValidating && contentSpecType == XMLElementDecl.TYPE_SIMPLE) {
fBufferDatatype = true;
fDatatypeBuffer.setLength(0);
}
fInElementContent = (contentSpecType == XMLElementDecl.TYPE_CHILDREN);
} // validateElementAndAttributes(QName,XMLAttrList)
//validate attributes in DTD fashion
private void validateDTDattribute(QName element, int attValue,
XMLAttributeDecl attributeDecl) throws Exception{
AttributeValidator av = null;
switch (attributeDecl.type) {
case XMLAttributeDecl.TYPE_ENTITY:
{
boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef
String unTrimValue = fStringPool.toString(attValue);
String value = unTrimValue.trim();
//System.out.println("value = " + value );
//changes fTempAttDef
if (fValidationEnabled) {
if (value != unTrimValue) {
if (invalidStandaloneAttDef(element, attributeDecl.name)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value);
}
}
}
try {
if ( isAlistAttribute ) {
fValENTITIES.validate( value, null );
} else {
fValENTITY.validate( value, null );
}
} catch ( InvalidDatatypeValueException ex ) {
if ( ex.getMajorCode() != 1 && ex.getMinorCode() != -1 ) {
reportRecoverableXMLError(ex.getMajorCode(),
ex.getMinorCode(),
fStringPool.toString( attributeDecl.name.rawname), value );
} else {
System.err.println("Error: " + ex.getLocalizedMessage() );//Should not happen
}
}
/*if (attributeDecl.list) {
av = fAttValidatorENTITIES;
}
else {
av = fAttValidatorENTITY;
}*/
}
break;
case XMLAttributeDecl.TYPE_ENUMERATION:
av = fAttValidatorENUMERATION;
break;
case XMLAttributeDecl.TYPE_ID:
{
String unTrimValue = fStringPool.toString(attValue);
String value = unTrimValue.trim();
if (fValidationEnabled) {
if (value != unTrimValue) {
if (invalidStandaloneAttDef(element, attributeDecl.name)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value);
}
}
}
try {
//this.fIdDefs = (Hashtable) fValID.validate( value, null );
//System.out.println("this.fIdDefs = " + this.fIdDefs );
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
fValIDRef.validate( value, this.fStoreIDRef ); //just in case we called id after IDREF
} catch ( InvalidDatatypeValueException ex ) {
reportRecoverableXMLError(ex.getMajorCode(),
ex.getMinorCode(),
fStringPool.toString( attributeDecl.name.rawname), value );
}
}
break;
case XMLAttributeDecl.TYPE_IDREF:
{
String unTrimValue = fStringPool.toString(attValue);
String value = unTrimValue.trim();
boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef
//changes fTempAttDef
if (fValidationEnabled) {
if (value != unTrimValue) {
if (invalidStandaloneAttDef(element, attributeDecl.name)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value);
}
}
}
try {
if ( isAlistAttribute ) {
fValIDRefs.validate( value, this.fStoreIDRef );
} else {
fValIDRef.validate( value, this.fStoreIDRef );
}
} catch ( InvalidDatatypeValueException ex ) {
if ( ex.getMajorCode() != 1 && ex.getMinorCode() != -1 ) {
reportRecoverableXMLError(ex.getMajorCode(),
ex.getMinorCode(),
fStringPool.toString( attributeDecl.name.rawname), value );
} else {
System.err.println("Error: " + ex.getLocalizedMessage() );//Should not happen
}
}
}
break;
case XMLAttributeDecl.TYPE_NOTATION:
{
/* WIP
String unTrimValue = fStringPool.toString(attValue);
String value = unTrimValue.trim();
if (fValidationEnabled) {
if (value != unTrimValue) {
if (invalidStandaloneAttDef(element, attributeDecl.name)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value);
}
}
}
try {
//this.fIdDefs = (Hashtable) fValID.validate( value, null );
//System.out.println("this.fIdDefs = " + this.fIdDefs );
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
} catch ( InvalidDatatypeValueException ex ) {
reportRecoverableXMLError(ex.getMajorCode(),
ex.getMinorCode(),
fStringPool.toString( attributeDecl.name.rawname), value );
}
}
*/
av = fAttValidatorNOTATION;
}
break;
case XMLAttributeDecl.TYPE_NMTOKEN:
{
String unTrimValue = fStringPool.toString(attValue);
String value = unTrimValue.trim();
boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef
//changes fTempAttDef
if (fValidationEnabled) {
if (value != unTrimValue) {
if (invalidStandaloneAttDef(element, attributeDecl.name)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value);
}
}
}
try {
if ( isAlistAttribute ) {
fValNMTOKENS.validate( value, null );
} else {
fValNMTOKEN.validate( value, null );
}
} catch ( InvalidDatatypeValueException ex ) {
reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID,
XMLMessages.VC_NAME_TOKEN,
fStringPool.toString(attributeDecl.name.rawname), value);//TODO NMTOKENS messge
}
}
break;
}
if ( av != null )
av.normalize(element, attributeDecl.name, attValue,
attributeDecl.type, attributeDecl.enumeration);
}
/** Character data in content. */
private void charDataInContent() {
if (DEBUG_ELEMENT_CHILDREN) {
System.out.println("charDataInContent()");
}
if (fElementChildren.length <= fElementChildrenLength) {
QName[] newarray = new QName[fElementChildren.length * 2];
System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length);
fElementChildren = newarray;
}
QName qname = fElementChildren[fElementChildrenLength];
if (qname == null) {
for (int i = fElementChildrenLength; i < fElementChildren.length; i++) {
fElementChildren[i] = new QName();
}
qname = fElementChildren[fElementChildrenLength];
}
qname.clear();
fElementChildrenLength++;
} // charDataInCount()
/**
* Check that the content of an element is valid.
* <p>
* This is the method of primary concern to the validator. This method is called
* upon the scanner reaching the end tag of an element. At that time, the
* element's children must be structurally validated, so it calls this method.
* The index of the element being checked (in the decl pool), is provided as
* well as an array of element name indexes of the children. The validator must
* confirm that this element can have these children in this order.
* <p>
* This can also be called to do 'what if' testing of content models just to see
* if they would be valid.
* <p>
* Note that the element index is an index into the element decl pool, whereas
* the children indexes are name indexes, i.e. into the string pool.
* <p>
* A value of -1 in the children array indicates a PCDATA node. All other
* indexes will be positive and represent child elements. The count can be
* zero, since some elements have the EMPTY content model and that must be
* confirmed.
*
* @param elementIndex The index within the <code>ElementDeclPool</code> of this
* element.
* @param childCount The number of entries in the <code>children</code> array.
* @param children The children of this element. Each integer is an index within
* the <code>StringPool</code> of the child element name. An index
* of -1 is used to indicate an occurrence of non-whitespace character
* data.
*
* @return The value -1 if fully valid, else the 0 based index of the child
* that first failed. If the value returned is equal to the number
* of children, then additional content is required to reach a valid
* ending state.
*
* @exception Exception Thrown on error.
*/
private int checkContent(int elementIndex,
QName[] children,
int childOffset,
int childCount) throws Exception {
// Get the element name index from the element
// REVISIT: Validation
final int elementType = fCurrentElement.rawname;
if (DEBUG_PRINT_CONTENT) {
String strTmp = fStringPool.toString(elementType);
System.out.println("Name: "+strTmp+", "+
"Count: "+childCount+", "+
"ContentSpecType: " +fCurrentContentSpecType); //+getContentSpecAsString(elementIndex));
for (int index = childOffset; index < (childOffset+childCount) && index < 10; index++) {
if (index == 0) {
System.out.print(" (");
}
String childName = (children[index].localpart == -1) ? "#PCDATA" : fStringPool.toString(children[index].localpart);
if (index + 1 == childCount) {
System.out.println(childName + ")");
} else if (index + 1 == 10) {
System.out.println(childName + ",...)");
} else {
System.out.print(childName + ",");
}
}
}
// Get out the content spec for this element
final int contentType = fCurrentContentSpecType;
// debugging
//System.out.println("~~~~~~in checkContent, fCurrentContentSpecType : " + fCurrentContentSpecType);
//
// Deal with the possible types of content. We try to optimized here
// by dealing specially with content models that don't require the
// full DFA treatment.
//
if (contentType == XMLElementDecl.TYPE_EMPTY) {
//
// If the child count is greater than zero, then this is
// an error right off the bat at index 0.
//
if (childCount != 0) {
return 0;
}
} else if (contentType == XMLElementDecl.TYPE_ANY) {
//
// This one is open game so we don't pass any judgement on it
// at all. Its assumed to fine since it can hold anything.
//
} else if (contentType == XMLElementDecl.TYPE_MIXED ||
contentType == XMLElementDecl.TYPE_CHILDREN) {
// Get the content model for this element, faulting it in if needed
XMLContentModel cmElem = null;
try {
cmElem = getElementContentModel(elementIndex);
int result = cmElem.validateContent(children, childOffset, childCount);
if (result != -1 && fGrammarIsSchemaGrammar) {
// REVISIT: not optimized for performance,
EquivClassComparator comparator = new EquivClassComparator(fGrammarResolver, fStringPool);
cmElem.setEquivClassComparator(comparator);
result = cmElem.validateContentSpecial(children, childOffset, childCount);
}
return result;
} catch (CMException excToCatch) {
// REVISIT - Translate the caught exception to the protected error API
int majorCode = excToCatch.getErrorCode();
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
majorCode,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
} else if (contentType == -1) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
elementType);
} else if (contentType == XMLElementDecl.TYPE_SIMPLE ) {
XMLContentModel cmElem = null;
if (childCount > 0) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { "In element '"+fStringPool.toString(elementType)+"' : "+
"Can not have element children within a simple type content"},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} else {
try {
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
DatatypeValidator dv = fTempElementDecl.datatypeValidator;
// If there is xsi:type validator, substitute it.
if ( fXsiTypeValidator != null ) {
dv = fXsiTypeValidator;
fXsiTypeValidator = null;
}
if (dv == null) {
System.out.println("Internal Error: this element have a simpletype "+
"but no datatypevalidator was found, element "+fTempElementDecl.name
+",locapart: "+fStringPool.toString(fTempElementDecl.name.localpart));
} else {
dv.validate(fDatatypeBuffer.toString(), null);
}
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { "In element '"+fStringPool.toString(elementType)+"' : "+idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} else {
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
ImplementationMessages.VAL_CST,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
// We succeeded
return -1;
} // checkContent(int,int,int[]):int
/**
* Checks that all declared elements refer to declared elements
* in their content models. This method calls out to the error
* handler to indicate warnings.
*/
/*private void checkDeclaredElements() throws Exception {
//****DEBUG****
if (DEBUG) print("(???) XMLValidator.checkDeclaredElements\n");
//****DEBUG****
for (int i = 0; i < fElementCount; i++) {
int type = fGrammar.getContentSpecType(i);
if (type == XMLElementDecl.TYPE_MIXED || type == XMLElementDecl.TYPE_CHILDREN) {
int chunk = i >> CHUNK_SHIFT;
int index = i & CHUNK_MASK;
int contentSpecIndex = fContentSpec[chunk][index];
checkDeclaredElements(i, contentSpecIndex);
}
}
}
*/
private void printChildren() {
if (DEBUG_ELEMENT_CHILDREN) {
System.out.print('[');
for (int i = 0; i < fElementChildrenLength; i++) {
System.out.print(' ');
QName qname = fElementChildren[i];
if (qname != null) {
System.out.print(fStringPool.toString(qname.rawname));
} else {
System.out.print("null");
}
if (i < fElementChildrenLength - 1) {
System.out.print(", ");
}
System.out.flush();
}
System.out.print(" ]");
System.out.println();
}
}
private void printStack() {
if (DEBUG_ELEMENT_CHILDREN) {
System.out.print('{');
for (int i = 0; i <= fElementDepth; i++) {
System.out.print(' ');
System.out.print(fElementChildrenOffsetStack[i]);
if (i < fElementDepth) {
System.out.print(", ");
}
System.out.flush();
}
System.out.print(" }");
System.out.println();
}
}
//
// Interfaces
//
/**
* AttributeValidator.
*/
public interface AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValue, int attType, int enumHandle)
throws Exception;
} // interface AttributeValidator
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
//
// Classes
//
/**
* AttValidatorNOTATION.
*/
final class AttValidatorNOTATION
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
} else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
//
// NOTATION - check that the value is in the AttDef enumeration (V_TAGo)
//
if (!fStringPool.stringInList(enumHandle, attValueHandle)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST,
XMLMessages.VC_NOTATION_ATTRIBUTES,
fStringPool.toString(attribute.rawname),
newAttValue, fStringPool.stringListAsString(enumHandle));
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorNOTATION
/**
* AttValidatorENUMERATION.
*/
final class AttValidatorENUMERATION
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
} else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
//
// ENUMERATION - check that value is in the AttDef enumeration (V_TAG9)
//
if (!fStringPool.stringInList(enumHandle, attValueHandle)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST,
XMLMessages.VC_ENUMERATION,
fStringPool.toString(attribute.rawname),
newAttValue, fStringPool.stringListAsString(enumHandle));
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorENUMERATION
} // class XMLValidator
| false | true | private void validateElementAndAttributes(QName element,
XMLAttrList attrList)
throws Exception {
if ((fElementDepth >= 0 && fValidationFlagStack[fElementDepth] != 0 )||
(fGrammar == null && !fValidating && !fNamespacesEnabled) ) {
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
if (fStringPool.equalNames(fAttrList.getAttrName(index), fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(fAttrList.getAttValue(index));
break;
}
index = fAttrList.getNextAttr(index);
}
}
return;
}
int elementIndex = -1;
int contentSpecType = -1;
boolean skipThisOne = false;
boolean laxThisOne = false;
if ( fGrammarIsSchemaGrammar && fContentLeafStack[fElementDepth] != null ) {
ContentLeafNameTypeVector cv = fContentLeafStack[fElementDepth];
QName[] fElemMap = cv.leafNames;
for (int i=0; i<cv.leafCount; i++) {
int type = cv.leafTypes[i] ;
//System.out.println("******* see a ANY_OTHER_SKIP, "+type+","+element+","+fElemMap[i]+"\n*******");
if (type == XMLContentSpec.CONTENTSPECNODE_LEAF) {
if (fElemMap[i].uri==element.uri
&& fElemMap[i].localpart == element.localpart)
break;
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL) {
if (element.uri == -1) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER) {
if (fElemMap[i].uri != element.uri) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_SKIP) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_SKIP) {
if (element.uri == -1) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP) {
if (fElemMap[i].uri != element.uri) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LAX) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
laxThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_LAX) {
if (element.uri == -1) {
laxThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX) {
if (fElemMap[i].uri != element.uri) {
laxThisOne = true;
break;
}
}
}
}
if (skipThisOne) {
fNeedValidationOff = true;
} else {
//REVISIT: is this the right place to check on if the Schema has changed?
if ( fNamespacesEnabled && fValidating && element.uri != fGrammarNameSpaceIndex && element.uri != -1 ) {
fGrammarNameSpaceIndex = element.uri;
boolean success = switchGrammar(fGrammarNameSpaceIndex);
if (!success && !laxThisOne) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 2: " + fStringPool.toString(fGrammarNameSpaceIndex)
+ " , can not found");
}
}
if ( fGrammar != null ) {
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("*******Lookup element: uri: " + fStringPool.toString(element.uri)+
"localpart: '" + fStringPool.toString(element.localpart)
+"' and scope : " + fCurrentScope+"\n");
}
elementIndex = fGrammar.getElementDeclIndex(element,fCurrentScope);
if (elementIndex == -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element, TOP_LEVEL_SCOPE);
}
if (elementIndex == -1) {
// if validating based on a Schema, try to resolve the element again by searching in its type's ancestor types
if (fGrammarIsSchemaGrammar && fCurrentElementIndex != -1) {
TraverseSchema.ComplexTypeInfo baseTypeInfo = null;
baseTypeInfo = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(fCurrentElementIndex);
int aGrammarNSIndex = fGrammarNameSpaceIndex;
while (baseTypeInfo != null) {
elementIndex = fGrammar.getElementDeclIndex(element, baseTypeInfo.scopeDefined);
if (elementIndex > -1 ) {
// update the current Grammar NS index if resolving element succeed.
fGrammarNameSpaceIndex = aGrammarNSIndex;
break;
}
baseTypeInfo = baseTypeInfo.baseComplexTypeInfo;
String baseTName = baseTypeInfo.typeName;
if (!baseTName.startsWith("#")) {
int comma = baseTName.indexOf(',');
aGrammarNSIndex = fStringPool.addSymbol(baseTName.substring(0,comma).trim());
if (aGrammarNSIndex != fGrammarNameSpaceIndex) {
if ( !switchGrammar(aGrammarNSIndex) ) {
break; //exit the loop in this case
}
}
}
}
}
//if still can't resolve it, try TOP_LEVEL_SCOPE AGAIN
/****
if ( element.uri == -1 && elementIndex == -1
&& fNamespacesScope != null
&& fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING) != -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE);
// REVISIT:
// this is a hack to handle the situation where namespace prefix "" is bound to nothing, and there
// is a "noNamespaceSchemaLocation" specified, and element
element.uri = StringPool.EMPTY_STRING;
}
/****/
/****/
if (elementIndex == -1) {
if (laxThisOne) {
fNeedValidationOff = true;
} else
if (DEBUG_SCHEMA_VALIDATION)
System.out.println("!!! can not find elementDecl in the grammar, " +
" the element localpart: " + element.localpart +
"["+fStringPool.toString(element.localpart) +"]" +
" the element uri: " + element.uri +
"["+fStringPool.toString(element.uri) +"]" +
" and the current enclosing scope: " + fCurrentScope );
}
/****/
}
if (DEBUG_SCHEMA_VALIDATION) {
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
System.out.println("elementIndex: " + elementIndex+" \n and itsName : '"
+ fStringPool.toString(fTempElementDecl.name.localpart)
+"' \n its ContentType:" + fTempElementDecl.type
+"\n its ContentSpecIndex : " + fTempElementDecl.contentSpecIndex +"\n"+
" and the current enclosing scope: " + fCurrentScope);
}
}
contentSpecType = getContentSpecType(elementIndex);
if (fGrammarIsSchemaGrammar && elementIndex != -1) {
// handle "xsi:type" right here
if (fXsiTypeAttValue > -1) {
String xsiType = fStringPool.toString(fXsiTypeAttValue);
int colonP = xsiType.indexOf(":");
String prefix = "";
String localpart = xsiType;
if (colonP > -1) {
prefix = xsiType.substring(0,colonP);
localpart = xsiType.substring(colonP+1);
}
String uri = "";
int uriIndex = -1;
if (fNamespacesScope != null) {
uriIndex = fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix));
if (uriIndex > -1) {
uri = fStringPool.toString(uriIndex);
if (uriIndex != fGrammarNameSpaceIndex) {
fGrammarNameSpaceIndex = fCurrentSchemaURI = uriIndex;
boolean success = switchGrammar(fCurrentSchemaURI);
if (!success && !fNeedValidationOff) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 3: "
+ fStringPool.toString(fCurrentSchemaURI)
+ " , can not found");
}
}
}
}
Hashtable complexRegistry = ((SchemaGrammar)fGrammar).getComplexTypeRegistry();
DatatypeValidatorFactoryImpl dataTypeReg = ((SchemaGrammar)fGrammar).getDatatypeRegistry();
if (complexRegistry==null || dataTypeReg == null) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
fErrorReporter.getLocator().getSystemId()
+" line"+fErrorReporter.getLocator().getLineNumber()
+", canot resolve xsi:type = " + xsiType+" ---2");
} else {
TraverseSchema.ComplexTypeInfo typeInfo =
(TraverseSchema.ComplexTypeInfo) complexRegistry.get(uri+","+localpart);
//TO DO:
// here need to check if this substitution is legal based on the current active grammar,
// this should be easy, cause we already saved final, block and base type information in
// the SchemaGrammar.
if (typeInfo==null) {
if (uri.length() == 0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) ) {
fXsiTypeValidator = dataTypeReg.getDatatypeValidator(localpart);
} else
fXsiTypeValidator = dataTypeReg.getDatatypeValidator(uri+","+localpart);
if ( fXsiTypeValidator == null )
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"unresolved type : "+uri+","+localpart
+" found in xsi:type handling");
} else
elementIndex = typeInfo.templateElementIndex;
}
fXsiTypeAttValue = -1;
}
//Change the current scope to be the one defined by this element.
fCurrentScope = ((SchemaGrammar) fGrammar).getElementDefinedScope(elementIndex);
// here need to check if we need to switch Grammar by asking SchemaGrammar whether
// this element actually is of a type in another Schema.
String anotherSchemaURI = ((SchemaGrammar)fGrammar).getElementFromAnotherSchemaURI(elementIndex);
if (anotherSchemaURI != null) {
//before switch Grammar, set the elementIndex to be the template elementIndex of its type
if (contentSpecType != -1
&& contentSpecType != XMLElementDecl.TYPE_EMPTY ) {
TraverseSchema.ComplexTypeInfo typeInfo = ((SchemaGrammar) fGrammar).getElementComplexTypeInfo(elementIndex);
if (typeInfo != null) {
elementIndex = typeInfo.templateElementIndex;
}
}
// now switch the grammar
fGrammarNameSpaceIndex = fCurrentSchemaURI = fStringPool.addSymbol(anotherSchemaURI);
boolean success = switchGrammar(fCurrentSchemaURI);
if (!success && !fNeedValidationOff) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 4: "
+ fStringPool.toString(fCurrentSchemaURI)
+ " , can not found");
}
}
}
if (contentSpecType == -1 && fValidating && !fNeedValidationOff ) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
element.rawname);
}
if (fGrammar != null && fGrammarIsSchemaGrammar && elementIndex != -1) {
fAttrListHandle = addDefaultAttributes(elementIndex, attrList, fAttrListHandle, fValidating, fStandaloneReader != -1);
}
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
}
if (DEBUG_PRINT_ATTRIBUTES) {
String elementStr = fStringPool.toString(element.rawname);
System.out.print("startElement: <" + elementStr);
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
// REVISIT: Validation. Do we need to recheck for the xml:lang
// attribute? It was already checked above -- perhaps
// this is to check values that are defaulted in? If
// so, this check could move to the attribute decl
// callback so we can check the default value before
// it is used.
if (fAttrListHandle != -1 && !fNeedValidationOff ) {
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attrNameIndex = attrList.getAttrName(index);
if (fStringPool.equalNames(attrNameIndex, fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index));
// break;
}
// here, we validate every "user-defined" attributes
int _xmlns = fStringPool.addSymbol("xmlns");
if (attrNameIndex != _xmlns && attrList.getAttrPrefix(index) != _xmlns)
if (fGrammar != null) {
fAttrNameLocator = getLocatorImpl(fAttrNameLocator);
fTempQName.setValues(attrList.getAttrPrefix(index),
attrList.getAttrLocalpart(index),
attrList.getAttrName(index),
attrList.getAttrURI(index) );
int attDefIndex = getAttDefByElementIndex(elementIndex, fTempQName);
if (fTempQName.uri != fXsiURI)
if (attDefIndex == -1 ) {
if (fValidating) {
// REVISIT - cache the elem/attr tuple so that we only give
// this error once for each unique occurrence
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index))};
/*****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/******/
}
} else {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
int attributeType = attributeTypeName(fTempAttDecl);
attrList.setAttType(index, attributeType);
if (fValidating) {
if (fGrammarIsDTDGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ENTITY ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ENUMERATION ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NMTOKEN ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NOTATION)
) {
validateDTDattribute(element, attrList.getAttValue(index), fTempAttDecl);
}
// check to see if this attribute matched an attribute wildcard
else if ( fGrammarIsSchemaGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_ANY
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LIST
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER) ) {
if (fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_SKIP) {
// attribute should just be bypassed,
} else if ( fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_STRICT
|| fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_LAX) {
boolean reportError = false;
boolean processContentStrict =
fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_STRICT;
if (fTempQName.uri == -1) {
if (processContentStrict) {
reportError = true;
}
} else {
Grammar aGrammar =
fGrammarResolver.getGrammar(fStringPool.toString(fTempQName.uri));
if (aGrammar == null || !(aGrammar instanceof SchemaGrammar) ) {
if (processContentStrict) {
reportError = true;
}
} else {
SchemaGrammar sGrammar = (SchemaGrammar) aGrammar;
Hashtable attRegistry = sGrammar.getAttirubteDeclRegistry();
if (attRegistry == null) {
if (processContentStrict) {
reportError = true;
}
} else {
XMLAttributeDecl attDecl = (XMLAttributeDecl) attRegistry.get(fStringPool.toString(fTempQName.localpart));
if (attDecl == null) {
if (processContentStrict) {
reportError = true;
}
} else {
DatatypeValidator attDV = attDecl.datatypeValidator;
if (attDV == null) {
if (processContentStrict) {
reportError = true;
}
} else {
try {
String unTrimValue = fStringPool.toString(attrList.getAttValue(index));
String value = unTrimValue.trim();
if (attDecl.type == XMLAttributeDecl.TYPE_ID ) {
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
}
if (attDecl.type == XMLAttributeDecl.TYPE_IDREF ) {
attDV.validate(value, this.fStoreIDRef );
} else
attDV.validate(unTrimValue, null );
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
}
}
}
}
if (reportError) {
Object[] args = { fStringPool.toString(element.rawname),
"ANY---"+fStringPool.toString(attrList.getAttrName(index))};
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} else if (fTempAttDecl.datatypeValidator == null) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index))};
System.out.println("[Error] Datatypevalidator for attribute " + fStringPool.toString(attrList.getAttrName(index))
+ " not found in element type " + fStringPool.toString(element.rawname));
//REVISIT : is this the right message?
/****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/****/
} else {
try {
String unTrimValue = fStringPool.toString(attrList.getAttValue(index));
String value = unTrimValue.trim();
if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ) {
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
} else if (fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ) {
fTempAttDecl.datatypeValidator.validate(value, this.fStoreIDRef );
} else {
fTempAttDecl.datatypeValidator.validate(unTrimValue, null );
}
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} // end of if (fValidating)
} // end of if (attDefIndex == -1) else
}// end of if (fGrammar != null)
index = fAttrList.getNextAttr(index);
}
}
}
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = attrList.getAttrPrefix(index);
if (attPrefix != fNamespacesPrefix) {
if (attPrefix != -1) {
int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (uri == -1) {
Object[] args = { fStringPool.toString(attPrefix)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
attrList.setAttrURI(index, uri);
}
}
}
index = attrList.getNextAttr(index);
}
}
fCurrentElementIndex = elementIndex;
fCurrentContentSpecType = contentSpecType;
if (fValidating && contentSpecType == XMLElementDecl.TYPE_SIMPLE) {
fBufferDatatype = true;
fDatatypeBuffer.setLength(0);
}
fInElementContent = (contentSpecType == XMLElementDecl.TYPE_CHILDREN);
} // validateElementAndAttributes(QName,XMLAttrList)
| private void validateElementAndAttributes(QName element,
XMLAttrList attrList)
throws Exception {
if ((fElementDepth >= 0 && fValidationFlagStack[fElementDepth] != 0 )||
(fGrammar == null && !fValidating && !fNamespacesEnabled) ) {
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
if (fStringPool.equalNames(fAttrList.getAttrName(index), fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(fAttrList.getAttValue(index));
break;
}
index = fAttrList.getNextAttr(index);
}
}
return;
}
int elementIndex = -1;
int contentSpecType = -1;
boolean skipThisOne = false;
boolean laxThisOne = false;
if ( fGrammarIsSchemaGrammar && fContentLeafStack[fElementDepth] != null ) {
ContentLeafNameTypeVector cv = fContentLeafStack[fElementDepth];
QName[] fElemMap = cv.leafNames;
for (int i=0; i<cv.leafCount; i++) {
int type = cv.leafTypes[i] ;
//System.out.println("******* see a ANY_OTHER_SKIP, "+type+","+element+","+fElemMap[i]+"\n*******");
if (type == XMLContentSpec.CONTENTSPECNODE_LEAF) {
if (fElemMap[i].uri==element.uri
&& fElemMap[i].localpart == element.localpart)
break;
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL) {
if (element.uri == -1) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER) {
if (fElemMap[i].uri != element.uri) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_SKIP) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_SKIP) {
if (element.uri == -1) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP) {
if (fElemMap[i].uri != element.uri) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LAX) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
laxThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_LAX) {
if (element.uri == -1) {
laxThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX) {
if (fElemMap[i].uri != element.uri) {
laxThisOne = true;
break;
}
}
}
}
if (skipThisOne) {
fNeedValidationOff = true;
} else {
//REVISIT: is this the right place to check on if the Schema has changed?
if ( fNamespacesEnabled && fValidating && element.uri != fGrammarNameSpaceIndex && element.uri != -1 ) {
fGrammarNameSpaceIndex = element.uri;
boolean success = switchGrammar(fGrammarNameSpaceIndex);
if (!success && !laxThisOne) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 2: " + fStringPool.toString(fGrammarNameSpaceIndex)
+ " , can not found");
}
}
if ( fGrammar != null ) {
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("*******Lookup element: uri: " + fStringPool.toString(element.uri)+
"localpart: '" + fStringPool.toString(element.localpart)
+"' and scope : " + fCurrentScope+"\n");
}
elementIndex = fGrammar.getElementDeclIndex(element,fCurrentScope);
if (elementIndex == -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element, TOP_LEVEL_SCOPE);
}
if (elementIndex == -1) {
// if validating based on a Schema, try to resolve the element again by searching in its type's ancestor types
if (fGrammarIsSchemaGrammar && fCurrentElementIndex != -1) {
TraverseSchema.ComplexTypeInfo baseTypeInfo = null;
baseTypeInfo = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(fCurrentElementIndex);
int aGrammarNSIndex = fGrammarNameSpaceIndex;
while (baseTypeInfo != null) {
elementIndex = fGrammar.getElementDeclIndex(element, baseTypeInfo.scopeDefined);
if (elementIndex > -1 ) {
// update the current Grammar NS index if resolving element succeed.
fGrammarNameSpaceIndex = aGrammarNSIndex;
break;
}
baseTypeInfo = baseTypeInfo.baseComplexTypeInfo;
if (baseTypeInfo != null) {
String baseTName = baseTypeInfo.typeName;
if (!baseTName.startsWith("#")) {
int comma = baseTName.indexOf(',');
aGrammarNSIndex = fStringPool.addSymbol(baseTName.substring(0,comma).trim());
if (aGrammarNSIndex != fGrammarNameSpaceIndex) {
if ( !switchGrammar(aGrammarNSIndex) ) {
break; //exit the loop in this case
}
}
}
}
}
if (elementIndex == -1) {
switchGrammar(fGrammarNameSpaceIndex);
}
}
//if still can't resolve it, try TOP_LEVEL_SCOPE AGAIN
/****
if ( element.uri == -1 && elementIndex == -1
&& fNamespacesScope != null
&& fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING) != -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE);
// REVISIT:
// this is a hack to handle the situation where namespace prefix "" is bound to nothing, and there
// is a "noNamespaceSchemaLocation" specified, and element
element.uri = StringPool.EMPTY_STRING;
}
/****/
/****/
if (elementIndex == -1) {
if (laxThisOne) {
fNeedValidationOff = true;
} else
if (DEBUG_SCHEMA_VALIDATION)
System.out.println("!!! can not find elementDecl in the grammar, " +
" the element localpart: " + element.localpart +
"["+fStringPool.toString(element.localpart) +"]" +
" the element uri: " + element.uri +
"["+fStringPool.toString(element.uri) +"]" +
" and the current enclosing scope: " + fCurrentScope );
}
/****/
}
if (DEBUG_SCHEMA_VALIDATION) {
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
System.out.println("elementIndex: " + elementIndex+" \n and itsName : '"
+ fStringPool.toString(fTempElementDecl.name.localpart)
+"' \n its ContentType:" + fTempElementDecl.type
+"\n its ContentSpecIndex : " + fTempElementDecl.contentSpecIndex +"\n"+
" and the current enclosing scope: " + fCurrentScope);
}
}
contentSpecType = getContentSpecType(elementIndex);
if (fGrammarIsSchemaGrammar && elementIndex != -1) {
// handle "xsi:type" right here
if (fXsiTypeAttValue > -1) {
String xsiType = fStringPool.toString(fXsiTypeAttValue);
int colonP = xsiType.indexOf(":");
String prefix = "";
String localpart = xsiType;
if (colonP > -1) {
prefix = xsiType.substring(0,colonP);
localpart = xsiType.substring(colonP+1);
}
String uri = "";
int uriIndex = -1;
if (fNamespacesScope != null) {
uriIndex = fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix));
if (uriIndex > -1) {
uri = fStringPool.toString(uriIndex);
if (uriIndex != fGrammarNameSpaceIndex) {
fGrammarNameSpaceIndex = fCurrentSchemaURI = uriIndex;
boolean success = switchGrammar(fCurrentSchemaURI);
if (!success && !fNeedValidationOff) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 3: "
+ fStringPool.toString(fCurrentSchemaURI)
+ " , can not found");
}
}
}
}
Hashtable complexRegistry = ((SchemaGrammar)fGrammar).getComplexTypeRegistry();
DatatypeValidatorFactoryImpl dataTypeReg = ((SchemaGrammar)fGrammar).getDatatypeRegistry();
if (complexRegistry==null || dataTypeReg == null) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
fErrorReporter.getLocator().getSystemId()
+" line"+fErrorReporter.getLocator().getLineNumber()
+", canot resolve xsi:type = " + xsiType+" ---2");
} else {
TraverseSchema.ComplexTypeInfo typeInfo =
(TraverseSchema.ComplexTypeInfo) complexRegistry.get(uri+","+localpart);
//TO DO:
// here need to check if this substitution is legal based on the current active grammar,
// this should be easy, cause we already saved final, block and base type information in
// the SchemaGrammar.
if (typeInfo==null) {
if (uri.length() == 0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) ) {
fXsiTypeValidator = dataTypeReg.getDatatypeValidator(localpart);
} else
fXsiTypeValidator = dataTypeReg.getDatatypeValidator(uri+","+localpart);
if ( fXsiTypeValidator == null )
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"unresolved type : "+uri+","+localpart
+" found in xsi:type handling");
} else
elementIndex = typeInfo.templateElementIndex;
}
fXsiTypeAttValue = -1;
}
//Change the current scope to be the one defined by this element.
fCurrentScope = ((SchemaGrammar) fGrammar).getElementDefinedScope(elementIndex);
// here need to check if we need to switch Grammar by asking SchemaGrammar whether
// this element actually is of a type in another Schema.
String anotherSchemaURI = ((SchemaGrammar)fGrammar).getElementFromAnotherSchemaURI(elementIndex);
if (anotherSchemaURI != null) {
//before switch Grammar, set the elementIndex to be the template elementIndex of its type
if (contentSpecType != -1
&& contentSpecType != XMLElementDecl.TYPE_EMPTY ) {
TraverseSchema.ComplexTypeInfo typeInfo = ((SchemaGrammar) fGrammar).getElementComplexTypeInfo(elementIndex);
if (typeInfo != null) {
elementIndex = typeInfo.templateElementIndex;
}
}
// now switch the grammar
fGrammarNameSpaceIndex = fCurrentSchemaURI = fStringPool.addSymbol(anotherSchemaURI);
boolean success = switchGrammar(fCurrentSchemaURI);
if (!success && !fNeedValidationOff) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 4: "
+ fStringPool.toString(fCurrentSchemaURI)
+ " , can not found");
}
}
}
if (contentSpecType == -1 && fValidating && !fNeedValidationOff ) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
element.rawname);
}
if (fGrammar != null && fGrammarIsSchemaGrammar && elementIndex != -1) {
fAttrListHandle = addDefaultAttributes(elementIndex, attrList, fAttrListHandle, fValidating, fStandaloneReader != -1);
}
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
}
if (DEBUG_PRINT_ATTRIBUTES) {
String elementStr = fStringPool.toString(element.rawname);
System.out.print("startElement: <" + elementStr);
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
// REVISIT: Validation. Do we need to recheck for the xml:lang
// attribute? It was already checked above -- perhaps
// this is to check values that are defaulted in? If
// so, this check could move to the attribute decl
// callback so we can check the default value before
// it is used.
if (fAttrListHandle != -1 && !fNeedValidationOff ) {
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attrNameIndex = attrList.getAttrName(index);
if (fStringPool.equalNames(attrNameIndex, fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index));
// break;
}
// here, we validate every "user-defined" attributes
int _xmlns = fStringPool.addSymbol("xmlns");
if (attrNameIndex != _xmlns && attrList.getAttrPrefix(index) != _xmlns)
if (fGrammar != null) {
fAttrNameLocator = getLocatorImpl(fAttrNameLocator);
fTempQName.setValues(attrList.getAttrPrefix(index),
attrList.getAttrLocalpart(index),
attrList.getAttrName(index),
attrList.getAttrURI(index) );
int attDefIndex = getAttDefByElementIndex(elementIndex, fTempQName);
if (fTempQName.uri != fXsiURI)
if (attDefIndex == -1 ) {
if (fValidating) {
// REVISIT - cache the elem/attr tuple so that we only give
// this error once for each unique occurrence
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index))};
/*****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/******/
}
} else {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
int attributeType = attributeTypeName(fTempAttDecl);
attrList.setAttType(index, attributeType);
if (fValidating) {
if (fGrammarIsDTDGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ENTITY ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ENUMERATION ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NMTOKEN ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NOTATION)
) {
validateDTDattribute(element, attrList.getAttValue(index), fTempAttDecl);
}
// check to see if this attribute matched an attribute wildcard
else if ( fGrammarIsSchemaGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_ANY
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LIST
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER) ) {
if (fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_SKIP) {
// attribute should just be bypassed,
} else if ( fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_STRICT
|| fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_LAX) {
boolean reportError = false;
boolean processContentStrict =
fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_STRICT;
if (fTempQName.uri == -1) {
if (processContentStrict) {
reportError = true;
}
} else {
Grammar aGrammar =
fGrammarResolver.getGrammar(fStringPool.toString(fTempQName.uri));
if (aGrammar == null || !(aGrammar instanceof SchemaGrammar) ) {
if (processContentStrict) {
reportError = true;
}
} else {
SchemaGrammar sGrammar = (SchemaGrammar) aGrammar;
Hashtable attRegistry = sGrammar.getAttirubteDeclRegistry();
if (attRegistry == null) {
if (processContentStrict) {
reportError = true;
}
} else {
XMLAttributeDecl attDecl = (XMLAttributeDecl) attRegistry.get(fStringPool.toString(fTempQName.localpart));
if (attDecl == null) {
if (processContentStrict) {
reportError = true;
}
} else {
DatatypeValidator attDV = attDecl.datatypeValidator;
if (attDV == null) {
if (processContentStrict) {
reportError = true;
}
} else {
try {
String unTrimValue = fStringPool.toString(attrList.getAttValue(index));
String value = unTrimValue.trim();
if (attDecl.type == XMLAttributeDecl.TYPE_ID ) {
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
}
if (attDecl.type == XMLAttributeDecl.TYPE_IDREF ) {
attDV.validate(value, this.fStoreIDRef );
} else
attDV.validate(unTrimValue, null );
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
}
}
}
}
if (reportError) {
Object[] args = { fStringPool.toString(element.rawname),
"ANY---"+fStringPool.toString(attrList.getAttrName(index))};
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} else if (fTempAttDecl.datatypeValidator == null) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index))};
System.out.println("[Error] Datatypevalidator for attribute " + fStringPool.toString(attrList.getAttrName(index))
+ " not found in element type " + fStringPool.toString(element.rawname));
//REVISIT : is this the right message?
/****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/****/
} else {
try {
String unTrimValue = fStringPool.toString(attrList.getAttValue(index));
String value = unTrimValue.trim();
if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ) {
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
} else if (fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ) {
fTempAttDecl.datatypeValidator.validate(value, this.fStoreIDRef );
} else {
fTempAttDecl.datatypeValidator.validate(unTrimValue, null );
}
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} // end of if (fValidating)
} // end of if (attDefIndex == -1) else
}// end of if (fGrammar != null)
index = fAttrList.getNextAttr(index);
}
}
}
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = attrList.getAttrPrefix(index);
if (attPrefix != fNamespacesPrefix) {
if (attPrefix != -1) {
int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (uri == -1) {
Object[] args = { fStringPool.toString(attPrefix)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
attrList.setAttrURI(index, uri);
}
}
}
index = attrList.getNextAttr(index);
}
}
fCurrentElementIndex = elementIndex;
fCurrentContentSpecType = contentSpecType;
if (fValidating && contentSpecType == XMLElementDecl.TYPE_SIMPLE) {
fBufferDatatype = true;
fDatatypeBuffer.setLength(0);
}
fInElementContent = (contentSpecType == XMLElementDecl.TYPE_CHILDREN);
} // validateElementAndAttributes(QName,XMLAttrList)
|
diff --git a/GAE/src/org/waterforpeople/mapping/app/gwt/client/survey/SurveyGroupDto.java b/GAE/src/org/waterforpeople/mapping/app/gwt/client/survey/SurveyGroupDto.java
index f674023b9..ba7ad867e 100644
--- a/GAE/src/org/waterforpeople/mapping/app/gwt/client/survey/SurveyGroupDto.java
+++ b/GAE/src/org/waterforpeople/mapping/app/gwt/client/survey/SurveyGroupDto.java
@@ -1,69 +1,69 @@
package org.waterforpeople.mapping.app.gwt.client.survey;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import com.gallatinsystems.framework.gwt.dto.client.BaseDto;
public class SurveyGroupDto extends BaseDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2235565143615667202L;
private String description;
private String code;
private Date createdDateTime;
private Date lastUpdateDateTime;
private ArrayList<SurveyDto> surveyList = null;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Date getCreatedDateTime() {
return createdDateTime;
}
public void setCreatedDateTime(Date createdDateTime) {
this.createdDateTime = createdDateTime;
}
public Date getLastUpdateDateTime() {
return lastUpdateDateTime;
}
public void setLastUpdateDateTime(Date lastUpdateDateTime) {
this.lastUpdateDateTime = lastUpdateDateTime;
}
public void setSurveyList(ArrayList<SurveyDto> surveyList) {
this.surveyList = surveyList;
}
public ArrayList<SurveyDto> getSurveyList() {
return surveyList;
}
public void addSurvey(SurveyDto item) {
- if (surveyList == null)
+ if (surveyList == null){
surveyList = new ArrayList<SurveyDto>();
- else
+ }
surveyList.add(item);
}
}
| false | true | public void addSurvey(SurveyDto item) {
if (surveyList == null)
surveyList = new ArrayList<SurveyDto>();
else
surveyList.add(item);
}
| public void addSurvey(SurveyDto item) {
if (surveyList == null){
surveyList = new ArrayList<SurveyDto>();
}
surveyList.add(item);
}
|
diff --git a/AE-go_GameServer/src/com/aionemu/gameserver/model/gameobjects/player/Storage.java b/AE-go_GameServer/src/com/aionemu/gameserver/model/gameobjects/player/Storage.java
index f5155b44..14df31c6 100644
--- a/AE-go_GameServer/src/com/aionemu/gameserver/model/gameobjects/player/Storage.java
+++ b/AE-go_GameServer/src/com/aionemu/gameserver/model/gameobjects/player/Storage.java
@@ -1,453 +1,454 @@
/*
* This file is part of aion-unique <aion-unique.org>.
*
* aion-unique 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.
*
* aion-unique 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 aion-unique. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.model.gameobjects.player;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.PersistentState;
import com.aionemu.gameserver.model.items.ItemStorage;
import com.aionemu.gameserver.network.aion.serverpackets.SM_DELETE_ITEM;
import com.aionemu.gameserver.network.aion.serverpackets.SM_UPDATE_ITEM;
import com.aionemu.gameserver.network.aion.serverpackets.SM_UPDATE_WAREHOUSE_ITEM;
import com.aionemu.gameserver.utils.PacketSendUtility;
/**
* @author Avol
* modified by ATracer, kosyachok
*/
public class Storage
{
private Player owner;
protected ItemStorage storage;
private Item kinahItem;
protected int storageType;
protected Queue<Item> deletedItems = new ConcurrentLinkedQueue<Item>();
/**
* Can be of 2 types: UPDATED and UPDATE_REQUIRED
*/
private PersistentState persistentState = PersistentState.UPDATED;
/**
* Will be enhanced during development.
*/
public Storage(StorageType storageType)
{
switch(storageType)
{
case CUBE:
storage = new ItemStorage(108);
this.storageType = storageType.getId();
break;
case REGULAR_WAREHOUSE:
storage = new ItemStorage(104);
this.storageType = storageType.getId();
break;
case ACCOUNT_WAREHOUSE:
storage = new ItemStorage(16);
this.storageType = storageType.getId();
break;
case LEGION_WAREHOUSE:
storage = new ItemStorage(24); // TODO: FIND OUT WHAT MAX IS
this.storageType = storageType.getId();
break;
}
}
/**
* @param owner
*/
public Storage(Player owner, StorageType storageType)
{
this(storageType);
this.owner = owner;
}
/**
* @return the owner
*/
public Player getOwner()
{
return owner;
}
/**
* @param owner the owner to set
*/
public void setOwner(Player owner)
{
this.owner = owner;
}
/**
* @return the kinahItem
*/
public Item getKinahItem()
{
return kinahItem;
}
public int getStorageType()
{
return storageType;
}
/**
* Increasing kinah amount is persisted immediately
*
* @param amount
*/
public void increaseKinah(int amount)
{
kinahItem.increaseItemCount(amount);
if(storageType == StorageType.CUBE.getId())
PacketSendUtility.sendPacket(getOwner(), new SM_UPDATE_ITEM(kinahItem));
if (storageType == StorageType.ACCOUNT_WAREHOUSE.getId())
PacketSendUtility.sendPacket(getOwner(), new SM_UPDATE_WAREHOUSE_ITEM(kinahItem, storageType));
setPersistentState(PersistentState.UPDATE_REQUIRED);
}
/**
* Decreasing kinah amount is persisted immediately
*
* @param amount
*/
public boolean decreaseKinah(int amount)
{
boolean operationResult = kinahItem.decreaseItemCount(amount);
if(operationResult)
{
if(storageType == StorageType.CUBE.getId())
PacketSendUtility.sendPacket(getOwner(), new SM_UPDATE_ITEM(kinahItem));
if (storageType == StorageType.ACCOUNT_WAREHOUSE.getId())
PacketSendUtility.sendPacket(getOwner(), new SM_UPDATE_WAREHOUSE_ITEM(kinahItem, storageType));
}
setPersistentState(PersistentState.UPDATE_REQUIRED);
return operationResult;
}
/**
*
* This method should be called only for new items added to inventory (loading from DB)
* If item is equiped - will be put to equipment
* if item is unequiped - will be put to default bag for now
* Kinah is stored separately as it will be used frequently
*
* @param item
*/
public void onLoadHandler(Item item)
{
if(item.isEquipped())
{
owner.getEquipment().onLoadHandler(item);
}
else if(item.getItemTemplate().isKinah())
{
kinahItem = item;
}
else
{
storage.putToNextAvailableSlot(item);
}
}
/**
* Used to put item into storage cube at first avaialble slot (no check for existing item)
* During unequip/equip process persistImmediately should be false
*
* @param item
* @param persistImmediately
* @return Item
*/
public Item putToBag(Item item)
{
Item resultItem = storage.putToNextAvailableSlot(item);
if(resultItem != null)
{
resultItem.setItemLocation(storageType);
}
setPersistentState(PersistentState.UPDATE_REQUIRED);
return resultItem;
}
/**
* Removes item completely from inventory.
* Every remove operation is persisted immediately now
*
* @param item
*/
public void removeFromBag(Item item, boolean persist)
{
boolean operationResult = storage.removeItemFromStorage(item);
if(operationResult && persist)
{
item.setPersistentState(PersistentState.DELETED);
deletedItems.add(item);
setPersistentState(PersistentState.UPDATE_REQUIRED);
}
}
/**
* Used to reduce item count in bag or completely remove by ITEMID
* This method operates in iterative manner overl all items with specified ITEMID.
* Return value can be the following:
* - true - item removal was successfull
* - false - not enough amount of items to reduce
* or item is not present
*
* @param itemId
* @param count
* @return true or false
*/
public boolean removeFromBagByItemId(int itemId, int count)
{
if(count < 1)
return false;
List<Item> items = storage.getItemsFromStorageByItemId(itemId);
for(Item item : items)
{
count = decreaseItemCount(item, count);
if(count == 0)
break;
}
boolean result = count >=0;
if(result)
setPersistentState(PersistentState.UPDATE_REQUIRED);
return result;
}
/**
* Used to reduce item count in bag or completely remove by OBJECTID
* Return value can be the following:
* - true - item removal was successfull
* - false - not enough amount of items to reduce
* or item is not present
*
* @param itemObjId
* @param count
* @return true or false
*/
public boolean removeFromBagByObjectId(int itemObjId, int count)
{
if(count < 1)
return false;
Item item = storage.getItemFromStorageByItemObjId(itemObjId);
boolean result = decreaseItemCount(item, count) >= 0;
if(result)
setPersistentState(PersistentState.UPDATE_REQUIRED);
return result;
}
/**
* This method decreases inventory's item by count and sends
* appropriate packets to owner.
* Item will be saved in database after update or deleted if count=0 (and persist=true)
*
* @param count should be > 0
* @param item
* @return
*/
public int decreaseItemCount(Item item, int count)
{
- if(item.getItemCount() >= count)
+ int itemCount = item.getItemCount();
+ if(itemCount >= count)
{
item.decreaseItemCount(count);
count = 0;
}
else
- {
- item.decreaseItemCount(item.getItemCount());
- count -= item.getItemCount();
+ {
+ item.decreaseItemCount(itemCount);
+ count -= itemCount;
}
if(item.getItemCount() == 0)
{
storage.removeItemFromStorage(item);
PacketSendUtility.sendPacket(getOwner(), new SM_DELETE_ITEM(item.getObjectId()));
deletedItems.add(item);
}
else
PacketSendUtility.sendPacket(getOwner(), new SM_UPDATE_ITEM(item));
setPersistentState(PersistentState.UPDATE_REQUIRED);
return count;
}
/**
* Method primarily used when saving to DB
*
* @return List<Item>
*/
public List<Item> getAllItems()
{
List<Item> allItems = new ArrayList<Item>();
allItems.add(kinahItem);
allItems.addAll(storage.getStorageItems());
return allItems;
}
/**
* All deleted items with persistent state DELETED
*
* @return
*/
public Queue<Item> getDeletedItems()
{
return deletedItems;
}
/**
* Searches for item with specified itemId in equipment and cube
*
* @param itemId
* @return List<Item>
*/
public List<Item> getAllItemsByItemId(int itemId)
{
List<Item> allItemsByItemId = new ArrayList<Item>();
for (Item item : storage.getStorageItems())
{
if(item.getItemTemplate().getTemplateId() == itemId)
allItemsByItemId.add(item);
}
return allItemsByItemId;
}
public List<Item> getStorageItems()
{
return storage.getStorageItems();
}
/**
* Will look item in default item bag
*
* @param value
* @return Item
*/
public Item getItemByObjId(int value)
{
return storage.getItemFromStorageByItemObjId(value);
}
/**
*
* @param value
* @return List<Item>
*/
public List<Item> getItemsByItemId(int value)
{
return storage.getItemsFromStorageByItemId(value);
}
/**
*
* @param itemId
* @return number of items using search by itemid
*/
public int getItemCountByItemId(int itemId)
{
List<Item> items = getItemsByItemId(itemId);
int count = 0;
for(Item item : items)
{
count += item.getItemCount();
}
return count;
}
/**
* Checks whether default cube is full
*
* @return true or false
*/
public boolean isFull()
{
return storage.isFull();
}
/**
* Number of available slots of the underlying storage
*
* @return
*/
public int getNumberOfFreeSlots()
{
return storage.getNumberOfFreeSlots();
}
/**
* Sets the Inventory Limit from Cube Size
*
* @param Limit
*/
public void setLimit(int limit)
{
this.storage.setLimit(limit);
}
/**
* Limit value of the underlying storage
*
* @return
*/
public int getLimit()
{
return this.storage.getLimit();
}
/**
* @return the persistentState
*/
public PersistentState getPersistentState()
{
return persistentState;
}
/**
* @param persistentState the persistentState to set
*/
public void setPersistentState(PersistentState persistentState)
{
this.persistentState = persistentState;
}
/**
* @param item
* @param count
*/
public void increaseItemCount(Item item, int count)
{
item.increaseItemCount(count);
setPersistentState(PersistentState.UPDATE_REQUIRED);
}
}
| false | true | public int decreaseItemCount(Item item, int count)
{
if(item.getItemCount() >= count)
{
item.decreaseItemCount(count);
count = 0;
}
else
{
item.decreaseItemCount(item.getItemCount());
count -= item.getItemCount();
}
if(item.getItemCount() == 0)
{
storage.removeItemFromStorage(item);
PacketSendUtility.sendPacket(getOwner(), new SM_DELETE_ITEM(item.getObjectId()));
deletedItems.add(item);
}
else
PacketSendUtility.sendPacket(getOwner(), new SM_UPDATE_ITEM(item));
setPersistentState(PersistentState.UPDATE_REQUIRED);
return count;
}
| public int decreaseItemCount(Item item, int count)
{
int itemCount = item.getItemCount();
if(itemCount >= count)
{
item.decreaseItemCount(count);
count = 0;
}
else
{
item.decreaseItemCount(itemCount);
count -= itemCount;
}
if(item.getItemCount() == 0)
{
storage.removeItemFromStorage(item);
PacketSendUtility.sendPacket(getOwner(), new SM_DELETE_ITEM(item.getObjectId()));
deletedItems.add(item);
}
else
PacketSendUtility.sendPacket(getOwner(), new SM_UPDATE_ITEM(item));
setPersistentState(PersistentState.UPDATE_REQUIRED);
return count;
}
|
diff --git a/plugins/maven-site-scm-publish-plugin/src/main/java/org/apache/maven/plugins/scmpublish/ScmPublishPublishMojo.java b/plugins/maven-site-scm-publish-plugin/src/main/java/org/apache/maven/plugins/scmpublish/ScmPublishPublishMojo.java
index cd379c414..75ea8e334 100644
--- a/plugins/maven-site-scm-publish-plugin/src/main/java/org/apache/maven/plugins/scmpublish/ScmPublishPublishMojo.java
+++ b/plugins/maven-site-scm-publish-plugin/src/main/java/org/apache/maven/plugins/scmpublish/ScmPublishPublishMojo.java
@@ -1,342 +1,342 @@
package org.apache.maven.plugins.scmpublish;
/*
* 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 java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmFileSet;
import org.apache.maven.scm.command.add.AddScmResult;
import org.apache.maven.scm.command.checkin.CheckInScmResult;
import org.apache.maven.scm.command.remove.RemoveScmResult;
import org.apache.maven.shared.release.ReleaseExecutionException;
import org.apache.maven.shared.release.scm.ReleaseScmRepositoryException;
/**
* Compare the list of files now on disk to the original inventory, then fire off scm adds and deletes as needed.
*
* @goal publish
* @phase post-site
* @aggregate
*/
public class ScmPublishPublishMojo
extends AbstractScmPublishMojo
{
/**
* Display list of added, deleted, and changed files, but do not do any actual SCM operations.
*
* @parameter expression="${scmpublish.dryRun}"
*/
private boolean dryRun;
/**
* Run add and delete commands, but leave the actually checkin for the user to run manually.
*
* @parameter expression="${scmpublish.skipCheckin}"
*/
private boolean skipCheckin;
/**
* SCM log/checkin comment for this publication.
* @parameter expression="${scmpublish.checkinComment}"
*/
private String checkinComment;
/**
* Filename extensions of files which need new line normalization.
*/
private final static String[] NORMALIZE_EXTENSIONS = { "html", "css", "js" };
private File relativize( File base, File file )
{
return new File( base.toURI().relativize( file.toURI() ).getPath() );
}
private boolean requireNormalizeNewlines( File f )
throws IOException
{
return FilenameUtils.isExtension( f.getName(), NORMALIZE_EXTENSIONS );
}
private void normalizeNewlines( File f )
throws IOException
{
File tmpFile = null;
BufferedReader in = null;
PrintWriter out = null;
try
{
tmpFile = File.createTempFile( "maven-site-scm-plugin-", ".tmp" );
FileUtils.copyFile( f, tmpFile );
in = new BufferedReader( new InputStreamReader( new FileInputStream( tmpFile ), siteOutputEncoding ) );
out = new PrintWriter( new OutputStreamWriter( new FileOutputStream( f ), siteOutputEncoding ) );
String line;
while ( ( line = in.readLine() ) != null )
{
if ( in.ready() )
{
out.println( line );
}
else
{
out.print( line );
}
}
}
finally
{
IOUtils.closeQuietly( out );
IOUtils.closeQuietly( in );
FileUtils.deleteQuietly( tmpFile );
}
}
private void normalizeNewLines( Set<File> files )
throws MojoFailureException
{
for ( File f : files )
{
try
{
if ( requireNormalizeNewlines( f ) )
{
normalizeNewlines( f );
}
}
catch ( IOException e )
{
throw new MojoFailureException( "Failed to normalize newlines in " + f.getAbsolutePath(), e );
}
}
}
/*
* (non-Javadoc)
* @see org.apache.maven.plugin.Mojo#execute()
*/
public void execute()
throws MojoExecutionException, MojoFailureException
{
if ( siteOutputEncoding == null )
{
getLog().warn( "No output encoding, defaulting to UTF-8." );
siteOutputEncoding = "utf-8";
}
// read in the list left behind by prepare; fail if it's not there.
readInventory();
// setup the scm plugin with help from release plugin utilities
try
{
setupScm();
}
catch ( ReleaseScmRepositoryException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
catch ( ReleaseExecutionException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
// what files are in stock now?
Set<File> added = new HashSet<File>();
Collection<File> newInventory = FileUtils.listFiles( checkoutDirectory, new DotFilter(), new DotFilter() );
added.addAll( newInventory );
Set<File> deleted = new HashSet<File>();
deleted.addAll( inventory );
deleted.removeAll( added ); // old - new = deleted. (Added is the complete new inventory at this point.)
added.removeAll( inventory ); // new - old = added.
Set<File> updated = new HashSet<File>();
updated.addAll( newInventory );
updated.retainAll( inventory ); // set intersection
- logInfo( "Publish files: %d addition(s), %d update(s), %d delete(s)", added.size(), deleted.size(),
- updated.size() );
+ logInfo( "Publish files: %d addition(s), %d update(s), %d delete(s)", added.size(), updated.size(),
+ deleted.size() );
if ( dryRun )
{
for ( File addedFile : added )
{
logInfo( "Added %s", addedFile.getAbsolutePath() );
}
for ( File deletedFile : deleted )
{
logInfo( "Deleted %s", deletedFile.getAbsolutePath() );
}
for ( File updatedFile : updated )
{
logInfo( "Updated %s", updatedFile.getAbsolutePath() );
}
return;
}
if ( !added.isEmpty() )
{
normalizeNewLines( added );
addFiles( added );
}
if ( !deleted.isEmpty() )
{
deleteFiles( deleted );
}
normalizeNewLines( updated );
if ( !skipCheckin )
{
checkinFiles();
}
}
private void checkinFiles()
throws MojoExecutionException
{
if ( checkinComment == null )
{
checkinComment = "Site checkin for project " + project.getName();
}
ScmFileSet updatedFileSet = new ScmFileSet( checkoutDirectory );
try
{
CheckInScmResult checkinResult = scmProvider.checkIn( scmRepository, updatedFileSet, checkinComment );
if ( !checkinResult.isSuccess() )
{
logError( "checkin operation failed: %s",
checkinResult.getProviderMessage() + " " + checkinResult.getCommandOutput() );
throw new MojoExecutionException( "Failed to checkin files: " + checkinResult.getProviderMessage()
+ " " + checkinResult.getCommandOutput() );
}
}
catch ( ScmException e )
{
throw new MojoExecutionException( "Failed to perform checkin SCM", e );
}
}
private void deleteFiles( Set<File> deleted )
throws MojoExecutionException
{
List<File> deletedList = new ArrayList<File>();
for ( File f : deleted )
{
deletedList.add( relativize( checkoutDirectory, f ) );
}
ScmFileSet deletedFileSet = new ScmFileSet( checkoutDirectory, deletedList );
try
{
RemoveScmResult deleteResult =
scmProvider.remove( scmRepository, deletedFileSet, "Deleting obsolete site files." );
if ( !deleteResult.isSuccess() )
{
logError( "delete operation failed: %s",
deleteResult.getProviderMessage() + " " + deleteResult.getCommandOutput() );
throw new MojoExecutionException( "Failed to delete files: " + deleteResult.getProviderMessage()
+ " " + deleteResult.getCommandOutput() );
}
}
catch ( ScmException e )
{
throw new MojoExecutionException( "Failed to delete removed files to SCM", e );
}
}
private void addFiles( Set<File> added )
throws MojoFailureException, MojoExecutionException
{
List<File> addedList = new ArrayList<File>();
Set<File> createdDirs = new HashSet<File>();
Set<File> dirsToAdd = new TreeSet<File>();
createdDirs.add( relativize( checkoutDirectory, checkoutDirectory ) );
for ( File f : added )
{
for ( File dir = f.getParentFile(); !dir.equals( checkoutDirectory ); dir = dir.getParentFile() )
{
File relativized = relativize( checkoutDirectory, dir );
// we do the best we can with the directories
if ( !createdDirs.add( relativized ) )
{
dirsToAdd.add( relativized );
}
}
addedList.add( relativize( checkoutDirectory, f ) );
}
for ( File relativized : dirsToAdd )
{
try
{
ScmFileSet fileSet = new ScmFileSet( checkoutDirectory , relativized );
AddScmResult addDirResult = scmProvider.add( scmRepository, fileSet, "Adding directory" );
if ( !addDirResult.isSuccess() )
{
getLog().debug( " Error adding directory " + relativized + " " + addDirResult.getCommandOutput() );
}
}
catch ( ScmException e )
{
//
}
}
ScmFileSet addedFileSet = new ScmFileSet( checkoutDirectory, addedList );
try
{
AddScmResult addResult = scmProvider.add( scmRepository, addedFileSet, "Adding new site files." );
if ( !addResult.isSuccess() )
{
logError( "add operation failed: %s",
addResult.getProviderMessage() + " " + addResult.getCommandOutput() );
throw new MojoExecutionException( "Failed to add new files: " + addResult.getProviderMessage()
+ " " + addResult.getCommandOutput() );
}
}
catch ( ScmException e )
{
throw new MojoExecutionException( "Failed to add new files to SCM", e );
}
}
}
| true | true | public void execute()
throws MojoExecutionException, MojoFailureException
{
if ( siteOutputEncoding == null )
{
getLog().warn( "No output encoding, defaulting to UTF-8." );
siteOutputEncoding = "utf-8";
}
// read in the list left behind by prepare; fail if it's not there.
readInventory();
// setup the scm plugin with help from release plugin utilities
try
{
setupScm();
}
catch ( ReleaseScmRepositoryException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
catch ( ReleaseExecutionException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
// what files are in stock now?
Set<File> added = new HashSet<File>();
Collection<File> newInventory = FileUtils.listFiles( checkoutDirectory, new DotFilter(), new DotFilter() );
added.addAll( newInventory );
Set<File> deleted = new HashSet<File>();
deleted.addAll( inventory );
deleted.removeAll( added ); // old - new = deleted. (Added is the complete new inventory at this point.)
added.removeAll( inventory ); // new - old = added.
Set<File> updated = new HashSet<File>();
updated.addAll( newInventory );
updated.retainAll( inventory ); // set intersection
logInfo( "Publish files: %d addition(s), %d update(s), %d delete(s)", added.size(), deleted.size(),
updated.size() );
if ( dryRun )
{
for ( File addedFile : added )
{
logInfo( "Added %s", addedFile.getAbsolutePath() );
}
for ( File deletedFile : deleted )
{
logInfo( "Deleted %s", deletedFile.getAbsolutePath() );
}
for ( File updatedFile : updated )
{
logInfo( "Updated %s", updatedFile.getAbsolutePath() );
}
return;
}
if ( !added.isEmpty() )
{
normalizeNewLines( added );
addFiles( added );
}
if ( !deleted.isEmpty() )
{
deleteFiles( deleted );
}
normalizeNewLines( updated );
if ( !skipCheckin )
{
checkinFiles();
}
}
| public void execute()
throws MojoExecutionException, MojoFailureException
{
if ( siteOutputEncoding == null )
{
getLog().warn( "No output encoding, defaulting to UTF-8." );
siteOutputEncoding = "utf-8";
}
// read in the list left behind by prepare; fail if it's not there.
readInventory();
// setup the scm plugin with help from release plugin utilities
try
{
setupScm();
}
catch ( ReleaseScmRepositoryException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
catch ( ReleaseExecutionException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
// what files are in stock now?
Set<File> added = new HashSet<File>();
Collection<File> newInventory = FileUtils.listFiles( checkoutDirectory, new DotFilter(), new DotFilter() );
added.addAll( newInventory );
Set<File> deleted = new HashSet<File>();
deleted.addAll( inventory );
deleted.removeAll( added ); // old - new = deleted. (Added is the complete new inventory at this point.)
added.removeAll( inventory ); // new - old = added.
Set<File> updated = new HashSet<File>();
updated.addAll( newInventory );
updated.retainAll( inventory ); // set intersection
logInfo( "Publish files: %d addition(s), %d update(s), %d delete(s)", added.size(), updated.size(),
deleted.size() );
if ( dryRun )
{
for ( File addedFile : added )
{
logInfo( "Added %s", addedFile.getAbsolutePath() );
}
for ( File deletedFile : deleted )
{
logInfo( "Deleted %s", deletedFile.getAbsolutePath() );
}
for ( File updatedFile : updated )
{
logInfo( "Updated %s", updatedFile.getAbsolutePath() );
}
return;
}
if ( !added.isEmpty() )
{
normalizeNewLines( added );
addFiles( added );
}
if ( !deleted.isEmpty() )
{
deleteFiles( deleted );
}
normalizeNewLines( updated );
if ( !skipCheckin )
{
checkinFiles();
}
}
|
diff --git a/CloudEmoji/src/main/java/org/ktachibana/cloudemoji/MainActivity.java b/CloudEmoji/src/main/java/org/ktachibana/cloudemoji/MainActivity.java
index 5b99dde..4f633bb 100644
--- a/CloudEmoji/src/main/java/org/ktachibana/cloudemoji/MainActivity.java
+++ b/CloudEmoji/src/main/java/org/ktachibana/cloudemoji/MainActivity.java
@@ -1,580 +1,578 @@
package org.ktachibana.cloudemoji;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.*;
import android.widget.*;
import org.apache.commons.io.IOUtils;
import org.ktachibana.cloudemoji.RepoXmlParser.Emoji;
import org.xmlpull.v1.XmlPullParserException;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity implements
SharedPreferences.OnSharedPreferenceChangeListener,
DoubleItemListFragment.OnRefreshStartedListener,
OnExceptionListener,
OnCopyToClipBoardListener {
// Constants
private static final int PERSISTENT_NOTIFICATION_ID = 0;
private static final String XML_FILE_NAME = "emoji.xml";
// Preferences
private SharedPreferences preferences;
private String notificationVisibility;
private String url;
// UI components
private DrawerLayout drawerLayout;
private ListView leftDrawer;
private ActionBarDrawerToggle toggle;
private boolean isDrawerStatic;
private PullToRefreshLayout refreshingPullToRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// Initializations
setupPreferences();
setupUI();
switchNotificationState();
firstTimeCheck();
// Fill drawer
fillNavigationDrawer();
// If not coming from previous sessions
if (savedInstanceState == null) {
updateMainContainer(new MyMenuItem(getString(R.string.my_fav), MyMenuItem.FAV_TYPE));
}
}
private void setupPreferences() {
// Set up preferences
preferences = PreferenceManager.getDefaultSharedPreferences(this);
notificationVisibility = preferences.getString(SettingsActivity.PREF_NOTIFICATION_VISIBILITY, "both");
url = preferences.getString(SettingsActivity.PREF_TEST_MY_REPO, getString(R.string.default_url));
}
private void setupUI() {
// Find views
FrameLayout mainContainer = (FrameLayout) findViewById(R.id.mainContainer);
leftDrawer = (ListView) findViewById(R.id.leftDrawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Determine whether the drawer is static
int mainContainerLeftMargin = ((ViewGroup.MarginLayoutParams) mainContainer.getLayoutParams()).leftMargin;
int drawerSize = leftDrawer.getLayoutParams().width;
- Log.e("233", "mainContainerLeftMargin is " + Integer.toString(mainContainerLeftMargin));
- Log.e("233", "drawerSize is " + drawerSize);
- isDrawerStatic = mainContainerLeftMargin == drawerSize;
+ isDrawerStatic = (mainContainerLeftMargin == drawerSize);
// Set up if drawer is locked
if (isDrawerStatic) {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN, leftDrawer);
drawerLayout.setScrimColor(Color.TRANSPARENT);
}
// Set up toggle
toggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_navigation_drawer, R.string.app_name, R.string.app_name) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(R.string.app_name);
}
};
drawerLayout.setDrawerListener(toggle);
if (!isDrawerStatic) {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
/**
* Build notification with a given priority
*
* @param priority priority from Notification.priority
* @return a Notification object
*/
private Notification buildNotification(int priority) {
String title = getString(R.string.app_name);
String text = getString(R.string.touch_to_launch);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
return new NotificationCompat.Builder(this)
.setContentTitle(title) // Title
.setContentText(text) // Text
.setSmallIcon(R.drawable.ic_notification) // Icon
.setContentIntent(pIntent) // Intent to launch this app
.setWhen(0) // No time to display
.setPriority(priority) // Given priority
.build();
}
private void firstTimeCheck() {
boolean hasRunBefore = preferences.getBoolean(SettingsActivity.PREF_HAS_RUN_BEFORE, false);
// Hasn't run before
if (!hasRunBefore) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(SettingsActivity.PREF_HAS_RUN_BEFORE, true);
editor.commit();
drawerLayout.openDrawer(leftDrawer);
}
}
/**
* Download XML file from user's preferred URL and replace the local one
*/
private void update() {
new UpdateRepoTask().execute(url);
}
/**
* AsyncTask that fetches an XML file given a URL and replace the local one
* This module uses Apache Commons IO from http://commons.apache.org/proper/commons-io/
*/
private class UpdateRepoTask extends AsyncTask<String, Void, Void> {
private List<Exception> taskExceptions;
@Override
protected void onPreExecute() {
taskExceptions = new ArrayList<Exception>();
}
@Override
protected Void doInBackground(String... stringUrl) {
HttpURLConnection conn = null;
Reader reader = null;
OutputStream fileOut = null;
try {
// Establish connection
URL url = new URL(stringUrl[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(15000);
conn.setReadTimeout(10000);
conn.setRequestMethod("GET");
conn.connect();
// Over-write existing file
reader = new InputStreamReader(conn.getInputStream());
fileOut = openFileOutput(XML_FILE_NAME, Context.MODE_PRIVATE);
IOUtils.copy(reader, fileOut);
} catch (IOException e) {
taskExceptions.add(e);
} catch (Exception e) {
taskExceptions.add(e);
} finally {
IOUtils.close(conn);
IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(fileOut);
}
return null;
}
@Override
protected void onPostExecute(Void v) {
// Stop the refreshing pull to refresh layout
if (refreshingPullToRefreshLayout != null) {
refreshingPullToRefreshLayout.setRefreshComplete();
}
// If update finishes without exceptions
if (taskExceptions.isEmpty()) {
fillNavigationDrawer();
drawerLayout.openDrawer(leftDrawer);
Toast.makeText(MainActivity.this, getString(R.string.updated), Toast.LENGTH_SHORT).show();
} else {
promptException(taskExceptions.get(0));
}
}
}
/**
* Read emoji from a given file and return it
* Handle exceptions by its own so that XmlPullParserException is not covered by IOException
* This module uses Apache Commons IO from http://commons.apache.org/proper/commons-io/
*
* @param file File object
* @return Emoji object
*/
private Emoji readEmoji(File file) {
FileInputStream fileIn = null;
Reader reader = null;
Emoji emoji = null;
try {
fileIn = new FileInputStream(file);
reader = new InputStreamReader(fileIn);
emoji = new RepoXmlParser().parse(reader);
} catch (FileNotFoundException e) {
promptException(e);
} catch (XmlPullParserException e) {
promptException(e);
} catch (IOException e) {
promptException(e);
} finally {
IOUtils.closeQuietly(fileIn);
IOUtils.closeQuietly(reader);
}
return emoji;
}
/**
* Fill the navigation drawer with categories read from local XML file
*/
private void fillNavigationDrawer() {
// Read file from local storage
File file = new File(getFilesDir(), XML_FILE_NAME);
if (!file.exists()) {
update();
}
Emoji emoji = readEmoji(file);
if (emoji != null) {
// Fill leftDrawer
leftDrawer.setAdapter(new SectionedMenuAdapter(emoji));
leftDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyMenuItem menuItem = (MyMenuItem) parent.getAdapter().getItem(position);
updateMainContainer(menuItem);
if (!isDrawerStatic) {
drawerLayout.closeDrawers();
}
}
});
}
}
/**
*
*/
/**
* Replace the main container with a fragment and change actionbar title
*
* @param menuItem Menu item being pressed on
*/
private void updateMainContainer(MyMenuItem menuItem) {
int type = menuItem.getType();
if (type != MyMenuItem.SECTION_HEADER_TYPE) {
getSupportActionBar().setTitle(menuItem.getItemName());
FragmentManager fragmentManager = getSupportFragmentManager();
if (type == MyMenuItem.FAV_TYPE) {
fragmentManager.beginTransaction().replace(R.id.mainContainer, new FavFragment()).commit();
} else if (type == MyMenuItem.CATEGORY_TYPE) {
fragmentManager.beginTransaction().replace(R.id.mainContainer, DoubleItemListFragment.newInstance(menuItem.getCategory())).commit();
}
}
}
/**
* Switch notification state to according to current user preference
*/
private void switchNotificationState() {
// Cancel current notification
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(PERSISTENT_NOTIFICATION_ID);
if (notificationVisibility.equals("no")) {
notificationManager.cancel(PERSISTENT_NOTIFICATION_ID);
} else if (notificationVisibility.equals("panel")) {
Notification notification = buildNotification(Notification.PRIORITY_MIN);
notification.flags = Notification.FLAG_NO_CLEAR;
notificationManager.notify(PERSISTENT_NOTIFICATION_ID, notification);
} else if (notificationVisibility.equals("both")) {
Notification notification = buildNotification(Notification.PRIORITY_DEFAULT);
notification.flags = Notification.FLAG_NO_CLEAR;
notificationManager.notify(PERSISTENT_NOTIFICATION_ID, notification);
}
}
/**
* Show a toast given a type of exception
*
* @param e exception
*/
private void promptException(Exception e) {
String prompt;
if (e instanceof XmlPullParserException) {
prompt = getString(R.string.wrong_xml);
} else if (e instanceof FileNotFoundException) {
prompt = getString(R.string.file_not_found);
} else if (e instanceof IOException) {
prompt = getString(R.string.bad_conn);
} else {
prompt = getString(R.string.fail);
}
Toast.makeText(MainActivity.this, prompt, Toast.LENGTH_SHORT).show();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences,
String key) {
if (key.equals(SettingsActivity.PREF_NOTIFICATION_VISIBILITY)) {
notificationVisibility = preferences.getString(key, "both");
switchNotificationState();
} else if (key.equals(SettingsActivity.PREF_TEST_MY_REPO)) {
url = preferences.getString(key, getString(R.string.default_url));
}
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
preferences.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
preferences.registerOnSharedPreferenceChangeListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu
// Adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
if (toggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_refresh: {
update();
return true;
}
case R.id.action_settings: {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
case R.id.action_exit: {
finish();
}
default: {
return super.onOptionsItemSelected(item);
}
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
toggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
/**
* Implements from OnExceptionListener
*
* @param e Exception handled
*/
public void onException(Exception e) {
promptException(e);
}
/**
* Implements from DoubleItemListFragment.OnRefreshStartedListener
*
* @param layout Layout being pulled
*/
public void onRefreshStarted(PullToRefreshLayout layout) {
refreshingPullToRefreshLayout = layout;
update();
}
/**
* Implements from OnCopyToClipBoardListener
*
* @param copied String copied
*/
public void copyToClipBoard(String copied) {
// Below 3.0 support
int SDK = Build.VERSION.SDK_INT;
if (SDK < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(copied);
}
// Above 3.0
else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("emoji", copied);
clipboard.setPrimaryClip(clip);
}
Toast.makeText(MainActivity.this, getString(R.string.copied), Toast.LENGTH_SHORT).show();
boolean isCloseAfterCopy = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).getBoolean(SettingsActivity.PREF_CLOSE_AFTER_COPY, true);
if (isCloseAfterCopy) {
finish();
}
}
/**
* A class for a menu item in menu drawer
* Holding it's item name, its corresponding type and Category it's holding if the type is CATEGORY
*/
private class MyMenuItem {
public static final int SECTION_HEADER_TYPE = 0;
public static final int CATEGORY_TYPE = 1;
public static final int FAV_TYPE = 2;
private String itemName;
private int type;
private RepoXmlParser.Category category;
public MyMenuItem(String itemName, int type) {
this.itemName = itemName;
this.type = type;
}
public MyMenuItem(String itemName, int type, RepoXmlParser.Category category) {
this.itemName = itemName;
this.type = type;
this.category = category;
}
public String getItemName() {
return itemName;
}
public int getType() {
return type;
}
public RepoXmlParser.Category getCategory() {
return category;
}
}
private class SectionedMenuAdapter implements ListAdapter {
private List<MyMenuItem> menuItemMap;
public SectionedMenuAdapter(Emoji data) {
menuItemMap = new ArrayList<MyMenuItem>();
// Put section header for "local"
menuItemMap.add(new MyMenuItem(getResources().getString(R.string.local), MyMenuItem.SECTION_HEADER_TYPE));
// Put my fav
menuItemMap.add(new MyMenuItem(getResources().getString(R.string.my_fav), MyMenuItem.FAV_TYPE));
// Put section header for "repository"
menuItemMap.add(new MyMenuItem(getResources().getString(R.string.repositories), MyMenuItem.SECTION_HEADER_TYPE));
// Put all other categories
for (RepoXmlParser.Category category : data.categories) {
menuItemMap.add(new MyMenuItem(category.name, MyMenuItem.CATEGORY_TYPE, category));
}
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public boolean isEnabled(int position) {
return menuItemMap.get(position).getType() != MyMenuItem.SECTION_HEADER_TYPE;
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
@Override
public int getCount() {
return menuItemMap.size();
}
@Override
public Object getItem(int position) {
return menuItemMap.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TextView textView = (TextView) convertView;
// Determine if the menu item is section header or list item
MyMenuItem menuItem = menuItemMap.get(position);
// If it is a section header
if (menuItem.getType() == MyMenuItem.SECTION_HEADER_TYPE) {
if (textView == null) {
textView = (TextView) inflater.inflate(R.layout.text_separator_style, parent, false);
}
String sectionName = menuItem.getItemName();
textView.setText(sectionName);
}
// Else it is a list item
else {
if (textView == null) {
textView = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
}
String itemName = menuItem.getItemName();
textView.setText(itemName);
}
return textView;
}
@Override
public int getItemViewType(int position) {
return (menuItemMap.get(position).getType() == MyMenuItem.SECTION_HEADER_TYPE) ? 0 : 1;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public boolean isEmpty() {
return menuItemMap.isEmpty();
}
}
}
| true | true | private void setupUI() {
// Find views
FrameLayout mainContainer = (FrameLayout) findViewById(R.id.mainContainer);
leftDrawer = (ListView) findViewById(R.id.leftDrawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Determine whether the drawer is static
int mainContainerLeftMargin = ((ViewGroup.MarginLayoutParams) mainContainer.getLayoutParams()).leftMargin;
int drawerSize = leftDrawer.getLayoutParams().width;
Log.e("233", "mainContainerLeftMargin is " + Integer.toString(mainContainerLeftMargin));
Log.e("233", "drawerSize is " + drawerSize);
isDrawerStatic = mainContainerLeftMargin == drawerSize;
// Set up if drawer is locked
if (isDrawerStatic) {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN, leftDrawer);
drawerLayout.setScrimColor(Color.TRANSPARENT);
}
// Set up toggle
toggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_navigation_drawer, R.string.app_name, R.string.app_name) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(R.string.app_name);
}
};
drawerLayout.setDrawerListener(toggle);
if (!isDrawerStatic) {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
| private void setupUI() {
// Find views
FrameLayout mainContainer = (FrameLayout) findViewById(R.id.mainContainer);
leftDrawer = (ListView) findViewById(R.id.leftDrawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Determine whether the drawer is static
int mainContainerLeftMargin = ((ViewGroup.MarginLayoutParams) mainContainer.getLayoutParams()).leftMargin;
int drawerSize = leftDrawer.getLayoutParams().width;
isDrawerStatic = (mainContainerLeftMargin == drawerSize);
// Set up if drawer is locked
if (isDrawerStatic) {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN, leftDrawer);
drawerLayout.setScrimColor(Color.TRANSPARENT);
}
// Set up toggle
toggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_navigation_drawer, R.string.app_name, R.string.app_name) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(R.string.app_name);
}
};
drawerLayout.setDrawerListener(toggle);
if (!isDrawerStatic) {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
|
diff --git a/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/PtuSettingsView.java b/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/PtuSettingsView.java
index 0385a85f..656cb045 100644
--- a/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/PtuSettingsView.java
+++ b/apvs/src/main/java/ch/cern/atlas/apvs/client/ui/PtuSettingsView.java
@@ -1,286 +1,286 @@
package ch.cern.atlas.apvs.client.ui;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import ch.cern.atlas.apvs.client.ClientFactory;
import ch.cern.atlas.apvs.client.event.PtuSettingsChangedEvent;
import ch.cern.atlas.apvs.client.settings.PtuSettings;
import ch.cern.atlas.apvs.client.widget.ActiveCheckboxCell;
import ch.cern.atlas.apvs.client.widget.DynamicSelectionCell;
import ch.cern.atlas.apvs.client.widget.StringList;
import ch.cern.atlas.apvs.client.widget.TextInputSizeCell;
import ch.cern.atlas.apvs.client.widget.VerticalFlowPanel;
import ch.cern.atlas.apvs.dosimeter.shared.DosimeterPtuChangedEvent;
import ch.cern.atlas.apvs.dosimeter.shared.DosimeterSerialNumbersChangedEvent;
import ch.cern.atlas.apvs.eventbus.shared.RemoteEventBus;
import ch.cern.atlas.apvs.ptu.shared.PtuIdsChangedEvent;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.view.client.ListDataProvider;
import com.google.web.bindery.event.shared.EventBus;
/**
* Shows a list of PTU settings which are alive. A list of ever alive PTU
* settings is persisted.
*
* @author duns
*
*/
public class PtuSettingsView extends VerticalFlowPanel {
private ListDataProvider<String> dataProvider = new ListDataProvider<String>();
private CellTable<String> table = new CellTable<String>();
private ListHandler<String> columnSortHandler;
protected PtuSettings settings = new PtuSettings();
protected List<Integer> dosimeterSerialNumbers = new ArrayList<Integer>();
protected List<String> activePtuIds = new ArrayList<String>();
public PtuSettingsView(ClientFactory clientFactory, Arguments args) {
final RemoteEventBus eventBus = clientFactory.getRemoteEventBus();
add(table);
// ACTIVE
Column<String, Boolean> active = new Column<String, Boolean>(
new ActiveCheckboxCell()) {
@Override
public Boolean getValue(String object) {
return activePtuIds.contains(object);
}
};
active.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
active.setSortable(true);
table.addColumn(active, "Active");
// ENABLED
Column<String, Boolean> enabled = new Column<String, Boolean>(
new CheckboxCell()) {
@Override
public Boolean getValue(String object) {
return settings.isEnabled(object);
}
};
enabled.setFieldUpdater(new FieldUpdater<String, Boolean>() {
@Override
public void update(int index, String object, Boolean value) {
settings.setEnabled(object, value);
fireSettingsChangedEvent(eventBus, settings);
}
});
enabled.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
enabled.setSortable(true);
table.addColumn(enabled, "Enabled");
// PTU ID
Column<String, String> ptuId = new Column<String, String>(
new TextCell()) {
@Override
public String getValue(String object) {
return object;
}
};
- ptuId.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
+ ptuId.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
ptuId.setSortable(true);
table.addColumn(ptuId, "PTU ID");
// NAME
Column<String, String> name = new Column<String, String>(
new TextInputSizeCell(30)) {
@Override
public String getValue(String object) {
return settings.getName(object);
}
};
name.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
settings.setName(object, value);
fireSettingsChangedEvent(eventBus, settings);
}
});
name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
name.setSortable(true);
table.addColumn(name, "Name");
// DOSIMETER
Column<String, String> dosimeter = new Column<String, String>(
new DynamicSelectionCell(new StringList<Integer>(
dosimeterSerialNumbers))) {
@Override
public String getValue(String object) {
return settings.getDosimeterSerialNumber(object).toString();
}
};
dosimeter.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
settings.setDosimeterSerialNumber(object,
Integer.parseInt(value));
fireSettingsChangedEvent(eventBus, settings);
}
});
dosimeter.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
dosimeter.setSortable(true);
table.addColumn(dosimeter, "Dosimeter #");
// HELMET URL
Column<String, String> helmetUrl = new Column<String, String>(
new TextInputSizeCell(50)) {
@Override
public String getValue(String object) {
return settings.getCameraUrl(object, CameraView.HELMET);
}
};
helmetUrl.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
settings.setCameraUrl(object, CameraView.HELMET, value);
fireSettingsChangedEvent(eventBus, settings);
}
});
helmetUrl.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
helmetUrl.setSortable(true);
table.addColumn(helmetUrl, "Helmet Camera URL");
// HAND URL
Column<String, String> handUrl = new Column<String, String>(
new TextInputSizeCell(50)) {
@Override
public String getValue(String object) {
return settings.getCameraUrl(object, CameraView.HAND);
}
};
handUrl.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
settings.setCameraUrl(object, CameraView.HAND, value);
fireSettingsChangedEvent(eventBus, settings);
}
});
handUrl.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
handUrl.setSortable(true);
table.addColumn(handUrl, "Hand Camera URL");
dataProvider.addDataDisplay(table);
dataProvider.setList(new ArrayList<String>());
// SORTING
columnSortHandler = new ListHandler<String>(dataProvider.getList());
columnSortHandler.setComparator(ptuId, new Comparator<String>() {
public int compare(String o1, String o2) {
return o1 != null ? o1.compareTo(o2) : -1;
}
});
columnSortHandler.setComparator(active, new Comparator<String>() {
public int compare(String o1, String o2) {
return activePtuIds.contains(o1) ? activePtuIds.contains(o2) ? 0 : 1 : -1;
}
});
columnSortHandler.setComparator(enabled, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.isEnabled(o1).compareTo(settings.isEnabled(o2));
}
});
columnSortHandler.setComparator(name, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.getName(o1).compareTo(settings.getName(o2));
}
});
columnSortHandler.setComparator(dosimeter, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.getDosimeterSerialNumber(o1).compareTo(
settings.getDosimeterSerialNumber(o2));
}
});
columnSortHandler.setComparator(helmetUrl, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.getCameraUrl(o1, CameraView.HELMET).compareTo(
settings.getCameraUrl(o2, CameraView.HELMET));
}
});
columnSortHandler.setComparator(handUrl, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.getCameraUrl(o1, CameraView.HAND).compareTo(
settings.getCameraUrl(o2, CameraView.HAND));
}
});
table.addColumnSortHandler(columnSortHandler);
table.getColumnSortList().push(ptuId);
PtuSettingsChangedEvent.subscribe(eventBus,
new PtuSettingsChangedEvent.Handler() {
@Override
public void onPtuSettingsChanged(
PtuSettingsChangedEvent event) {
System.err.println("PTU Settings changed");
settings = event.getPtuSettings();
dataProvider.getList().clear();
dataProvider.getList().addAll(settings.getPtuIds());
update();
}
});
PtuIdsChangedEvent.subscribe(eventBus,
new PtuIdsChangedEvent.Handler() {
@Override
public void onPtuIdsChanged(PtuIdsChangedEvent event) {
System.err.println("PTU IDS changed");
activePtuIds = event.getPtuIds();
update();
}
});
DosimeterSerialNumbersChangedEvent.subscribe(eventBus,
new DosimeterSerialNumbersChangedEvent.Handler() {
@Override
public void onDosimeterSerialNumbersChanged(
DosimeterSerialNumbersChangedEvent event) {
dosimeterSerialNumbers.clear();
dosimeterSerialNumbers.addAll(event
.getDosimeterSerialNumbers());
System.err.println("DOSI changed "
+ dosimeterSerialNumbers.size());
// FIXME, allow for setting not available as DOSI #
update();
}
});
update();
}
private void update() {
// Resort the table
ColumnSortEvent.fire(table, table.getColumnSortList());
table.redraw();
}
private void fireSettingsChangedEvent(EventBus eventBus,
PtuSettings settings) {
((RemoteEventBus)eventBus).fireEvent(new PtuSettingsChangedEvent(settings));
((RemoteEventBus)eventBus).fireEvent(new DosimeterPtuChangedEvent(settings
.getDosimeterToPtuMap()));
}
}
| true | true | public PtuSettingsView(ClientFactory clientFactory, Arguments args) {
final RemoteEventBus eventBus = clientFactory.getRemoteEventBus();
add(table);
// ACTIVE
Column<String, Boolean> active = new Column<String, Boolean>(
new ActiveCheckboxCell()) {
@Override
public Boolean getValue(String object) {
return activePtuIds.contains(object);
}
};
active.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
active.setSortable(true);
table.addColumn(active, "Active");
// ENABLED
Column<String, Boolean> enabled = new Column<String, Boolean>(
new CheckboxCell()) {
@Override
public Boolean getValue(String object) {
return settings.isEnabled(object);
}
};
enabled.setFieldUpdater(new FieldUpdater<String, Boolean>() {
@Override
public void update(int index, String object, Boolean value) {
settings.setEnabled(object, value);
fireSettingsChangedEvent(eventBus, settings);
}
});
enabled.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
enabled.setSortable(true);
table.addColumn(enabled, "Enabled");
// PTU ID
Column<String, String> ptuId = new Column<String, String>(
new TextCell()) {
@Override
public String getValue(String object) {
return object;
}
};
ptuId.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
ptuId.setSortable(true);
table.addColumn(ptuId, "PTU ID");
// NAME
Column<String, String> name = new Column<String, String>(
new TextInputSizeCell(30)) {
@Override
public String getValue(String object) {
return settings.getName(object);
}
};
name.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
settings.setName(object, value);
fireSettingsChangedEvent(eventBus, settings);
}
});
name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
name.setSortable(true);
table.addColumn(name, "Name");
// DOSIMETER
Column<String, String> dosimeter = new Column<String, String>(
new DynamicSelectionCell(new StringList<Integer>(
dosimeterSerialNumbers))) {
@Override
public String getValue(String object) {
return settings.getDosimeterSerialNumber(object).toString();
}
};
dosimeter.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
settings.setDosimeterSerialNumber(object,
Integer.parseInt(value));
fireSettingsChangedEvent(eventBus, settings);
}
});
dosimeter.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
dosimeter.setSortable(true);
table.addColumn(dosimeter, "Dosimeter #");
// HELMET URL
Column<String, String> helmetUrl = new Column<String, String>(
new TextInputSizeCell(50)) {
@Override
public String getValue(String object) {
return settings.getCameraUrl(object, CameraView.HELMET);
}
};
helmetUrl.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
settings.setCameraUrl(object, CameraView.HELMET, value);
fireSettingsChangedEvent(eventBus, settings);
}
});
helmetUrl.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
helmetUrl.setSortable(true);
table.addColumn(helmetUrl, "Helmet Camera URL");
// HAND URL
Column<String, String> handUrl = new Column<String, String>(
new TextInputSizeCell(50)) {
@Override
public String getValue(String object) {
return settings.getCameraUrl(object, CameraView.HAND);
}
};
handUrl.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
settings.setCameraUrl(object, CameraView.HAND, value);
fireSettingsChangedEvent(eventBus, settings);
}
});
handUrl.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
handUrl.setSortable(true);
table.addColumn(handUrl, "Hand Camera URL");
dataProvider.addDataDisplay(table);
dataProvider.setList(new ArrayList<String>());
// SORTING
columnSortHandler = new ListHandler<String>(dataProvider.getList());
columnSortHandler.setComparator(ptuId, new Comparator<String>() {
public int compare(String o1, String o2) {
return o1 != null ? o1.compareTo(o2) : -1;
}
});
columnSortHandler.setComparator(active, new Comparator<String>() {
public int compare(String o1, String o2) {
return activePtuIds.contains(o1) ? activePtuIds.contains(o2) ? 0 : 1 : -1;
}
});
columnSortHandler.setComparator(enabled, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.isEnabled(o1).compareTo(settings.isEnabled(o2));
}
});
columnSortHandler.setComparator(name, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.getName(o1).compareTo(settings.getName(o2));
}
});
columnSortHandler.setComparator(dosimeter, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.getDosimeterSerialNumber(o1).compareTo(
settings.getDosimeterSerialNumber(o2));
}
});
columnSortHandler.setComparator(helmetUrl, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.getCameraUrl(o1, CameraView.HELMET).compareTo(
settings.getCameraUrl(o2, CameraView.HELMET));
}
});
columnSortHandler.setComparator(handUrl, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.getCameraUrl(o1, CameraView.HAND).compareTo(
settings.getCameraUrl(o2, CameraView.HAND));
}
});
table.addColumnSortHandler(columnSortHandler);
table.getColumnSortList().push(ptuId);
PtuSettingsChangedEvent.subscribe(eventBus,
new PtuSettingsChangedEvent.Handler() {
@Override
public void onPtuSettingsChanged(
PtuSettingsChangedEvent event) {
System.err.println("PTU Settings changed");
settings = event.getPtuSettings();
dataProvider.getList().clear();
dataProvider.getList().addAll(settings.getPtuIds());
update();
}
});
PtuIdsChangedEvent.subscribe(eventBus,
new PtuIdsChangedEvent.Handler() {
@Override
public void onPtuIdsChanged(PtuIdsChangedEvent event) {
System.err.println("PTU IDS changed");
activePtuIds = event.getPtuIds();
update();
}
});
DosimeterSerialNumbersChangedEvent.subscribe(eventBus,
new DosimeterSerialNumbersChangedEvent.Handler() {
@Override
public void onDosimeterSerialNumbersChanged(
DosimeterSerialNumbersChangedEvent event) {
dosimeterSerialNumbers.clear();
dosimeterSerialNumbers.addAll(event
.getDosimeterSerialNumbers());
System.err.println("DOSI changed "
+ dosimeterSerialNumbers.size());
// FIXME, allow for setting not available as DOSI #
update();
}
});
update();
}
| public PtuSettingsView(ClientFactory clientFactory, Arguments args) {
final RemoteEventBus eventBus = clientFactory.getRemoteEventBus();
add(table);
// ACTIVE
Column<String, Boolean> active = new Column<String, Boolean>(
new ActiveCheckboxCell()) {
@Override
public Boolean getValue(String object) {
return activePtuIds.contains(object);
}
};
active.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
active.setSortable(true);
table.addColumn(active, "Active");
// ENABLED
Column<String, Boolean> enabled = new Column<String, Boolean>(
new CheckboxCell()) {
@Override
public Boolean getValue(String object) {
return settings.isEnabled(object);
}
};
enabled.setFieldUpdater(new FieldUpdater<String, Boolean>() {
@Override
public void update(int index, String object, Boolean value) {
settings.setEnabled(object, value);
fireSettingsChangedEvent(eventBus, settings);
}
});
enabled.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
enabled.setSortable(true);
table.addColumn(enabled, "Enabled");
// PTU ID
Column<String, String> ptuId = new Column<String, String>(
new TextCell()) {
@Override
public String getValue(String object) {
return object;
}
};
ptuId.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
ptuId.setSortable(true);
table.addColumn(ptuId, "PTU ID");
// NAME
Column<String, String> name = new Column<String, String>(
new TextInputSizeCell(30)) {
@Override
public String getValue(String object) {
return settings.getName(object);
}
};
name.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
settings.setName(object, value);
fireSettingsChangedEvent(eventBus, settings);
}
});
name.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
name.setSortable(true);
table.addColumn(name, "Name");
// DOSIMETER
Column<String, String> dosimeter = new Column<String, String>(
new DynamicSelectionCell(new StringList<Integer>(
dosimeterSerialNumbers))) {
@Override
public String getValue(String object) {
return settings.getDosimeterSerialNumber(object).toString();
}
};
dosimeter.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
settings.setDosimeterSerialNumber(object,
Integer.parseInt(value));
fireSettingsChangedEvent(eventBus, settings);
}
});
dosimeter.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
dosimeter.setSortable(true);
table.addColumn(dosimeter, "Dosimeter #");
// HELMET URL
Column<String, String> helmetUrl = new Column<String, String>(
new TextInputSizeCell(50)) {
@Override
public String getValue(String object) {
return settings.getCameraUrl(object, CameraView.HELMET);
}
};
helmetUrl.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
settings.setCameraUrl(object, CameraView.HELMET, value);
fireSettingsChangedEvent(eventBus, settings);
}
});
helmetUrl.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
helmetUrl.setSortable(true);
table.addColumn(helmetUrl, "Helmet Camera URL");
// HAND URL
Column<String, String> handUrl = new Column<String, String>(
new TextInputSizeCell(50)) {
@Override
public String getValue(String object) {
return settings.getCameraUrl(object, CameraView.HAND);
}
};
handUrl.setFieldUpdater(new FieldUpdater<String, String>() {
@Override
public void update(int index, String object, String value) {
settings.setCameraUrl(object, CameraView.HAND, value);
fireSettingsChangedEvent(eventBus, settings);
}
});
handUrl.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
handUrl.setSortable(true);
table.addColumn(handUrl, "Hand Camera URL");
dataProvider.addDataDisplay(table);
dataProvider.setList(new ArrayList<String>());
// SORTING
columnSortHandler = new ListHandler<String>(dataProvider.getList());
columnSortHandler.setComparator(ptuId, new Comparator<String>() {
public int compare(String o1, String o2) {
return o1 != null ? o1.compareTo(o2) : -1;
}
});
columnSortHandler.setComparator(active, new Comparator<String>() {
public int compare(String o1, String o2) {
return activePtuIds.contains(o1) ? activePtuIds.contains(o2) ? 0 : 1 : -1;
}
});
columnSortHandler.setComparator(enabled, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.isEnabled(o1).compareTo(settings.isEnabled(o2));
}
});
columnSortHandler.setComparator(name, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.getName(o1).compareTo(settings.getName(o2));
}
});
columnSortHandler.setComparator(dosimeter, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.getDosimeterSerialNumber(o1).compareTo(
settings.getDosimeterSerialNumber(o2));
}
});
columnSortHandler.setComparator(helmetUrl, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.getCameraUrl(o1, CameraView.HELMET).compareTo(
settings.getCameraUrl(o2, CameraView.HELMET));
}
});
columnSortHandler.setComparator(handUrl, new Comparator<String>() {
public int compare(String o1, String o2) {
return settings.getCameraUrl(o1, CameraView.HAND).compareTo(
settings.getCameraUrl(o2, CameraView.HAND));
}
});
table.addColumnSortHandler(columnSortHandler);
table.getColumnSortList().push(ptuId);
PtuSettingsChangedEvent.subscribe(eventBus,
new PtuSettingsChangedEvent.Handler() {
@Override
public void onPtuSettingsChanged(
PtuSettingsChangedEvent event) {
System.err.println("PTU Settings changed");
settings = event.getPtuSettings();
dataProvider.getList().clear();
dataProvider.getList().addAll(settings.getPtuIds());
update();
}
});
PtuIdsChangedEvent.subscribe(eventBus,
new PtuIdsChangedEvent.Handler() {
@Override
public void onPtuIdsChanged(PtuIdsChangedEvent event) {
System.err.println("PTU IDS changed");
activePtuIds = event.getPtuIds();
update();
}
});
DosimeterSerialNumbersChangedEvent.subscribe(eventBus,
new DosimeterSerialNumbersChangedEvent.Handler() {
@Override
public void onDosimeterSerialNumbersChanged(
DosimeterSerialNumbersChangedEvent event) {
dosimeterSerialNumbers.clear();
dosimeterSerialNumbers.addAll(event
.getDosimeterSerialNumbers());
System.err.println("DOSI changed "
+ dosimeterSerialNumbers.size());
// FIXME, allow for setting not available as DOSI #
update();
}
});
update();
}
|
diff --git a/Tantalum3Android/src/com/futurice/tantalum3/TantalumActivity.java b/Tantalum3Android/src/com/futurice/tantalum3/TantalumActivity.java
index 708e411d..f3c7ad13 100644
--- a/Tantalum3Android/src/com/futurice/tantalum3/TantalumActivity.java
+++ b/Tantalum3Android/src/com/futurice/tantalum3/TantalumActivity.java
@@ -1,69 +1,69 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.futurice.tantalum3;
import android.app.Activity;
import android.os.Bundle;
import com.futurice.tantalum3.rms.AndroidDatabase;
/**
*
* @author phou
*/
public abstract class TantalumActivity extends Activity {
public TantalumActivity() {
super();
PlatformUtils.setProgram(this);
- Worker.init(4);
+ Worker.init(this, 4);
}
/**
* Call this to close your MIDlet in an orderly manner, exactly the same way
* it is closed if the system sends you a destoryApp().
*
* Ongoing Work tasks will complete, or if you set unconditional then they
* will complete within 3 seconds.
*
* @param unconditional
*/
public void exitMIDlet(final boolean unconditional) {
Worker.shutdown(unconditional);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidDatabase.setContext(((Activity) this).getApplicationContext());
}
/**
* Do not call this directly. Instead, call exitMidlet(false) to avoid
* common errors.
*
* If you do for some reason call this directly, realize the MIDlet will
* exit immediately after the call is complete, rather than wait for you to
* call notifyDestroyed() once an ongoing file or RMS write actions are
* completed. Usually, this is not desirable, call exitMidlet() instead and
* ongoing tasks will complete.
*
* If you want something done during shutdown, use
* Worker.queueShutdownTask(Workable) and it will be handled for you.
*
* @param unconditional
* @throws MIDletStateChangeException
*/
protected final void destroyApp(final boolean unconditional) {
exitMIDlet(unconditional);
}
/**
* Do nothing, not generally used
*
*/
protected void pauseApp() {
}
}
| true | true | public TantalumActivity() {
super();
PlatformUtils.setProgram(this);
Worker.init(4);
}
| public TantalumActivity() {
super();
PlatformUtils.setProgram(this);
Worker.init(this, 4);
}
|
diff --git a/modules/core/src/main/java/org/apache/sandesha2/storage/inmemory/InMemoryTransaction.java b/modules/core/src/main/java/org/apache/sandesha2/storage/inmemory/InMemoryTransaction.java
index 15b12e46..835a021d 100644
--- a/modules/core/src/main/java/org/apache/sandesha2/storage/inmemory/InMemoryTransaction.java
+++ b/modules/core/src/main/java/org/apache/sandesha2/storage/inmemory/InMemoryTransaction.java
@@ -1,178 +1,178 @@
/*
* 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.sandesha2.storage.inmemory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sandesha2.i18n.SandeshaMessageHelper;
import org.apache.sandesha2.i18n.SandeshaMessageKeys;
import org.apache.sandesha2.storage.SandeshaStorageException;
import org.apache.sandesha2.storage.Transaction;
import org.apache.sandesha2.storage.beans.RMBean;
/**
* This class does not really implement transactions, but it is a good
* place to implement locking for the in memory storage manager.
*/
public class InMemoryTransaction implements Transaction {
private static final Log log = LogFactory.getLog(InMemoryTransaction.class);
private InMemoryStorageManager manager;
private String threadName;
private ArrayList enlistedBeans = new ArrayList();
private InMemoryTransaction waitingForTran = null;
private boolean sentMessages = false;
private boolean active = true;
private Thread thread;
InMemoryTransaction(InMemoryStorageManager manager, Thread thread) {
if(log.isDebugEnabled()) log.debug("Entry: InMemoryTransaction::<init>");
this.manager = manager;
this.thread = thread;
this.threadName = thread.getName();
if(log.isDebugEnabled()) log.debug("Exit: InMemoryTransaction::<init>, " + this);
}
public void commit() {
releaseLocks();
if(sentMessages) manager.getSender().wakeThread();
active = false;
}
public void rollback() {
releaseLocks();
active = false;
}
public boolean isActive () {
return active;
}
public void enlist(RMBean bean) throws SandeshaStorageException {
if(log.isDebugEnabled()) log.debug("Entry: InMemoryTransaction::enlist, " + bean);
if(bean != null) {
synchronized (bean) {
InMemoryTransaction other = (InMemoryTransaction) bean.getTransaction();
while(other != null && other != this) {
// Put ourselves into the list of waiters
waitingForTran = other;
// Look to see if there is a loop in the chain of waiters
if(!enlistedBeans.isEmpty()) {
HashSet set = new HashSet();
set.add(this);
- while(other != null) {
+ while(other != null && other != this) {
if(set.contains(other)) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.deadlock, this.toString(), bean.toString());
SandeshaStorageException e = new SandeshaStorageException(message);
// Do our best to get out of the way of the other work in the system
waitingForTran = null;
releaseLocks();
if(log.isDebugEnabled()) log.debug(message, e);
throw e;
}
set.add(other);
other = other.waitingForTran;
}
}
boolean warn = false;
try {
if(log.isDebugEnabled()) log.debug("This " + this + " waiting for " + waitingForTran);
long pre = System.currentTimeMillis();
bean.wait(5000);
long post = System.currentTimeMillis();
if ((post - pre) > 50000)
warn = true;
} catch(InterruptedException e) {
// Do nothing
}
other = (InMemoryTransaction) bean.getTransaction();
if (other != null && warn) {
//we have been waiting for a long time - this might imply a three way deadlock so error condition
if(log.isDebugEnabled()) log.debug("possible deadlock :" + this.toString() + " : " + bean.toString());
}
}
waitingForTran = null;
if(other == null) {
if(log.isDebugEnabled()) log.debug(this + " locking bean");
bean.setTransaction(this);
enlistedBeans.add(bean);
}
}
}
if(log.isDebugEnabled()) log.debug("Exit: InMemoryTransaction::enlist");
}
private void releaseLocks() {
if(log.isDebugEnabled()) log.debug("Entry: InMemoryTransaction::releaseLocks, " + this);
manager.removeTransaction(this);
Iterator beans = enlistedBeans.iterator();
while(beans.hasNext()) {
RMBean bean = (RMBean) beans.next();
synchronized (bean) {
bean.setTransaction(null);
bean.notifyAll();
}
}
enlistedBeans.clear();
if(log.isDebugEnabled()) log.debug("Exit: InMemoryTransaction::releaseLocks");
}
public String toString() {
StringBuffer result = new StringBuffer();
result.append("[InMemoryTransaction, thread:");
result.append(thread);
result.append(", name: ");
result.append(threadName);
result.append(", locks: ");
result.append(enlistedBeans.size());
result.append("]");
return result.toString();
}
public void setSentMessages(boolean sentMessages) {
this.sentMessages = sentMessages;
}
/**
* Get the thread which this transaction is associated with.
* @return
*/
public Thread getThread(){
return thread;
}
}
| true | true | public void enlist(RMBean bean) throws SandeshaStorageException {
if(log.isDebugEnabled()) log.debug("Entry: InMemoryTransaction::enlist, " + bean);
if(bean != null) {
synchronized (bean) {
InMemoryTransaction other = (InMemoryTransaction) bean.getTransaction();
while(other != null && other != this) {
// Put ourselves into the list of waiters
waitingForTran = other;
// Look to see if there is a loop in the chain of waiters
if(!enlistedBeans.isEmpty()) {
HashSet set = new HashSet();
set.add(this);
while(other != null) {
if(set.contains(other)) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.deadlock, this.toString(), bean.toString());
SandeshaStorageException e = new SandeshaStorageException(message);
// Do our best to get out of the way of the other work in the system
waitingForTran = null;
releaseLocks();
if(log.isDebugEnabled()) log.debug(message, e);
throw e;
}
set.add(other);
other = other.waitingForTran;
}
}
boolean warn = false;
try {
if(log.isDebugEnabled()) log.debug("This " + this + " waiting for " + waitingForTran);
long pre = System.currentTimeMillis();
bean.wait(5000);
long post = System.currentTimeMillis();
if ((post - pre) > 50000)
warn = true;
} catch(InterruptedException e) {
// Do nothing
}
other = (InMemoryTransaction) bean.getTransaction();
if (other != null && warn) {
//we have been waiting for a long time - this might imply a three way deadlock so error condition
if(log.isDebugEnabled()) log.debug("possible deadlock :" + this.toString() + " : " + bean.toString());
}
}
waitingForTran = null;
if(other == null) {
if(log.isDebugEnabled()) log.debug(this + " locking bean");
bean.setTransaction(this);
enlistedBeans.add(bean);
}
}
}
if(log.isDebugEnabled()) log.debug("Exit: InMemoryTransaction::enlist");
}
| public void enlist(RMBean bean) throws SandeshaStorageException {
if(log.isDebugEnabled()) log.debug("Entry: InMemoryTransaction::enlist, " + bean);
if(bean != null) {
synchronized (bean) {
InMemoryTransaction other = (InMemoryTransaction) bean.getTransaction();
while(other != null && other != this) {
// Put ourselves into the list of waiters
waitingForTran = other;
// Look to see if there is a loop in the chain of waiters
if(!enlistedBeans.isEmpty()) {
HashSet set = new HashSet();
set.add(this);
while(other != null && other != this) {
if(set.contains(other)) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.deadlock, this.toString(), bean.toString());
SandeshaStorageException e = new SandeshaStorageException(message);
// Do our best to get out of the way of the other work in the system
waitingForTran = null;
releaseLocks();
if(log.isDebugEnabled()) log.debug(message, e);
throw e;
}
set.add(other);
other = other.waitingForTran;
}
}
boolean warn = false;
try {
if(log.isDebugEnabled()) log.debug("This " + this + " waiting for " + waitingForTran);
long pre = System.currentTimeMillis();
bean.wait(5000);
long post = System.currentTimeMillis();
if ((post - pre) > 50000)
warn = true;
} catch(InterruptedException e) {
// Do nothing
}
other = (InMemoryTransaction) bean.getTransaction();
if (other != null && warn) {
//we have been waiting for a long time - this might imply a three way deadlock so error condition
if(log.isDebugEnabled()) log.debug("possible deadlock :" + this.toString() + " : " + bean.toString());
}
}
waitingForTran = null;
if(other == null) {
if(log.isDebugEnabled()) log.debug(this + " locking bean");
bean.setTransaction(this);
enlistedBeans.add(bean);
}
}
}
if(log.isDebugEnabled()) log.debug("Exit: InMemoryTransaction::enlist");
}
|
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ReplaceWithTagAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ReplaceWithTagAction.java
index 0a8493237..e3c9ce1f6 100644
--- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ReplaceWithTagAction.java
+++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ReplaceWithTagAction.java
@@ -1,129 +1,129 @@
/*******************************************************************************
* 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.team.internal.ccvs.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.mapping.ResourceMapping;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.team.internal.ccvs.core.CVSTag;
import org.eclipse.team.internal.ccvs.ui.IHelpContextIds;
import org.eclipse.team.internal.ccvs.ui.Policy;
import org.eclipse.team.internal.ccvs.ui.operations.ReplaceOperation;
import org.eclipse.team.internal.ccvs.ui.tags.TagSelectionDialog;
import org.eclipse.team.internal.ccvs.ui.tags.TagSource;
import org.eclipse.team.internal.core.InfiniteSubProgressMonitor;
import org.eclipse.team.internal.ui.dialogs.ResourceMappingResourceDisplayArea;
/**
* Action for replace with tag.
*/
public class ReplaceWithTagAction extends WorkspaceTraversalAction {
/* package*/ static UncommittedChangesDialog getPromptingDialog(Shell shell, ResourceMapping[] mappings) {
return new UncommittedChangesDialog(shell, Policy.bind("ReplaceWithTagAction.4"), mappings) { //$NON-NLS-1$
protected String getSingleMappingMessage(ResourceMapping mapping) {
String label = ResourceMappingResourceDisplayArea.getLabel(mapping);
if (getAllMappings().length == 1) {
return Policy.bind("ReplaceWithTagAction.2", label); //$NON-NLS-1$
}
return Policy.bind("ReplaceWithTagAction.0", label); //$NON-NLS-1$
}
protected String getMultipleMappingsMessage() {
return Policy.bind("ReplaceWithTagAction.1"); //$NON-NLS-1$
}
};
}
protected static ResourceMapping[] checkOverwriteOfDirtyResources(Shell shell, ResourceMapping[] mappings, IProgressMonitor monitor) {
// Prompt for any uncommitted changes
UncommittedChangesDialog dialog = getPromptingDialog(shell, mappings);
mappings = dialog.promptToSelectMappings();
if(mappings.length == 0) {
// nothing to do
return null;
}
return mappings;
}
/*
* Method declared on IActionDelegate.
*/
public void execute(IAction action) throws InterruptedException, InvocationTargetException {
// Setup the holders
final ResourceMapping[][] resourceMappings = new ResourceMapping[][] {null};
final CVSTag[] tag = new CVSTag[] {null};
final boolean[] recurse = new boolean[] {true};
// Show a busy cursor while display the tag selection dialog
run(new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InterruptedException, InvocationTargetException {
monitor = Policy.monitorFor(monitor);
resourceMappings[0] = checkOverwriteOfDirtyResources(getShell(), getCVSResourceMappings(), new InfiniteSubProgressMonitor(monitor, 100));
if(resourceMappings[0] == null || resourceMappings[0].length == 0) {
// nothing to do
return;
}
TagSelectionDialog dialog = new TagSelectionDialog(getShell(), TagSource.create(resourceMappings[0]),
Policy.bind("ReplaceWithTagAction.message"), //$NON-NLS-1$
Policy.bind("TagSelectionDialog.Select_a_Tag_1"), //$NON-NLS-1$
TagSelectionDialog.INCLUDE_ALL_TAGS,
- true, /*show recurse*/
+ !isLogicalModel(getCVSResourceMappings()), /*show recurse*/
IHelpContextIds.REPLACE_TAG_SELECTION_DIALOG); //$NON-NLS-1$
dialog.setBlockOnOpen(true);
if (dialog.open() == Dialog.CANCEL) {
return;
}
tag[0] = dialog.getResult();
recurse[0] = dialog.getRecursive();
// For non-projects determine if the tag being loaded is the same as the resource's parent
// If it's not, warn the user that they will have strange sync behavior
try {
if(!CVSAction.checkForMixingTags(getShell(), getRootTraversalResources(resourceMappings[0], null, null), tag[0])) {
tag[0] = null;
return;
}
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
}, false /* cancelable */, PROGRESS_BUSYCURSOR); //$NON-NLS-1$
if (resourceMappings[0] == null || resourceMappings[0].length == 0 || tag[0] == null) return;
// Peform the replace in the background
new ReplaceOperation(getTargetPart(), resourceMappings[0], tag[0], recurse[0]).run();
}
/**
* @see org.eclipse.team.internal.ccvs.ui.actions.CVSAction#getErrorTitle()
*/
protected String getErrorTitle() {
return Policy.bind("ReplaceWithTagAction.replace"); //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.eclipse.team.internal.ccvs.ui.actions.WorkspaceAction#isEnabledForNonExistantResources()
*/
protected boolean isEnabledForNonExistantResources() {
return true;
}
}
| true | true | public void execute(IAction action) throws InterruptedException, InvocationTargetException {
// Setup the holders
final ResourceMapping[][] resourceMappings = new ResourceMapping[][] {null};
final CVSTag[] tag = new CVSTag[] {null};
final boolean[] recurse = new boolean[] {true};
// Show a busy cursor while display the tag selection dialog
run(new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InterruptedException, InvocationTargetException {
monitor = Policy.monitorFor(monitor);
resourceMappings[0] = checkOverwriteOfDirtyResources(getShell(), getCVSResourceMappings(), new InfiniteSubProgressMonitor(monitor, 100));
if(resourceMappings[0] == null || resourceMappings[0].length == 0) {
// nothing to do
return;
}
TagSelectionDialog dialog = new TagSelectionDialog(getShell(), TagSource.create(resourceMappings[0]),
Policy.bind("ReplaceWithTagAction.message"), //$NON-NLS-1$
Policy.bind("TagSelectionDialog.Select_a_Tag_1"), //$NON-NLS-1$
TagSelectionDialog.INCLUDE_ALL_TAGS,
true, /*show recurse*/
IHelpContextIds.REPLACE_TAG_SELECTION_DIALOG); //$NON-NLS-1$
dialog.setBlockOnOpen(true);
if (dialog.open() == Dialog.CANCEL) {
return;
}
tag[0] = dialog.getResult();
recurse[0] = dialog.getRecursive();
// For non-projects determine if the tag being loaded is the same as the resource's parent
// If it's not, warn the user that they will have strange sync behavior
try {
if(!CVSAction.checkForMixingTags(getShell(), getRootTraversalResources(resourceMappings[0], null, null), tag[0])) {
tag[0] = null;
return;
}
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
}, false /* cancelable */, PROGRESS_BUSYCURSOR); //$NON-NLS-1$
if (resourceMappings[0] == null || resourceMappings[0].length == 0 || tag[0] == null) return;
// Peform the replace in the background
new ReplaceOperation(getTargetPart(), resourceMappings[0], tag[0], recurse[0]).run();
}
| public void execute(IAction action) throws InterruptedException, InvocationTargetException {
// Setup the holders
final ResourceMapping[][] resourceMappings = new ResourceMapping[][] {null};
final CVSTag[] tag = new CVSTag[] {null};
final boolean[] recurse = new boolean[] {true};
// Show a busy cursor while display the tag selection dialog
run(new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InterruptedException, InvocationTargetException {
monitor = Policy.monitorFor(monitor);
resourceMappings[0] = checkOverwriteOfDirtyResources(getShell(), getCVSResourceMappings(), new InfiniteSubProgressMonitor(monitor, 100));
if(resourceMappings[0] == null || resourceMappings[0].length == 0) {
// nothing to do
return;
}
TagSelectionDialog dialog = new TagSelectionDialog(getShell(), TagSource.create(resourceMappings[0]),
Policy.bind("ReplaceWithTagAction.message"), //$NON-NLS-1$
Policy.bind("TagSelectionDialog.Select_a_Tag_1"), //$NON-NLS-1$
TagSelectionDialog.INCLUDE_ALL_TAGS,
!isLogicalModel(getCVSResourceMappings()), /*show recurse*/
IHelpContextIds.REPLACE_TAG_SELECTION_DIALOG); //$NON-NLS-1$
dialog.setBlockOnOpen(true);
if (dialog.open() == Dialog.CANCEL) {
return;
}
tag[0] = dialog.getResult();
recurse[0] = dialog.getRecursive();
// For non-projects determine if the tag being loaded is the same as the resource's parent
// If it's not, warn the user that they will have strange sync behavior
try {
if(!CVSAction.checkForMixingTags(getShell(), getRootTraversalResources(resourceMappings[0], null, null), tag[0])) {
tag[0] = null;
return;
}
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
}, false /* cancelable */, PROGRESS_BUSYCURSOR); //$NON-NLS-1$
if (resourceMappings[0] == null || resourceMappings[0].length == 0 || tag[0] == null) return;
// Peform the replace in the background
new ReplaceOperation(getTargetPart(), resourceMappings[0], tag[0], recurse[0]).run();
}
|
diff --git a/src/me/gods/raintimer/TimerFragment.java b/src/me/gods/raintimer/TimerFragment.java
index 08af312..7a580a1 100644
--- a/src/me/gods/raintimer/TimerFragment.java
+++ b/src/me/gods/raintimer/TimerFragment.java
@@ -1,413 +1,413 @@
package me.gods.raintimer;
import java.util.Calendar;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class TimerFragment extends Fragment {
private TextView favoriteEvents;
private RadioButton[] radios = new RadioButton[6];
private int[] radioIds = new int[6];
private FavoriteRadioListener frl = new FavoriteRadioListener();
private Spinner eventSpinner;
private ArrayAdapter<String> adapter;
private static TextView timerText;
private static Button switcherButton;
private SharedPreferences settings;
private String[] events;
private int eventLength;
private String[] candidateFavorite;
private boolean[] candidateChecked;
private JSONArray favoriteArray;
private enum State {
reset,
running,
pause,
stop
};
private State state;
private static long startTime;
private static long offsetTime;
private TimerThread timerThread;
private String currentEvent;
private SQLiteDatabase db;
final static Handler handler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what) {
case 1:
long minus = System.currentTimeMillis() - startTime;
timerText.setText(millisToTime(offsetTime + minus));
break;
default:
break;
}
super.handleMessage(msg);
}
};
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.state = State.reset;
}
@Override
public void onResume () {
super.onResume();
}
@Override
public void onPause () {
super.onPause();
db.close();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_timer, container, false);
db = getActivity().openOrCreateDatabase("raintimer.db", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS history (_id INTEGER PRIMARY KEY AUTOINCREMENT, event_name VARCHAR, total_time INT, commit_date VARCHAR)");
settings = this.getActivity().getPreferences(Activity.MODE_PRIVATE);
String eventList = settings.getString(PreferenceFragment.EVENT_LIST, "[]");
JSONArray eventArray = null;
try {
eventArray = new JSONArray(eventList);
} catch (JSONException e) {
e.printStackTrace();
}
eventLength = eventArray.length();
events = new String[eventLength + 1];
events[0] = getString(R.string.default_event);
for (int i = 1; i < eventLength + 1; i++) {
try {
events[i] = eventArray.getString(i - 1);
} catch (JSONException e) {
e.printStackTrace();
}
}
String favoriteList = settings.getString(PreferenceFragment.FAVORITE_EVENT_LIST, "[]");
favoriteArray = null;
try {
favoriteArray = new JSONArray(favoriteList);
} catch (JSONException e) {
e.printStackTrace();
}
candidateFavorite = new String[eventLength];
candidateChecked = new boolean[eventLength];
for (int i = 0; i < eventLength; i++) {
try {
candidateFavorite[i] = eventArray.getString(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < favoriteArray.length(); i++) {
int j;
for (j = 0; j < candidateFavorite.length; j++) {
try {
if (favoriteArray.getString(i).equals(candidateFavorite[j])) {
candidateChecked[j] = true;
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
radioIds[0] = R.id.radio_0;
radioIds[1] = R.id.radio_1;
radioIds[2] = R.id.radio_2;
radioIds[3] = R.id.radio_3;
radioIds[4] = R.id.radio_4;
radioIds[5] = R.id.radio_5;
for (int i = 0; i < 6; i++) {
radios[i] = (RadioButton)v.findViewById(radioIds[i]);
radios[i].setOnClickListener(frl);
}
updateFavoriteRadios();
favoriteEvents = (TextView)v.findViewById(R.id.favorite_events);
favoriteEvents.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setIcon(android.R.drawable.btn_star_big_on)
.setTitle("Choose Favorite")
.setMultiChoiceItems(candidateFavorite, candidateChecked, new OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface arg0, int which, boolean isChecked) {
int count = 0;
for (int i = 0; i < eventLength; i++) {
if (candidateChecked[i]) {
Log.i("caca", "checked" + count);
count ++;
}
if (count > 6) {
Toast.makeText(getActivity(), "No more than 6:)", Toast.LENGTH_SHORT).show();
((AlertDialog) arg0).getButton(arg0.BUTTON_POSITIVE).setEnabled(false);
} else {
((AlertDialog) arg0).getButton(arg0.BUTTON_POSITIVE).setEnabled(true);
}
}
}
})
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
SparseBooleanArray Checked = ((AlertDialog) arg0).getListView().getCheckedItemPositions();
favoriteArray = new JSONArray();
- for (int i = 0; i < eventLength - 1; i++) {
+ for (int i = 0; i < eventLength; i++) {
if (Checked.get(i)) {
favoriteArray.put(candidateFavorite[i]);
}
}
settings.edit().putString(PreferenceFragment.FAVORITE_EVENT_LIST, favoriteArray.toString()).commit();
updateFavoriteRadios();
}
})
.setNegativeButton("Cancel", null).create();
dialog.show();
}
});
eventSpinner = (Spinner)v.findViewById(R.id.event_spinner);
adapter = new ArrayAdapter<String>(this.getActivity(), R.layout.spinner_text, events);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
eventSpinner.setAdapter(adapter);
eventSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
currentEvent = events[arg2];
if (arg2 == 0) {
for (int i = 0; i < 6; i++) {
radios[i].setChecked(false);
}
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
timerText = (TextView)v.findViewById(R.id.timer_text);
timerText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (state == State.running) {
state = State.pause;
try {
timerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
offsetTime += System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
} else if (state == State.pause) {
state = State.running;
startTime = System.currentTimeMillis();
timerThread = new TimerThread();
timerThread.start();
}
}
});
switcherButton = (Button)v.findViewById(R.id.timer_switcher);
switcherButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(state) {
case reset:
state = State.running;
startTime = System.currentTimeMillis();
timerThread = new TimerThread();
timerThread.start();
break;
case running:
case pause:
state = State.stop;
try {
timerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
offsetTime += System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
if (currentEvent != null && currentEvent != getString(R.string.default_event)) {
new Builder(getActivity())
.setMessage("Save this?")
.setTitle("Info")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
String sql = "insert into history values(null, ?, ?, ?)";
Calendar now = Calendar.getInstance();
String dateString = String.format("%02d-%02d-%04d", now.get(Calendar.MONTH) + 1, now.get(Calendar.DATE), now.get(Calendar.YEAR));
Object[] bindArgs = new Object[] {currentEvent, offsetTime, dateString};
db.execSQL(sql, bindArgs);
}
})
.setNegativeButton("Discard", null).show();
}
break;
case stop:
state = State.reset;
timerText.setText("0'00\"00");
offsetTime = 0;
break;
default:
break;
}
updateButton();
}
});
updateButton();
return v;
}
public static String millisToTime(long millis) {
long millisecond = (millis / 10) % 100;
long second = (millis / 1000) % 60;
long minute = (millis / 1000 / 60) % 60;
return String.format(Locale.getDefault(), "%d'%02d\"%02d", minute, second, millisecond);
}
public void updateFavoriteRadios() {
int i;
int length = favoriteArray.length();
for (i = 0; i < length; i++) {
try {
radios[i].setText(favoriteArray.getString(i));
radios[i].setVisibility(View.VISIBLE);
} catch (Exception e) {
Log.e("RADIO", "Cannot set text");
}
}
for (;i < 6; i++) {
radios[i].setVisibility(View.GONE);
}
}
public void updateButton() {
switch(state) {
case reset:
switcherButton.setText("Start");
break;
case running:
switcherButton.setText("Stop");
break;
case stop:
switcherButton.setText("Reset");
break;
default:
break;
}
}
public class TimerThread extends Thread {
@Override
public void run(){
while(state == TimerFragment.State.running){
try{
Thread.sleep(10);
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}catch (Exception e) {
}
}
}
}
public class FavoriteRadioListener implements View.OnClickListener {
@Override
public void onClick(View v) {
for (int i = 0; i < 6; i++) {
if (radioIds[i] == v.getId()) {
radios[i].setChecked(true);
currentEvent = radios[i].getText().toString();
for (int j = 0; j < eventLength + 1; j++) {
if (currentEvent.equals(events[j])) {
eventSpinner.setSelection(j);
}
}
Log.i("Caca", currentEvent);;
}else {
radios[i].setChecked(false);
}
}
}
}
}
| true | true | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_timer, container, false);
db = getActivity().openOrCreateDatabase("raintimer.db", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS history (_id INTEGER PRIMARY KEY AUTOINCREMENT, event_name VARCHAR, total_time INT, commit_date VARCHAR)");
settings = this.getActivity().getPreferences(Activity.MODE_PRIVATE);
String eventList = settings.getString(PreferenceFragment.EVENT_LIST, "[]");
JSONArray eventArray = null;
try {
eventArray = new JSONArray(eventList);
} catch (JSONException e) {
e.printStackTrace();
}
eventLength = eventArray.length();
events = new String[eventLength + 1];
events[0] = getString(R.string.default_event);
for (int i = 1; i < eventLength + 1; i++) {
try {
events[i] = eventArray.getString(i - 1);
} catch (JSONException e) {
e.printStackTrace();
}
}
String favoriteList = settings.getString(PreferenceFragment.FAVORITE_EVENT_LIST, "[]");
favoriteArray = null;
try {
favoriteArray = new JSONArray(favoriteList);
} catch (JSONException e) {
e.printStackTrace();
}
candidateFavorite = new String[eventLength];
candidateChecked = new boolean[eventLength];
for (int i = 0; i < eventLength; i++) {
try {
candidateFavorite[i] = eventArray.getString(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < favoriteArray.length(); i++) {
int j;
for (j = 0; j < candidateFavorite.length; j++) {
try {
if (favoriteArray.getString(i).equals(candidateFavorite[j])) {
candidateChecked[j] = true;
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
radioIds[0] = R.id.radio_0;
radioIds[1] = R.id.radio_1;
radioIds[2] = R.id.radio_2;
radioIds[3] = R.id.radio_3;
radioIds[4] = R.id.radio_4;
radioIds[5] = R.id.radio_5;
for (int i = 0; i < 6; i++) {
radios[i] = (RadioButton)v.findViewById(radioIds[i]);
radios[i].setOnClickListener(frl);
}
updateFavoriteRadios();
favoriteEvents = (TextView)v.findViewById(R.id.favorite_events);
favoriteEvents.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setIcon(android.R.drawable.btn_star_big_on)
.setTitle("Choose Favorite")
.setMultiChoiceItems(candidateFavorite, candidateChecked, new OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface arg0, int which, boolean isChecked) {
int count = 0;
for (int i = 0; i < eventLength; i++) {
if (candidateChecked[i]) {
Log.i("caca", "checked" + count);
count ++;
}
if (count > 6) {
Toast.makeText(getActivity(), "No more than 6:)", Toast.LENGTH_SHORT).show();
((AlertDialog) arg0).getButton(arg0.BUTTON_POSITIVE).setEnabled(false);
} else {
((AlertDialog) arg0).getButton(arg0.BUTTON_POSITIVE).setEnabled(true);
}
}
}
})
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
SparseBooleanArray Checked = ((AlertDialog) arg0).getListView().getCheckedItemPositions();
favoriteArray = new JSONArray();
for (int i = 0; i < eventLength - 1; i++) {
if (Checked.get(i)) {
favoriteArray.put(candidateFavorite[i]);
}
}
settings.edit().putString(PreferenceFragment.FAVORITE_EVENT_LIST, favoriteArray.toString()).commit();
updateFavoriteRadios();
}
})
.setNegativeButton("Cancel", null).create();
dialog.show();
}
});
eventSpinner = (Spinner)v.findViewById(R.id.event_spinner);
adapter = new ArrayAdapter<String>(this.getActivity(), R.layout.spinner_text, events);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
eventSpinner.setAdapter(adapter);
eventSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
currentEvent = events[arg2];
if (arg2 == 0) {
for (int i = 0; i < 6; i++) {
radios[i].setChecked(false);
}
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
timerText = (TextView)v.findViewById(R.id.timer_text);
timerText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (state == State.running) {
state = State.pause;
try {
timerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
offsetTime += System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
} else if (state == State.pause) {
state = State.running;
startTime = System.currentTimeMillis();
timerThread = new TimerThread();
timerThread.start();
}
}
});
switcherButton = (Button)v.findViewById(R.id.timer_switcher);
switcherButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(state) {
case reset:
state = State.running;
startTime = System.currentTimeMillis();
timerThread = new TimerThread();
timerThread.start();
break;
case running:
case pause:
state = State.stop;
try {
timerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
offsetTime += System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
if (currentEvent != null && currentEvent != getString(R.string.default_event)) {
new Builder(getActivity())
.setMessage("Save this?")
.setTitle("Info")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
String sql = "insert into history values(null, ?, ?, ?)";
Calendar now = Calendar.getInstance();
String dateString = String.format("%02d-%02d-%04d", now.get(Calendar.MONTH) + 1, now.get(Calendar.DATE), now.get(Calendar.YEAR));
Object[] bindArgs = new Object[] {currentEvent, offsetTime, dateString};
db.execSQL(sql, bindArgs);
}
})
.setNegativeButton("Discard", null).show();
}
break;
case stop:
state = State.reset;
timerText.setText("0'00\"00");
offsetTime = 0;
break;
default:
break;
}
updateButton();
}
});
updateButton();
return v;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_timer, container, false);
db = getActivity().openOrCreateDatabase("raintimer.db", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS history (_id INTEGER PRIMARY KEY AUTOINCREMENT, event_name VARCHAR, total_time INT, commit_date VARCHAR)");
settings = this.getActivity().getPreferences(Activity.MODE_PRIVATE);
String eventList = settings.getString(PreferenceFragment.EVENT_LIST, "[]");
JSONArray eventArray = null;
try {
eventArray = new JSONArray(eventList);
} catch (JSONException e) {
e.printStackTrace();
}
eventLength = eventArray.length();
events = new String[eventLength + 1];
events[0] = getString(R.string.default_event);
for (int i = 1; i < eventLength + 1; i++) {
try {
events[i] = eventArray.getString(i - 1);
} catch (JSONException e) {
e.printStackTrace();
}
}
String favoriteList = settings.getString(PreferenceFragment.FAVORITE_EVENT_LIST, "[]");
favoriteArray = null;
try {
favoriteArray = new JSONArray(favoriteList);
} catch (JSONException e) {
e.printStackTrace();
}
candidateFavorite = new String[eventLength];
candidateChecked = new boolean[eventLength];
for (int i = 0; i < eventLength; i++) {
try {
candidateFavorite[i] = eventArray.getString(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < favoriteArray.length(); i++) {
int j;
for (j = 0; j < candidateFavorite.length; j++) {
try {
if (favoriteArray.getString(i).equals(candidateFavorite[j])) {
candidateChecked[j] = true;
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
radioIds[0] = R.id.radio_0;
radioIds[1] = R.id.radio_1;
radioIds[2] = R.id.radio_2;
radioIds[3] = R.id.radio_3;
radioIds[4] = R.id.radio_4;
radioIds[5] = R.id.radio_5;
for (int i = 0; i < 6; i++) {
radios[i] = (RadioButton)v.findViewById(radioIds[i]);
radios[i].setOnClickListener(frl);
}
updateFavoriteRadios();
favoriteEvents = (TextView)v.findViewById(R.id.favorite_events);
favoriteEvents.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setIcon(android.R.drawable.btn_star_big_on)
.setTitle("Choose Favorite")
.setMultiChoiceItems(candidateFavorite, candidateChecked, new OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface arg0, int which, boolean isChecked) {
int count = 0;
for (int i = 0; i < eventLength; i++) {
if (candidateChecked[i]) {
Log.i("caca", "checked" + count);
count ++;
}
if (count > 6) {
Toast.makeText(getActivity(), "No more than 6:)", Toast.LENGTH_SHORT).show();
((AlertDialog) arg0).getButton(arg0.BUTTON_POSITIVE).setEnabled(false);
} else {
((AlertDialog) arg0).getButton(arg0.BUTTON_POSITIVE).setEnabled(true);
}
}
}
})
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
SparseBooleanArray Checked = ((AlertDialog) arg0).getListView().getCheckedItemPositions();
favoriteArray = new JSONArray();
for (int i = 0; i < eventLength; i++) {
if (Checked.get(i)) {
favoriteArray.put(candidateFavorite[i]);
}
}
settings.edit().putString(PreferenceFragment.FAVORITE_EVENT_LIST, favoriteArray.toString()).commit();
updateFavoriteRadios();
}
})
.setNegativeButton("Cancel", null).create();
dialog.show();
}
});
eventSpinner = (Spinner)v.findViewById(R.id.event_spinner);
adapter = new ArrayAdapter<String>(this.getActivity(), R.layout.spinner_text, events);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
eventSpinner.setAdapter(adapter);
eventSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
currentEvent = events[arg2];
if (arg2 == 0) {
for (int i = 0; i < 6; i++) {
radios[i].setChecked(false);
}
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
timerText = (TextView)v.findViewById(R.id.timer_text);
timerText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (state == State.running) {
state = State.pause;
try {
timerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
offsetTime += System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
} else if (state == State.pause) {
state = State.running;
startTime = System.currentTimeMillis();
timerThread = new TimerThread();
timerThread.start();
}
}
});
switcherButton = (Button)v.findViewById(R.id.timer_switcher);
switcherButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(state) {
case reset:
state = State.running;
startTime = System.currentTimeMillis();
timerThread = new TimerThread();
timerThread.start();
break;
case running:
case pause:
state = State.stop;
try {
timerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
offsetTime += System.currentTimeMillis() - startTime;
startTime = System.currentTimeMillis();
if (currentEvent != null && currentEvent != getString(R.string.default_event)) {
new Builder(getActivity())
.setMessage("Save this?")
.setTitle("Info")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
String sql = "insert into history values(null, ?, ?, ?)";
Calendar now = Calendar.getInstance();
String dateString = String.format("%02d-%02d-%04d", now.get(Calendar.MONTH) + 1, now.get(Calendar.DATE), now.get(Calendar.YEAR));
Object[] bindArgs = new Object[] {currentEvent, offsetTime, dateString};
db.execSQL(sql, bindArgs);
}
})
.setNegativeButton("Discard", null).show();
}
break;
case stop:
state = State.reset;
timerText.setText("0'00\"00");
offsetTime = 0;
break;
default:
break;
}
updateButton();
}
});
updateButton();
return v;
}
|
diff --git a/src/main/java/com/viaplay/jcurl/JCurl.java b/src/main/java/com/viaplay/jcurl/JCurl.java
index b9fc605..fdfa9d7 100644
--- a/src/main/java/com/viaplay/jcurl/JCurl.java
+++ b/src/main/java/com/viaplay/jcurl/JCurl.java
@@ -1,367 +1,367 @@
package com.viaplay.jcurl;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URLConnection;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.viaplay.jcurl.exception.JCurlFileNotFoundException;
import com.viaplay.jcurl.exception.JCurlIOException;
import com.viaplay.jcurl.exception.JCurlMalformedURLException;
import com.viaplay.jcurl.exception.JCurlSocketTimeoutException;
/**
* JCurl is a simple yet powerful resource getter that works very much like the curl command line tool we all have used
* and learned to love. In its simplest form it fetches data from an entered url and return that data in a form of a
* String for further processing or direct use.
*
* @author [email protected]
*
*/
public class JCurl {
/**
* The head request does only fetch the status of an resource without transmitting any pay-load.
*
* @param urlAsString
* The url in String form to the wanted resource.
* @return a filled in JCurlResponse object.
*/
public static JCurlResponse head(String urlAsString) {
JCurlRequest request = new JCurlRequest(urlAsString);
return head(request);
}
public static JCurlResponse head(String urlAsString, JCurlCookieManager jCurlCookieManager) {
JCurlRequest request = new JCurlRequest(urlAsString, jCurlCookieManager);
return head(request);
}
/**
* The head request does only fetch the status of an resource without transmitting any pay-load.
*
* @param request
* A populated JCurlRequest object to the wanted resource.
* @return a filled in JCurlResponse object.
*/
public static JCurlResponse head(JCurlRequest request) {
JCurlResponse response = new JCurlResponse();
request.setMethod(JCurlRequest.HEAD);
request.setPayload(null);
doHttpCall(request, response);
return response;
}
public static JCurlResponse head(JCurlRequest request, JCurlCookieManager jCurlCookieManager) {
request.setCookieManager(jCurlCookieManager);
JCurlResponse response = new JCurlResponse(jCurlCookieManager);
request.setMethod(JCurlRequest.HEAD);
request.setPayload(null);
doHttpCall(request, response);
return response;
}
/**
* The get request is the type of request that a web browser does when it fetches a web page and other resources
* like an image.
*
* @param urlAsString
* The url in String form to the wanted resource.
* @return a filled in JCurlResponse object.
*/
public static JCurlResponse get(String urlAsString) {
JCurlRequest request = new JCurlRequest(urlAsString);
return get(request);
}
public static JCurlResponse get(String urlAsString, JCurlCookieManager jCurlCookieManager) {
JCurlRequest request = new JCurlRequest(urlAsString);
return get(request, jCurlCookieManager);
}
/**
* The get request is the type of request that a web browser does when it fetches a web page and other resources
* like an image.
*
* @param request
* A populated JCurlRequest object to the wanted resource.
* @return a filled in JCurlResponse object.
*/
public static JCurlResponse get(JCurlRequest request) {
JCurlResponse response = new JCurlResponse();
request.setPayload(null);
doHttpCall(request, response);
return response;
}
public static JCurlResponse get(JCurlRequest request, JCurlCookieManager jCurlCookieManager) {
request.setCookieManager(jCurlCookieManager);
JCurlResponse response = new JCurlResponse(jCurlCookieManager);
request.setPayload(null);
doHttpCall(request, response);
return response;
}
/**
* The put request is an important request when dealing with RESTful web services.
*
* @param urlAsString
* The url in String form to the wanted resource.
* @param payload
* @return a filled in JCurlResponse object.
*/
public static JCurlResponse put(String urlAsString, String payload) {
JCurlRequest request = new JCurlRequest(urlAsString);
request.setPayload(payload);
return put(request);
}
public static JCurlResponse put(String urlAsString, String payload, JCurlCookieManager jCurlCookieManager) {
JCurlRequest request = new JCurlRequest(urlAsString);
request.setPayload(payload);
return put(request, jCurlCookieManager);
}
/**
* The put request is an important request when dealing with RESTful web services.
*
* @param request
* A populated JCurlRequest object to the wanted resource.
* @return a filled in JCurlResponse object.
*/
public static JCurlResponse put(JCurlRequest request) {
JCurlResponse response = new JCurlResponse();
request.setMethod(JCurlRequest.PUT);
doHttpCall(request, response);
return response;
}
public static JCurlResponse put(JCurlRequest request, JCurlCookieManager jCurlCookieManager) {
request.setCookieManager(jCurlCookieManager);
JCurlResponse response = new JCurlResponse(jCurlCookieManager);
request.setMethod(JCurlRequest.PUT);
doHttpCall(request, response);
return response;
}
/**
* The post request is the type of request a web server does when a html form is submitted.
*
* @param urlAsString
* The url in String form to the wanted resource.
* @param payload
* @return a filled in JCurlResponse object.
*/
public static JCurlResponse post(String urlAsString, String payload) {
JCurlRequest request = new JCurlRequest(urlAsString);
request.setPayload(payload);
return post(request);
}
public static JCurlResponse post(String urlAsString, String payload, JCurlCookieManager jCurlCookieManager) {
JCurlRequest request = new JCurlRequest(urlAsString);
request.setPayload(payload);
return post(request, jCurlCookieManager);
}
/**
* The post request is the type of request a web server does when a html form is submitted.
*
* @param request
* A populated JCurlRequest object to the wanted resource.
* @return a filled in JCurlResponse object.
*/
public static JCurlResponse post(JCurlRequest request) {
JCurlResponse response = new JCurlResponse();
request.setMethod(JCurlRequest.POST);
doHttpCall(request, response);
return response;
}
public static JCurlResponse post(JCurlRequest request, JCurlCookieManager jCurlCookieManager) {
request.setCookieManager(jCurlCookieManager);
JCurlResponse response = new JCurlResponse(jCurlCookieManager);
request.setMethod(JCurlRequest.POST);
doHttpCall(request, response);
return response;
}
/**
* The delete request is an important request when dealing with RESTful web services. Beware that this request will
* delete an resource if the request is successful.
*
* @param urlAsString
* The url in String form to the wanted resource.
* @return a filled in JCurlResponse object.
*/
public static JCurlResponse delete(String urlAsString) {
JCurlRequest request = new JCurlRequest(urlAsString);
return delete(request);
}
public static JCurlResponse delete(String urlAsString, JCurlCookieManager jCurlCookieManager) {
JCurlRequest request = new JCurlRequest(urlAsString);
return delete(request, jCurlCookieManager);
}
/**
* The delete request is an important request when dealing with RESTful web services. Beware that this request will
* delete an resource if the request is successful.
*
* @param request
* A populated JCurlRequest object to the wanted resource.
* @return a filled in JCurlResponse object.
*/
public static JCurlResponse delete(JCurlRequest request) {
JCurlResponse response = new JCurlResponse();
request.setMethod(JCurlRequest.DELETE);
request.setPayload(null);
doHttpCall(request, response);
return response;
}
public static JCurlResponse delete(JCurlRequest request, JCurlCookieManager jCurlCookieManager) {
request.setCookieManager(jCurlCookieManager);
JCurlResponse response = new JCurlResponse(jCurlCookieManager);
request.setMethod(JCurlRequest.DELETE);
request.setPayload(null);
doHttpCall(request, response);
return response;
}
/**
* This method does the actual communication to simplify the methods above.
*
* @param request
* A populated JCurlRequest object to the wanted resource.
* @param response
* An instantiated JCurlResponse object.
*/
private static void doHttpCall(JCurlRequest request, JCurlResponse response) {
Logger log = LoggerFactory.getLogger(JCurl.class);
StringBuffer result = new StringBuffer();
URLConnection urlConnection = null;
response.setRequestObject(request);
request.updateCookies();
try {
urlConnection = (URLConnection) request.getURL().openConnection();
urlConnection.setDoInput(true);
if (urlConnection instanceof HttpURLConnection) {
((HttpURLConnection) urlConnection).setRequestMethod(request.getMethod());
}
urlConnection.setConnectTimeout(request.getTimeOutMillis());
urlConnection.setReadTimeout(request.getTimeOutMillis());
if (request.getURL().getUserInfo() != null) {
String basicAuth = "Basic "
+ new String(new Base64().encode(request.getURL().getUserInfo().getBytes()));
urlConnection.setRequestProperty("Authorization", basicAuth);
}
urlConnection.setRequestProperty("Content-Length", "0");
for (String key : request.getProperties().keySet()) {
urlConnection.setRequestProperty(key, request.getProperties().get(key));
}
if (request.hasPayload()) {
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Length",
- "" + request.getPayload().getBytes(request.getCharsetName()));
+ "" + request.getPayload().getBytes(request.getCharsetName()).length);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream(),
request.getCharsetName());
outputStreamWriter.write(request.getPayload());
outputStreamWriter.close();
}
response.updateFromUrlConnection(urlConnection);
readInputStream(result, urlConnection.getInputStream(), request.getCharsetName());
} catch (SocketTimeoutException e) {
response.setResponseCodeAndMessage(408, "The socket connection timed out.");
log.error("The socket timed out after {} milliseconds.", request.getTimeOutMillis());
if (request.isExceptionsToBeThrown())
throw new JCurlSocketTimeoutException(e);
} catch (RuntimeException e) {
response.setResponseCodeAndMessage(500, "Internal server error.");
log.error(e.getMessage());
if (request.isExceptionsToBeThrown())
throw e;
} catch (MalformedURLException e) {
response.setResponseCodeAndMessage(400, "The url is malformed.");
log.error("The url '{}' is malformed.", request.getUrlAsString());
if (request.isExceptionsToBeThrown())
throw new JCurlMalformedURLException(e);
} catch (IOException e) {
if (urlConnection instanceof HttpURLConnection) {
try {
readInputStream(result, ((HttpURLConnection) urlConnection).getErrorStream(),
request.getCharsetName());
} catch (IOException e1) {
if (response.getResponseCode() < 0) {
response.setResponseCodeAndMessage(500, "Internal server error.");
}
if (request.isExceptionsToBeThrown()) {
if (e instanceof FileNotFoundException) {
throw new JCurlFileNotFoundException(e);
} else {
throw new JCurlIOException(e);
}
}
}
} else {
response.setResponseCodeAndMessage(404, "Not Found.");
if (request.isExceptionsToBeThrown())
throw new JCurlFileNotFoundException(e);
}
} finally {
if (urlConnection != null && urlConnection instanceof HttpURLConnection) {
((HttpURLConnection) urlConnection).disconnect();
}
}
response.setResponseString(result);
}
/**
* Local helper method that reads data from an input stream.
*
* @param result
* The read text.
* @param inputStream
* The stream to read.
* @param charsetName
* The name of the char-set to be used to convert the read pay-load.
* @throws UnsupportedEncodingException
* @throws IOException
*/
private static void readInputStream(StringBuffer result, InputStream inputStream, String charsetName)
throws UnsupportedEncodingException, IOException {
if (inputStream == null)
throw new IOException("No working inputStream.");
InputStreamReader streamReader = new InputStreamReader(inputStream, charsetName);
BufferedReader bufferedReader = new BufferedReader(streamReader);
String row;
while ((row = bufferedReader.readLine()) != null) {
result.append(row);
result.append("\n");
}
bufferedReader.close();
streamReader.close();
}
}
| true | true | private static void doHttpCall(JCurlRequest request, JCurlResponse response) {
Logger log = LoggerFactory.getLogger(JCurl.class);
StringBuffer result = new StringBuffer();
URLConnection urlConnection = null;
response.setRequestObject(request);
request.updateCookies();
try {
urlConnection = (URLConnection) request.getURL().openConnection();
urlConnection.setDoInput(true);
if (urlConnection instanceof HttpURLConnection) {
((HttpURLConnection) urlConnection).setRequestMethod(request.getMethod());
}
urlConnection.setConnectTimeout(request.getTimeOutMillis());
urlConnection.setReadTimeout(request.getTimeOutMillis());
if (request.getURL().getUserInfo() != null) {
String basicAuth = "Basic "
+ new String(new Base64().encode(request.getURL().getUserInfo().getBytes()));
urlConnection.setRequestProperty("Authorization", basicAuth);
}
urlConnection.setRequestProperty("Content-Length", "0");
for (String key : request.getProperties().keySet()) {
urlConnection.setRequestProperty(key, request.getProperties().get(key));
}
if (request.hasPayload()) {
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Length",
"" + request.getPayload().getBytes(request.getCharsetName()));
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream(),
request.getCharsetName());
outputStreamWriter.write(request.getPayload());
outputStreamWriter.close();
}
response.updateFromUrlConnection(urlConnection);
readInputStream(result, urlConnection.getInputStream(), request.getCharsetName());
} catch (SocketTimeoutException e) {
response.setResponseCodeAndMessage(408, "The socket connection timed out.");
log.error("The socket timed out after {} milliseconds.", request.getTimeOutMillis());
if (request.isExceptionsToBeThrown())
throw new JCurlSocketTimeoutException(e);
} catch (RuntimeException e) {
response.setResponseCodeAndMessage(500, "Internal server error.");
log.error(e.getMessage());
if (request.isExceptionsToBeThrown())
throw e;
} catch (MalformedURLException e) {
response.setResponseCodeAndMessage(400, "The url is malformed.");
log.error("The url '{}' is malformed.", request.getUrlAsString());
if (request.isExceptionsToBeThrown())
throw new JCurlMalformedURLException(e);
} catch (IOException e) {
if (urlConnection instanceof HttpURLConnection) {
try {
readInputStream(result, ((HttpURLConnection) urlConnection).getErrorStream(),
request.getCharsetName());
} catch (IOException e1) {
if (response.getResponseCode() < 0) {
response.setResponseCodeAndMessage(500, "Internal server error.");
}
if (request.isExceptionsToBeThrown()) {
if (e instanceof FileNotFoundException) {
throw new JCurlFileNotFoundException(e);
} else {
throw new JCurlIOException(e);
}
}
}
} else {
response.setResponseCodeAndMessage(404, "Not Found.");
if (request.isExceptionsToBeThrown())
throw new JCurlFileNotFoundException(e);
}
} finally {
if (urlConnection != null && urlConnection instanceof HttpURLConnection) {
((HttpURLConnection) urlConnection).disconnect();
}
}
response.setResponseString(result);
}
| private static void doHttpCall(JCurlRequest request, JCurlResponse response) {
Logger log = LoggerFactory.getLogger(JCurl.class);
StringBuffer result = new StringBuffer();
URLConnection urlConnection = null;
response.setRequestObject(request);
request.updateCookies();
try {
urlConnection = (URLConnection) request.getURL().openConnection();
urlConnection.setDoInput(true);
if (urlConnection instanceof HttpURLConnection) {
((HttpURLConnection) urlConnection).setRequestMethod(request.getMethod());
}
urlConnection.setConnectTimeout(request.getTimeOutMillis());
urlConnection.setReadTimeout(request.getTimeOutMillis());
if (request.getURL().getUserInfo() != null) {
String basicAuth = "Basic "
+ new String(new Base64().encode(request.getURL().getUserInfo().getBytes()));
urlConnection.setRequestProperty("Authorization", basicAuth);
}
urlConnection.setRequestProperty("Content-Length", "0");
for (String key : request.getProperties().keySet()) {
urlConnection.setRequestProperty(key, request.getProperties().get(key));
}
if (request.hasPayload()) {
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Length",
"" + request.getPayload().getBytes(request.getCharsetName()).length);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream(),
request.getCharsetName());
outputStreamWriter.write(request.getPayload());
outputStreamWriter.close();
}
response.updateFromUrlConnection(urlConnection);
readInputStream(result, urlConnection.getInputStream(), request.getCharsetName());
} catch (SocketTimeoutException e) {
response.setResponseCodeAndMessage(408, "The socket connection timed out.");
log.error("The socket timed out after {} milliseconds.", request.getTimeOutMillis());
if (request.isExceptionsToBeThrown())
throw new JCurlSocketTimeoutException(e);
} catch (RuntimeException e) {
response.setResponseCodeAndMessage(500, "Internal server error.");
log.error(e.getMessage());
if (request.isExceptionsToBeThrown())
throw e;
} catch (MalformedURLException e) {
response.setResponseCodeAndMessage(400, "The url is malformed.");
log.error("The url '{}' is malformed.", request.getUrlAsString());
if (request.isExceptionsToBeThrown())
throw new JCurlMalformedURLException(e);
} catch (IOException e) {
if (urlConnection instanceof HttpURLConnection) {
try {
readInputStream(result, ((HttpURLConnection) urlConnection).getErrorStream(),
request.getCharsetName());
} catch (IOException e1) {
if (response.getResponseCode() < 0) {
response.setResponseCodeAndMessage(500, "Internal server error.");
}
if (request.isExceptionsToBeThrown()) {
if (e instanceof FileNotFoundException) {
throw new JCurlFileNotFoundException(e);
} else {
throw new JCurlIOException(e);
}
}
}
} else {
response.setResponseCodeAndMessage(404, "Not Found.");
if (request.isExceptionsToBeThrown())
throw new JCurlFileNotFoundException(e);
}
} finally {
if (urlConnection != null && urlConnection instanceof HttpURLConnection) {
((HttpURLConnection) urlConnection).disconnect();
}
}
response.setResponseString(result);
}
|
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/util/FS_POSIX.java b/org.eclipse.jgit/src/org/eclipse/jgit/util/FS_POSIX.java
index e6959631..14fac15d 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/util/FS_POSIX.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/util/FS_POSIX.java
@@ -1,97 +1,102 @@
/*
* Copyright (C) 2010, Robin Rosenberg
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.eclipse.jgit.util;
import java.io.File;
import java.nio.charset.Charset;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
abstract class FS_POSIX extends FS {
@Override
public File gitPrefix() {
String path = SystemReader.getInstance().getenv("PATH");
File gitExe = searchPath(path, "git");
if (gitExe != null)
return gitExe.getParentFile().getParentFile();
if (isMacOS()) {
// On MacOSX, PATH is shorter when Eclipse is launched from the
// Finder than from a terminal. Therefore try to launch bash as a
// login shell and search using that.
//
String w = readPipe(userHome(), //
new String[] { "bash", "--login", "-c", "which git" }, //
Charset.defaultCharset().name());
- return new File(w).getParentFile().getParentFile();
+ if (w == null || w.length() == 0)
+ return null;
+ File parentFile = new File(w).getParentFile();
+ if (parentFile == null)
+ return null;
+ return parentFile.getParentFile();
}
return null;
}
@Override
public ProcessBuilder runInShell(String cmd, String[] args) {
List<String> argv = new ArrayList<String>(4 + args.length);
argv.add("sh");
argv.add("-c");
argv.add(cmd + " \"$@\"");
argv.add(cmd);
argv.addAll(Arrays.asList(args));
ProcessBuilder proc = new ProcessBuilder();
proc.command(argv);
return proc;
}
private static boolean isMacOS() {
final String osDotName = AccessController
.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return System.getProperty("os.name");
}
});
return "Mac OS X".equals(osDotName);
}
}
| true | true | public File gitPrefix() {
String path = SystemReader.getInstance().getenv("PATH");
File gitExe = searchPath(path, "git");
if (gitExe != null)
return gitExe.getParentFile().getParentFile();
if (isMacOS()) {
// On MacOSX, PATH is shorter when Eclipse is launched from the
// Finder than from a terminal. Therefore try to launch bash as a
// login shell and search using that.
//
String w = readPipe(userHome(), //
new String[] { "bash", "--login", "-c", "which git" }, //
Charset.defaultCharset().name());
return new File(w).getParentFile().getParentFile();
}
return null;
}
| public File gitPrefix() {
String path = SystemReader.getInstance().getenv("PATH");
File gitExe = searchPath(path, "git");
if (gitExe != null)
return gitExe.getParentFile().getParentFile();
if (isMacOS()) {
// On MacOSX, PATH is shorter when Eclipse is launched from the
// Finder than from a terminal. Therefore try to launch bash as a
// login shell and search using that.
//
String w = readPipe(userHome(), //
new String[] { "bash", "--login", "-c", "which git" }, //
Charset.defaultCharset().name());
if (w == null || w.length() == 0)
return null;
File parentFile = new File(w).getParentFile();
if (parentFile == null)
return null;
return parentFile.getParentFile();
}
return null;
}
|
diff --git a/api/src/main/java/org/openmrs/module/emr/account/AccountServiceImpl.java b/api/src/main/java/org/openmrs/module/emr/account/AccountServiceImpl.java
index 7607f286..16b214d2 100644
--- a/api/src/main/java/org/openmrs/module/emr/account/AccountServiceImpl.java
+++ b/api/src/main/java/org/openmrs/module/emr/account/AccountServiceImpl.java
@@ -1,267 +1,267 @@
package org.openmrs.module.emr.account;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.openmrs.Person;
import org.openmrs.Privilege;
import org.openmrs.Provider;
import org.openmrs.Role;
import org.openmrs.User;
import org.openmrs.api.APIException;
import org.openmrs.api.PersonService;
import org.openmrs.api.ProviderService;
import org.openmrs.api.UserService;
import org.openmrs.api.context.Context;
import org.openmrs.api.impl.BaseOpenmrsService;
import org.openmrs.module.emr.EmrConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class AccountServiceImpl extends BaseOpenmrsService implements AccountService {
@Autowired
private UserService userService;
@Autowired
private ProviderService providerService;
@Autowired
private PersonService personService;
/**
* @param userService the userService to set
*/
public void setUserService(UserService userService) {
this.userService = userService;
}
/**
* @param providerService the providerService to set
*/
public void setProviderService(ProviderService providerService) {
this.providerService = providerService;
}
/**
* @param personService the personService to set
*/
public void setPersonService(PersonService personService) {
this.personService = personService;
}
/**
* @see org.openmrs.module.emr.account.AccountService#getAllAccounts()
*/
@Override
@Transactional(readOnly = true)
public List<Account> getAllAccounts() {
Map<Person, Account> byPerson = new LinkedHashMap<Person, Account>();
for (User user : userService.getAllUsers()) {
//exclude daemon user
if (EmrConstants.DAEMON_USER_UUID.equals(user.getUuid()))
continue;
Provider provider = getProviderByPerson(user.getPerson());
byPerson.put(user.getPerson(), new Account(user, provider));
}
for (Provider provider : providerService.getAllProviders()) {
if (provider.getPerson() == null)
throw new APIException("Providers not associated to a person are not supported");
Account account = byPerson.get(provider.getPerson());
if (account == null) {
User user = getUserByPerson(provider.getPerson());
byPerson.put(provider.getPerson(), new Account(user, provider));
}
}
List<Account> accounts = new ArrayList<Account>();
for (Account account : byPerson.values()) {
accounts.add(account);
}
return accounts;
}
/**
* @see org.openmrs.module.emr.account.AccountService#saveAccount(org.openmrs.module.emr.account.Account)
*/
public Account saveAccount(Account account) {
//account.syncProperties();//This is not necessary since the validator calls it
account.setPerson(personService.savePerson(account.getPerson()));
if (account.getUser() != null) {
User user = account.getUser();
//only include capabilities and privilege level set on the account
if (user.getRoles() != null) {
//TODO Figure out how to unset inherited roles
user.getRoles().removeAll(getAllPrivilegeLevels());
user.getRoles().removeAll(getAllCapabilities());
}
if (account.getPrivilegeLevel() != null && !user.hasRole(account.getPrivilegeLevel().getRole()))
user.addRole(account.getPrivilegeLevel());
for (Role capability : account.getCapabilities()) {
user.addRole(capability);
}
if (user.isRetired())
user.setRetireReason(Context.getMessageSourceService().getMessage("general.default.retireReason"));
String password = null;
if (StringUtils.isNotBlank(account.getPassword()))
password = account.getPassword();
account.setUser(userService.saveUser(user, password));
String secretQuestion = null;
String secretAnswer = null;
if (StringUtils.isNotBlank(account.getSecretQuestion()))
secretQuestion = account.getSecretQuestion();
if (StringUtils.isNotBlank(account.getSecretAnswer()))
secretAnswer = account.getSecretAnswer();
//If the we have no question, always clear the answer
if (secretQuestion == null)
secretAnswer = null;
if (secretQuestion == null || (secretQuestion != null && secretAnswer != null)) {
- userService.changeQuestionAnswer(user, account.getSecretQuestion(), account.getSecretAnswer());
+ userService.changeQuestionAnswer(user, secretQuestion, secretAnswer);
}
}
if (account.getProvider() != null) {
Provider provider = account.getProvider();
if (provider.isRetired())
provider.setRetireReason(Context.getMessageSourceService().getMessage("general.default.retireReason"));
account.setProvider(providerService.saveProvider(provider));
}
return account;
}
/**
* @see org.openmrs.module.emr.account.AccountService#getAccount(java.lang.Integer)
*/
@Override
@Transactional(readOnly = true)
public Account getAccount(Integer personId) {
return getAccountByPerson(personService.getPerson(personId));
}
/**
* @see org.openmrs.module.emr.account.AccountService#getAccountByPerson(org.openmrs.Person)
*/
@Override
@Transactional(readOnly = true)
public Account getAccountByPerson(Person person) {
return new Account(getUserByPerson(person), getProviderByPerson(person));
}
/**
* @see org.openmrs.module.emr.account.AccountService#getAllCapabilities()
*/
@Override
@Transactional(readOnly = true)
public List<Role> getAllCapabilities() {
List<Role> capabilities = new ArrayList<Role>();
for (Role candidate : userService.getAllRoles()) {
if (candidate.getName().startsWith(EmrConstants.ROLE_PREFIX_CAPABILITY))
capabilities.add(candidate);
}
return capabilities;
}
/**
* @see org.openmrs.module.emr.account.AccountService#getAllPrivilegeLevels()
*/
@Override
@Transactional(readOnly = true)
public List<Role> getAllPrivilegeLevels() {
List<Role> privilegeLevels = new ArrayList<Role>();
for (Role candidate : userService.getAllRoles()) {
if (candidate.getName().startsWith(EmrConstants.ROLE_PREFIX_PRIVILEGE_LEVEL))
privilegeLevels.add(candidate);
}
return privilegeLevels;
}
@Override
public List<Privilege> getApiPrivileges() {
List<Privilege> privileges = new ArrayList<Privilege>();
for (Privilege candidate : userService.getAllPrivileges()) {
if (!isApplicationPrivilege(candidate)) {
privileges.add(candidate);
}
}
return privileges;
}
@Override
public List<Privilege> getApplicationPrivileges() {
List<Privilege> privileges = new ArrayList<Privilege>();
for (Privilege candidate : userService.getAllPrivileges()) {
if (isApplicationPrivilege(candidate)) {
privileges.add(candidate);
}
}
return privileges;
}
private boolean isApplicationPrivilege(Privilege privilege) {
return privilege.getPrivilege().startsWith(EmrConstants.PRIVILEGE_PREFIX_APP)
|| privilege.getPrivilege().startsWith(EmrConstants.PRIVILEGE_PREFIX_TASK);
}
private User getUserByPerson(Person person) {
User user = null;
List<User> users = userService.getUsersByPerson(person, false);
//exclude daemon user
for (Iterator<User> i = users.iterator(); i.hasNext();) {
User candidate = i.next();
if (EmrConstants.DAEMON_USER_UUID.equals(candidate.getUuid())) {
i.remove();
break;
}
}
//return a retired account if they have none
if (users.size() == 0)
users = userService.getUsersByPerson(person, true);
if (users.size() == 1)
user = users.get(0);
else if (users.size() > 1)
throw new APIException("Found multiple users associated to the person with id: " + person.getPersonId());
return user;
}
private Provider getProviderByPerson(Person person) {
Provider provider = null;
Collection<Provider> providers = providerService.getProvidersByPerson(person, false);
for (Iterator<Provider> i = providers.iterator(); i.hasNext();) {
Provider candidate = i.next();
if (EmrConstants.DAEMON_USER_UUID.equals(candidate.getUuid())) {
i.remove();
break;
}
}
//see if they have a retired account
if (providers.size() == 0)
providers = providerService.getProvidersByPerson(person, true);
if (providers.size() == 1)
provider = providers.iterator().next();
else if (providers.size() > 1)
throw new APIException("Found multiple providers associated to the person with id: " + person.getPersonId());
return provider;
}
}
| true | true | public Account saveAccount(Account account) {
//account.syncProperties();//This is not necessary since the validator calls it
account.setPerson(personService.savePerson(account.getPerson()));
if (account.getUser() != null) {
User user = account.getUser();
//only include capabilities and privilege level set on the account
if (user.getRoles() != null) {
//TODO Figure out how to unset inherited roles
user.getRoles().removeAll(getAllPrivilegeLevels());
user.getRoles().removeAll(getAllCapabilities());
}
if (account.getPrivilegeLevel() != null && !user.hasRole(account.getPrivilegeLevel().getRole()))
user.addRole(account.getPrivilegeLevel());
for (Role capability : account.getCapabilities()) {
user.addRole(capability);
}
if (user.isRetired())
user.setRetireReason(Context.getMessageSourceService().getMessage("general.default.retireReason"));
String password = null;
if (StringUtils.isNotBlank(account.getPassword()))
password = account.getPassword();
account.setUser(userService.saveUser(user, password));
String secretQuestion = null;
String secretAnswer = null;
if (StringUtils.isNotBlank(account.getSecretQuestion()))
secretQuestion = account.getSecretQuestion();
if (StringUtils.isNotBlank(account.getSecretAnswer()))
secretAnswer = account.getSecretAnswer();
//If the we have no question, always clear the answer
if (secretQuestion == null)
secretAnswer = null;
if (secretQuestion == null || (secretQuestion != null && secretAnswer != null)) {
userService.changeQuestionAnswer(user, account.getSecretQuestion(), account.getSecretAnswer());
}
}
if (account.getProvider() != null) {
Provider provider = account.getProvider();
if (provider.isRetired())
provider.setRetireReason(Context.getMessageSourceService().getMessage("general.default.retireReason"));
account.setProvider(providerService.saveProvider(provider));
}
return account;
}
| public Account saveAccount(Account account) {
//account.syncProperties();//This is not necessary since the validator calls it
account.setPerson(personService.savePerson(account.getPerson()));
if (account.getUser() != null) {
User user = account.getUser();
//only include capabilities and privilege level set on the account
if (user.getRoles() != null) {
//TODO Figure out how to unset inherited roles
user.getRoles().removeAll(getAllPrivilegeLevels());
user.getRoles().removeAll(getAllCapabilities());
}
if (account.getPrivilegeLevel() != null && !user.hasRole(account.getPrivilegeLevel().getRole()))
user.addRole(account.getPrivilegeLevel());
for (Role capability : account.getCapabilities()) {
user.addRole(capability);
}
if (user.isRetired())
user.setRetireReason(Context.getMessageSourceService().getMessage("general.default.retireReason"));
String password = null;
if (StringUtils.isNotBlank(account.getPassword()))
password = account.getPassword();
account.setUser(userService.saveUser(user, password));
String secretQuestion = null;
String secretAnswer = null;
if (StringUtils.isNotBlank(account.getSecretQuestion()))
secretQuestion = account.getSecretQuestion();
if (StringUtils.isNotBlank(account.getSecretAnswer()))
secretAnswer = account.getSecretAnswer();
//If the we have no question, always clear the answer
if (secretQuestion == null)
secretAnswer = null;
if (secretQuestion == null || (secretQuestion != null && secretAnswer != null)) {
userService.changeQuestionAnswer(user, secretQuestion, secretAnswer);
}
}
if (account.getProvider() != null) {
Provider provider = account.getProvider();
if (provider.isRetired())
provider.setRetireReason(Context.getMessageSourceService().getMessage("general.default.retireReason"));
account.setProvider(providerService.saveProvider(provider));
}
return account;
}
|
diff --git a/src/com/android/bluetooth/opp/BluetoothOppReceiver.java b/src/com/android/bluetooth/opp/BluetoothOppReceiver.java
index 6364e1c..bf7d65b 100644
--- a/src/com/android/bluetooth/opp/BluetoothOppReceiver.java
+++ b/src/com/android/bluetooth/opp/BluetoothOppReceiver.java
@@ -1,288 +1,295 @@
/*
* Copyright (c) 2008-2009, Motorola, Inc.
* Copyright (c) 2010-2012, The Linux Foundation. All rights reserved.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of the Motorola, Inc. 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 HOLDER 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.android.bluetooth.opp;
import com.android.bluetooth.R;
import android.app.NotificationManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothDevicePicker;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;
/**
* Receives and handles: system broadcasts; Intents from other applications;
* Intents from OppService; Intents from modules in Opp application layer.
*/
public class BluetoothOppReceiver extends BroadcastReceiver {
private static final String TAG = "BluetoothOppReceiver";
private static final boolean D = Constants.DEBUG;
private static final boolean V = Constants.VERBOSE;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
if (BluetoothAdapter.STATE_ON == intent.getIntExtra(
BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {
if (V) Log.v(TAG, "Received BLUETOOTH_STATE_CHANGED_ACTION, BLUETOOTH_STATE_ON");
context.startService(new Intent(context, BluetoothOppService.class));
// If this is within a sending process, continue the handle
// logic to display device picker dialog.
synchronized (this) {
if (BluetoothOppManager.getInstance(context).mSendingFlag) {
// reset the flags
BluetoothOppManager.getInstance(context).mSendingFlag = false;
Intent in1 = new Intent(BluetoothDevicePicker.ACTION_LAUNCH);
in1.putExtra(BluetoothDevicePicker.EXTRA_NEED_AUTH, false);
in1.putExtra(BluetoothDevicePicker.EXTRA_FILTER_TYPE,
BluetoothDevicePicker.FILTER_TYPE_TRANSFER);
in1.putExtra(BluetoothDevicePicker.EXTRA_LAUNCH_PACKAGE,
Constants.THIS_PACKAGE_NAME);
in1.putExtra(BluetoothDevicePicker.EXTRA_LAUNCH_CLASS,
BluetoothOppReceiver.class.getName());
in1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(in1);
}
}
}
+ } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
+ if (V) Log.v(TAG, "Received ACTION_ACL_DISCONNECTED");
+ // Don't forward intent unless device has bluetooth and bluetooth is enabled.
+ BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
+ if (adapter != null && adapter.isEnabled()) {
+ context.startService(new Intent(context, BluetoothOppService.class));
+ }
} else if (action.equals(BluetoothDevicePicker.ACTION_DEVICE_SELECTED)) {
BluetoothOppManager mOppManager = BluetoothOppManager.getInstance(context);
BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (V) Log.v(TAG, "Received BT device selected intent, bt device: " + remoteDevice);
// Insert transfer session record to database
mOppManager.startTransfer(remoteDevice);
// Display toast message
String deviceName = remoteDevice.getName();
String toastMsg;
int batchSize = mOppManager.getBatchSize();
if (mOppManager.mMultipleFlag) {
toastMsg = context.getString(R.string.bt_toast_5, Integer.toString(batchSize),
deviceName);
} else {
toastMsg = context.getString(R.string.bt_toast_4, deviceName);
}
Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show();
} else if (action.equals(Constants.ACTION_INCOMING_FILE_CONFIRM)) {
if (V) Log.v(TAG, "Receiver ACTION_INCOMING_FILE_CONFIRM");
Uri uri = intent.getData();
Intent in = new Intent(context, BluetoothOppIncomingFileConfirmActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.setData(uri);
context.startActivity(in);
NotificationManager notMgr = (NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
if (notMgr != null) {
notMgr.cancel((int)ContentUris.parseId(intent.getData()));
if (V) Log.v(TAG, "notMgr.cancel called");
}
} else if (action.equals(BluetoothShare.INCOMING_FILE_CONFIRMATION_REQUEST_ACTION)) {
if (V) Log.v(TAG, "Receiver INCOMING_FILE_NOTIFICATION");
Toast.makeText(context, context.getString(R.string.incoming_file_toast_msg),
Toast.LENGTH_SHORT).show();
} else if (action.equals(Constants.ACTION_OPEN) || action.equals(Constants.ACTION_LIST)) {
if (V) {
if (action.equals(Constants.ACTION_OPEN)) {
Log.v(TAG, "Receiver open for " + intent.getData());
} else {
Log.v(TAG, "Receiver list for " + intent.getData());
}
}
BluetoothOppTransferInfo transInfo = new BluetoothOppTransferInfo();
Uri uri = intent.getData();
transInfo = BluetoothOppUtility.queryRecord(context, uri);
if (transInfo == null) {
Log.e(TAG, "Error: Can not get data from db");
return;
}
if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND
&& BluetoothShare.isStatusSuccess(transInfo.mStatus)) {
// if received file successfully, open this file
BluetoothOppUtility.openReceivedFile(context, transInfo.mFileName,
transInfo.mFileType, transInfo.mTimeStamp, uri);
BluetoothOppUtility.updateVisibilityToHidden(context, uri);
} else {
Intent in = new Intent(context, BluetoothOppTransferActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.setData(uri);
context.startActivity(in);
}
NotificationManager notMgr = (NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
if (notMgr != null) {
notMgr.cancel((int)ContentUris.parseId(intent.getData()));
if (V) Log.v(TAG, "notMgr.cancel called");
}
} else if (action.equals(Constants.ACTION_OPEN_OUTBOUND_TRANSFER)) {
if (V) Log.v(TAG, "Received ACTION_OPEN_OUTBOUND_TRANSFER.");
Intent in = new Intent(context, BluetoothOppTransferHistory.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
in.putExtra("direction", BluetoothShare.DIRECTION_OUTBOUND);
context.startActivity(in);
} else if (action.equals(Constants.ACTION_OPEN_INBOUND_TRANSFER)) {
if (V) Log.v(TAG, "Received ACTION_OPEN_INBOUND_TRANSFER.");
Intent in = new Intent(context, BluetoothOppTransferHistory.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
in.putExtra("direction", BluetoothShare.DIRECTION_INBOUND);
context.startActivity(in);
} else if (action.equals(Constants.ACTION_OPEN_RECEIVED_FILES)) {
if (V) Log.v(TAG, "Received ACTION_OPEN_RECEIVED_FILES.");
Intent in = new Intent(context, BluetoothOppTransferHistory.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
in.putExtra("direction", BluetoothShare.DIRECTION_INBOUND);
in.putExtra(Constants.EXTRA_SHOW_ALL_FILES, true);
context.startActivity(in);
} else if (action.equals(Constants.ACTION_HIDE)) {
if (V) Log.v(TAG, "Receiver hide for " + intent.getData());
Cursor cursor = context.getContentResolver().query(intent.getData(), null, null, null,
null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int statusColumn = cursor.getColumnIndexOrThrow(BluetoothShare.STATUS);
int status = cursor.getInt(statusColumn);
int visibilityColumn = cursor.getColumnIndexOrThrow(BluetoothShare.VISIBILITY);
int visibility = cursor.getInt(visibilityColumn);
int userConfirmationColumn = cursor
.getColumnIndexOrThrow(BluetoothShare.USER_CONFIRMATION);
int userConfirmation = cursor.getInt(userConfirmationColumn);
if (((userConfirmation == BluetoothShare.USER_CONFIRMATION_PENDING))
&& visibility == BluetoothShare.VISIBILITY_VISIBLE) {
ContentValues values = new ContentValues();
values.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN);
context.getContentResolver().update(intent.getData(), values, null, null);
if (V) Log.v(TAG, "Action_hide received and db updated");
}
}
cursor.close();
}
} else if (action.equals(Constants.ACTION_COMPLETE_HIDE)) {
if (V) Log.v(TAG, "Receiver ACTION_COMPLETE_HIDE");
ContentValues updateValues = new ContentValues();
updateValues.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN);
context.getContentResolver().update(BluetoothShare.CONTENT_URI, updateValues,
BluetoothOppNotification.WHERE_COMPLETED, null);
} else if (action.equals(BluetoothShare.TRANSFER_COMPLETED_ACTION)) {
if (V) Log.v(TAG, "Receiver Transfer Complete Intent for " + intent.getData());
String toastMsg = null;
BluetoothOppTransferInfo transInfo = new BluetoothOppTransferInfo();
transInfo = BluetoothOppUtility.queryRecord(context, intent.getData());
if (transInfo == null) {
Log.e(TAG, "Error: Can not get data from db");
return;
}
if (transInfo.mHandoverInitiated) {
// Deal with handover-initiated transfers separately
Intent handoverIntent = new Intent(Constants.ACTION_BT_OPP_TRANSFER_DONE);
if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND) {
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_DIRECTION,
Constants.DIRECTION_BLUETOOTH_INCOMING);
} else {
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_DIRECTION,
Constants.DIRECTION_BLUETOOTH_OUTGOING);
}
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_ID, transInfo.mID);
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_ADDRESS, transInfo.mDestAddr);
if (BluetoothShare.isStatusSuccess(transInfo.mStatus)) {
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_STATUS,
Constants.HANDOVER_TRANSFER_STATUS_SUCCESS);
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_URI,
transInfo.mFileName);
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_MIMETYPE,
transInfo.mFileType);
} else {
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_STATUS,
Constants.HANDOVER_TRANSFER_STATUS_FAILURE);
}
context.sendBroadcast(handoverIntent, Constants.HANDOVER_STATUS_PERMISSION);
return;
}
if (BluetoothShare.isStatusSuccess(transInfo.mStatus)) {
if (transInfo.mDirection == BluetoothShare.DIRECTION_OUTBOUND) {
toastMsg = context.getString(R.string.notification_sent, transInfo.mFileName);
} else if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND) {
toastMsg = context.getString(R.string.notification_received,
transInfo.mFileName);
}
} else if (BluetoothShare.isStatusError(transInfo.mStatus)) {
if (transInfo.mDirection == BluetoothShare.DIRECTION_OUTBOUND) {
toastMsg = context.getString(R.string.notification_sent_fail,
transInfo.mFileName);
} else if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND) {
toastMsg = context.getString(R.string.download_fail_line1);
}
}
if (Constants.ZERO_LENGTH_FILE) {
toastMsg = context.getString(R.string.empty_file_notification_sent, transInfo.mFileName);
}
if (V) Log.v(TAG, "Toast msg == " + toastMsg);
if (toastMsg != null) {
Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show();
}
}
}
}
| true | true | public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
if (BluetoothAdapter.STATE_ON == intent.getIntExtra(
BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {
if (V) Log.v(TAG, "Received BLUETOOTH_STATE_CHANGED_ACTION, BLUETOOTH_STATE_ON");
context.startService(new Intent(context, BluetoothOppService.class));
// If this is within a sending process, continue the handle
// logic to display device picker dialog.
synchronized (this) {
if (BluetoothOppManager.getInstance(context).mSendingFlag) {
// reset the flags
BluetoothOppManager.getInstance(context).mSendingFlag = false;
Intent in1 = new Intent(BluetoothDevicePicker.ACTION_LAUNCH);
in1.putExtra(BluetoothDevicePicker.EXTRA_NEED_AUTH, false);
in1.putExtra(BluetoothDevicePicker.EXTRA_FILTER_TYPE,
BluetoothDevicePicker.FILTER_TYPE_TRANSFER);
in1.putExtra(BluetoothDevicePicker.EXTRA_LAUNCH_PACKAGE,
Constants.THIS_PACKAGE_NAME);
in1.putExtra(BluetoothDevicePicker.EXTRA_LAUNCH_CLASS,
BluetoothOppReceiver.class.getName());
in1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(in1);
}
}
}
} else if (action.equals(BluetoothDevicePicker.ACTION_DEVICE_SELECTED)) {
BluetoothOppManager mOppManager = BluetoothOppManager.getInstance(context);
BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (V) Log.v(TAG, "Received BT device selected intent, bt device: " + remoteDevice);
// Insert transfer session record to database
mOppManager.startTransfer(remoteDevice);
// Display toast message
String deviceName = remoteDevice.getName();
String toastMsg;
int batchSize = mOppManager.getBatchSize();
if (mOppManager.mMultipleFlag) {
toastMsg = context.getString(R.string.bt_toast_5, Integer.toString(batchSize),
deviceName);
} else {
toastMsg = context.getString(R.string.bt_toast_4, deviceName);
}
Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show();
} else if (action.equals(Constants.ACTION_INCOMING_FILE_CONFIRM)) {
if (V) Log.v(TAG, "Receiver ACTION_INCOMING_FILE_CONFIRM");
Uri uri = intent.getData();
Intent in = new Intent(context, BluetoothOppIncomingFileConfirmActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.setData(uri);
context.startActivity(in);
NotificationManager notMgr = (NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
if (notMgr != null) {
notMgr.cancel((int)ContentUris.parseId(intent.getData()));
if (V) Log.v(TAG, "notMgr.cancel called");
}
} else if (action.equals(BluetoothShare.INCOMING_FILE_CONFIRMATION_REQUEST_ACTION)) {
if (V) Log.v(TAG, "Receiver INCOMING_FILE_NOTIFICATION");
Toast.makeText(context, context.getString(R.string.incoming_file_toast_msg),
Toast.LENGTH_SHORT).show();
} else if (action.equals(Constants.ACTION_OPEN) || action.equals(Constants.ACTION_LIST)) {
if (V) {
if (action.equals(Constants.ACTION_OPEN)) {
Log.v(TAG, "Receiver open for " + intent.getData());
} else {
Log.v(TAG, "Receiver list for " + intent.getData());
}
}
BluetoothOppTransferInfo transInfo = new BluetoothOppTransferInfo();
Uri uri = intent.getData();
transInfo = BluetoothOppUtility.queryRecord(context, uri);
if (transInfo == null) {
Log.e(TAG, "Error: Can not get data from db");
return;
}
if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND
&& BluetoothShare.isStatusSuccess(transInfo.mStatus)) {
// if received file successfully, open this file
BluetoothOppUtility.openReceivedFile(context, transInfo.mFileName,
transInfo.mFileType, transInfo.mTimeStamp, uri);
BluetoothOppUtility.updateVisibilityToHidden(context, uri);
} else {
Intent in = new Intent(context, BluetoothOppTransferActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.setData(uri);
context.startActivity(in);
}
NotificationManager notMgr = (NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
if (notMgr != null) {
notMgr.cancel((int)ContentUris.parseId(intent.getData()));
if (V) Log.v(TAG, "notMgr.cancel called");
}
} else if (action.equals(Constants.ACTION_OPEN_OUTBOUND_TRANSFER)) {
if (V) Log.v(TAG, "Received ACTION_OPEN_OUTBOUND_TRANSFER.");
Intent in = new Intent(context, BluetoothOppTransferHistory.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
in.putExtra("direction", BluetoothShare.DIRECTION_OUTBOUND);
context.startActivity(in);
} else if (action.equals(Constants.ACTION_OPEN_INBOUND_TRANSFER)) {
if (V) Log.v(TAG, "Received ACTION_OPEN_INBOUND_TRANSFER.");
Intent in = new Intent(context, BluetoothOppTransferHistory.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
in.putExtra("direction", BluetoothShare.DIRECTION_INBOUND);
context.startActivity(in);
} else if (action.equals(Constants.ACTION_OPEN_RECEIVED_FILES)) {
if (V) Log.v(TAG, "Received ACTION_OPEN_RECEIVED_FILES.");
Intent in = new Intent(context, BluetoothOppTransferHistory.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
in.putExtra("direction", BluetoothShare.DIRECTION_INBOUND);
in.putExtra(Constants.EXTRA_SHOW_ALL_FILES, true);
context.startActivity(in);
} else if (action.equals(Constants.ACTION_HIDE)) {
if (V) Log.v(TAG, "Receiver hide for " + intent.getData());
Cursor cursor = context.getContentResolver().query(intent.getData(), null, null, null,
null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int statusColumn = cursor.getColumnIndexOrThrow(BluetoothShare.STATUS);
int status = cursor.getInt(statusColumn);
int visibilityColumn = cursor.getColumnIndexOrThrow(BluetoothShare.VISIBILITY);
int visibility = cursor.getInt(visibilityColumn);
int userConfirmationColumn = cursor
.getColumnIndexOrThrow(BluetoothShare.USER_CONFIRMATION);
int userConfirmation = cursor.getInt(userConfirmationColumn);
if (((userConfirmation == BluetoothShare.USER_CONFIRMATION_PENDING))
&& visibility == BluetoothShare.VISIBILITY_VISIBLE) {
ContentValues values = new ContentValues();
values.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN);
context.getContentResolver().update(intent.getData(), values, null, null);
if (V) Log.v(TAG, "Action_hide received and db updated");
}
}
cursor.close();
}
} else if (action.equals(Constants.ACTION_COMPLETE_HIDE)) {
if (V) Log.v(TAG, "Receiver ACTION_COMPLETE_HIDE");
ContentValues updateValues = new ContentValues();
updateValues.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN);
context.getContentResolver().update(BluetoothShare.CONTENT_URI, updateValues,
BluetoothOppNotification.WHERE_COMPLETED, null);
} else if (action.equals(BluetoothShare.TRANSFER_COMPLETED_ACTION)) {
if (V) Log.v(TAG, "Receiver Transfer Complete Intent for " + intent.getData());
String toastMsg = null;
BluetoothOppTransferInfo transInfo = new BluetoothOppTransferInfo();
transInfo = BluetoothOppUtility.queryRecord(context, intent.getData());
if (transInfo == null) {
Log.e(TAG, "Error: Can not get data from db");
return;
}
if (transInfo.mHandoverInitiated) {
// Deal with handover-initiated transfers separately
Intent handoverIntent = new Intent(Constants.ACTION_BT_OPP_TRANSFER_DONE);
if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND) {
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_DIRECTION,
Constants.DIRECTION_BLUETOOTH_INCOMING);
} else {
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_DIRECTION,
Constants.DIRECTION_BLUETOOTH_OUTGOING);
}
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_ID, transInfo.mID);
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_ADDRESS, transInfo.mDestAddr);
if (BluetoothShare.isStatusSuccess(transInfo.mStatus)) {
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_STATUS,
Constants.HANDOVER_TRANSFER_STATUS_SUCCESS);
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_URI,
transInfo.mFileName);
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_MIMETYPE,
transInfo.mFileType);
} else {
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_STATUS,
Constants.HANDOVER_TRANSFER_STATUS_FAILURE);
}
context.sendBroadcast(handoverIntent, Constants.HANDOVER_STATUS_PERMISSION);
return;
}
if (BluetoothShare.isStatusSuccess(transInfo.mStatus)) {
if (transInfo.mDirection == BluetoothShare.DIRECTION_OUTBOUND) {
toastMsg = context.getString(R.string.notification_sent, transInfo.mFileName);
} else if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND) {
toastMsg = context.getString(R.string.notification_received,
transInfo.mFileName);
}
} else if (BluetoothShare.isStatusError(transInfo.mStatus)) {
if (transInfo.mDirection == BluetoothShare.DIRECTION_OUTBOUND) {
toastMsg = context.getString(R.string.notification_sent_fail,
transInfo.mFileName);
} else if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND) {
toastMsg = context.getString(R.string.download_fail_line1);
}
}
if (Constants.ZERO_LENGTH_FILE) {
toastMsg = context.getString(R.string.empty_file_notification_sent, transInfo.mFileName);
}
if (V) Log.v(TAG, "Toast msg == " + toastMsg);
if (toastMsg != null) {
Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show();
}
}
}
| public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
if (BluetoothAdapter.STATE_ON == intent.getIntExtra(
BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {
if (V) Log.v(TAG, "Received BLUETOOTH_STATE_CHANGED_ACTION, BLUETOOTH_STATE_ON");
context.startService(new Intent(context, BluetoothOppService.class));
// If this is within a sending process, continue the handle
// logic to display device picker dialog.
synchronized (this) {
if (BluetoothOppManager.getInstance(context).mSendingFlag) {
// reset the flags
BluetoothOppManager.getInstance(context).mSendingFlag = false;
Intent in1 = new Intent(BluetoothDevicePicker.ACTION_LAUNCH);
in1.putExtra(BluetoothDevicePicker.EXTRA_NEED_AUTH, false);
in1.putExtra(BluetoothDevicePicker.EXTRA_FILTER_TYPE,
BluetoothDevicePicker.FILTER_TYPE_TRANSFER);
in1.putExtra(BluetoothDevicePicker.EXTRA_LAUNCH_PACKAGE,
Constants.THIS_PACKAGE_NAME);
in1.putExtra(BluetoothDevicePicker.EXTRA_LAUNCH_CLASS,
BluetoothOppReceiver.class.getName());
in1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(in1);
}
}
}
} else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
if (V) Log.v(TAG, "Received ACTION_ACL_DISCONNECTED");
// Don't forward intent unless device has bluetooth and bluetooth is enabled.
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {
context.startService(new Intent(context, BluetoothOppService.class));
}
} else if (action.equals(BluetoothDevicePicker.ACTION_DEVICE_SELECTED)) {
BluetoothOppManager mOppManager = BluetoothOppManager.getInstance(context);
BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (V) Log.v(TAG, "Received BT device selected intent, bt device: " + remoteDevice);
// Insert transfer session record to database
mOppManager.startTransfer(remoteDevice);
// Display toast message
String deviceName = remoteDevice.getName();
String toastMsg;
int batchSize = mOppManager.getBatchSize();
if (mOppManager.mMultipleFlag) {
toastMsg = context.getString(R.string.bt_toast_5, Integer.toString(batchSize),
deviceName);
} else {
toastMsg = context.getString(R.string.bt_toast_4, deviceName);
}
Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show();
} else if (action.equals(Constants.ACTION_INCOMING_FILE_CONFIRM)) {
if (V) Log.v(TAG, "Receiver ACTION_INCOMING_FILE_CONFIRM");
Uri uri = intent.getData();
Intent in = new Intent(context, BluetoothOppIncomingFileConfirmActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.setData(uri);
context.startActivity(in);
NotificationManager notMgr = (NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
if (notMgr != null) {
notMgr.cancel((int)ContentUris.parseId(intent.getData()));
if (V) Log.v(TAG, "notMgr.cancel called");
}
} else if (action.equals(BluetoothShare.INCOMING_FILE_CONFIRMATION_REQUEST_ACTION)) {
if (V) Log.v(TAG, "Receiver INCOMING_FILE_NOTIFICATION");
Toast.makeText(context, context.getString(R.string.incoming_file_toast_msg),
Toast.LENGTH_SHORT).show();
} else if (action.equals(Constants.ACTION_OPEN) || action.equals(Constants.ACTION_LIST)) {
if (V) {
if (action.equals(Constants.ACTION_OPEN)) {
Log.v(TAG, "Receiver open for " + intent.getData());
} else {
Log.v(TAG, "Receiver list for " + intent.getData());
}
}
BluetoothOppTransferInfo transInfo = new BluetoothOppTransferInfo();
Uri uri = intent.getData();
transInfo = BluetoothOppUtility.queryRecord(context, uri);
if (transInfo == null) {
Log.e(TAG, "Error: Can not get data from db");
return;
}
if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND
&& BluetoothShare.isStatusSuccess(transInfo.mStatus)) {
// if received file successfully, open this file
BluetoothOppUtility.openReceivedFile(context, transInfo.mFileName,
transInfo.mFileType, transInfo.mTimeStamp, uri);
BluetoothOppUtility.updateVisibilityToHidden(context, uri);
} else {
Intent in = new Intent(context, BluetoothOppTransferActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.setData(uri);
context.startActivity(in);
}
NotificationManager notMgr = (NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
if (notMgr != null) {
notMgr.cancel((int)ContentUris.parseId(intent.getData()));
if (V) Log.v(TAG, "notMgr.cancel called");
}
} else if (action.equals(Constants.ACTION_OPEN_OUTBOUND_TRANSFER)) {
if (V) Log.v(TAG, "Received ACTION_OPEN_OUTBOUND_TRANSFER.");
Intent in = new Intent(context, BluetoothOppTransferHistory.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
in.putExtra("direction", BluetoothShare.DIRECTION_OUTBOUND);
context.startActivity(in);
} else if (action.equals(Constants.ACTION_OPEN_INBOUND_TRANSFER)) {
if (V) Log.v(TAG, "Received ACTION_OPEN_INBOUND_TRANSFER.");
Intent in = new Intent(context, BluetoothOppTransferHistory.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
in.putExtra("direction", BluetoothShare.DIRECTION_INBOUND);
context.startActivity(in);
} else if (action.equals(Constants.ACTION_OPEN_RECEIVED_FILES)) {
if (V) Log.v(TAG, "Received ACTION_OPEN_RECEIVED_FILES.");
Intent in = new Intent(context, BluetoothOppTransferHistory.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
in.putExtra("direction", BluetoothShare.DIRECTION_INBOUND);
in.putExtra(Constants.EXTRA_SHOW_ALL_FILES, true);
context.startActivity(in);
} else if (action.equals(Constants.ACTION_HIDE)) {
if (V) Log.v(TAG, "Receiver hide for " + intent.getData());
Cursor cursor = context.getContentResolver().query(intent.getData(), null, null, null,
null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int statusColumn = cursor.getColumnIndexOrThrow(BluetoothShare.STATUS);
int status = cursor.getInt(statusColumn);
int visibilityColumn = cursor.getColumnIndexOrThrow(BluetoothShare.VISIBILITY);
int visibility = cursor.getInt(visibilityColumn);
int userConfirmationColumn = cursor
.getColumnIndexOrThrow(BluetoothShare.USER_CONFIRMATION);
int userConfirmation = cursor.getInt(userConfirmationColumn);
if (((userConfirmation == BluetoothShare.USER_CONFIRMATION_PENDING))
&& visibility == BluetoothShare.VISIBILITY_VISIBLE) {
ContentValues values = new ContentValues();
values.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN);
context.getContentResolver().update(intent.getData(), values, null, null);
if (V) Log.v(TAG, "Action_hide received and db updated");
}
}
cursor.close();
}
} else if (action.equals(Constants.ACTION_COMPLETE_HIDE)) {
if (V) Log.v(TAG, "Receiver ACTION_COMPLETE_HIDE");
ContentValues updateValues = new ContentValues();
updateValues.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN);
context.getContentResolver().update(BluetoothShare.CONTENT_URI, updateValues,
BluetoothOppNotification.WHERE_COMPLETED, null);
} else if (action.equals(BluetoothShare.TRANSFER_COMPLETED_ACTION)) {
if (V) Log.v(TAG, "Receiver Transfer Complete Intent for " + intent.getData());
String toastMsg = null;
BluetoothOppTransferInfo transInfo = new BluetoothOppTransferInfo();
transInfo = BluetoothOppUtility.queryRecord(context, intent.getData());
if (transInfo == null) {
Log.e(TAG, "Error: Can not get data from db");
return;
}
if (transInfo.mHandoverInitiated) {
// Deal with handover-initiated transfers separately
Intent handoverIntent = new Intent(Constants.ACTION_BT_OPP_TRANSFER_DONE);
if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND) {
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_DIRECTION,
Constants.DIRECTION_BLUETOOTH_INCOMING);
} else {
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_DIRECTION,
Constants.DIRECTION_BLUETOOTH_OUTGOING);
}
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_ID, transInfo.mID);
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_ADDRESS, transInfo.mDestAddr);
if (BluetoothShare.isStatusSuccess(transInfo.mStatus)) {
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_STATUS,
Constants.HANDOVER_TRANSFER_STATUS_SUCCESS);
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_URI,
transInfo.mFileName);
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_MIMETYPE,
transInfo.mFileType);
} else {
handoverIntent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_STATUS,
Constants.HANDOVER_TRANSFER_STATUS_FAILURE);
}
context.sendBroadcast(handoverIntent, Constants.HANDOVER_STATUS_PERMISSION);
return;
}
if (BluetoothShare.isStatusSuccess(transInfo.mStatus)) {
if (transInfo.mDirection == BluetoothShare.DIRECTION_OUTBOUND) {
toastMsg = context.getString(R.string.notification_sent, transInfo.mFileName);
} else if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND) {
toastMsg = context.getString(R.string.notification_received,
transInfo.mFileName);
}
} else if (BluetoothShare.isStatusError(transInfo.mStatus)) {
if (transInfo.mDirection == BluetoothShare.DIRECTION_OUTBOUND) {
toastMsg = context.getString(R.string.notification_sent_fail,
transInfo.mFileName);
} else if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND) {
toastMsg = context.getString(R.string.download_fail_line1);
}
}
if (Constants.ZERO_LENGTH_FILE) {
toastMsg = context.getString(R.string.empty_file_notification_sent, transInfo.mFileName);
}
if (V) Log.v(TAG, "Toast msg == " + toastMsg);
if (toastMsg != null) {
Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show();
}
}
}
|
diff --git a/MULE/src/Tile.java b/MULE/src/Tile.java
index 3958fb9..a9602c8 100644
--- a/MULE/src/Tile.java
+++ b/MULE/src/Tile.java
@@ -1,91 +1,98 @@
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
/*
* A class that represents a Tile on the map
*/
public abstract class Tile extends JButton{
protected ImageIcon img;
protected Point location;
protected boolean isOwned;
protected Player owner;
protected int cost;
protected MapPanel panel;
protected ActionListener tileListener;
public Tile(Point location){
this.location=location;
cost = 20;
tileListener = new buyListener(this);
addActionListener(tileListener);
isOwned=false;
}
public void isBought(Player p){
owner = p;
isOwned=true;
}
public boolean isOwned(){
return isOwned;
}
class buyListener implements ActionListener{
private Tile tile;
private Player p;
public buyListener(Tile tile){
this.tile=tile;
}
@Override
public void actionPerformed(ActionEvent e) {
p=GameMain.getCurrPlayer();
if(!isOwned){ //note to fix
int askBuy = JOptionPane.showConfirmDialog(null,"Would you like to buy this property? It costs " + cost , "Buy this time?", JOptionPane.YES_NO_OPTION);
if(askBuy==JOptionPane.YES_OPTION){
if(GameMain.getCurrTurns()<=2){
if(p.buyProperty(0, tile)){
JOptionPane.showMessageDialog(null,
"Congratulations! You got it!");
tile.setBackground(p.getColor());
isBought(p);
}
else{
if(p.buyProperty(cost, tile)){
JOptionPane.showMessageDialog(null,
"Congratulations! You got it!");
tile.setBackground(p.getColor());
isBought(p);
}
}
}
else
{
- JOptionPane.showMessageDialog(null,
+ if(p.buyProperty(cost, tile)){
+ JOptionPane.showMessageDialog(null,
+ "Congratulations! You got it!");
+ tile.setBackground(p.getColor());
+ isBought(p);
+ }
+ else
+ JOptionPane.showMessageDialog(null,
"You're too poor for this land.");
}
}
if(askBuy==JOptionPane.NO_OPTION){
//idk think of something to do
}
}
else{
JOptionPane.showMessageDialog(null,
"This tile is already owned by or you are too poor to buy it. Better luck next time");
}
}
}
}
| true | true | public void actionPerformed(ActionEvent e) {
p=GameMain.getCurrPlayer();
if(!isOwned){ //note to fix
int askBuy = JOptionPane.showConfirmDialog(null,"Would you like to buy this property? It costs " + cost , "Buy this time?", JOptionPane.YES_NO_OPTION);
if(askBuy==JOptionPane.YES_OPTION){
if(GameMain.getCurrTurns()<=2){
if(p.buyProperty(0, tile)){
JOptionPane.showMessageDialog(null,
"Congratulations! You got it!");
tile.setBackground(p.getColor());
isBought(p);
}
else{
if(p.buyProperty(cost, tile)){
JOptionPane.showMessageDialog(null,
"Congratulations! You got it!");
tile.setBackground(p.getColor());
isBought(p);
}
}
}
else
{
JOptionPane.showMessageDialog(null,
"You're too poor for this land.");
}
}
if(askBuy==JOptionPane.NO_OPTION){
//idk think of something to do
}
}
else{
JOptionPane.showMessageDialog(null,
"This tile is already owned by or you are too poor to buy it. Better luck next time");
}
}
| public void actionPerformed(ActionEvent e) {
p=GameMain.getCurrPlayer();
if(!isOwned){ //note to fix
int askBuy = JOptionPane.showConfirmDialog(null,"Would you like to buy this property? It costs " + cost , "Buy this time?", JOptionPane.YES_NO_OPTION);
if(askBuy==JOptionPane.YES_OPTION){
if(GameMain.getCurrTurns()<=2){
if(p.buyProperty(0, tile)){
JOptionPane.showMessageDialog(null,
"Congratulations! You got it!");
tile.setBackground(p.getColor());
isBought(p);
}
else{
if(p.buyProperty(cost, tile)){
JOptionPane.showMessageDialog(null,
"Congratulations! You got it!");
tile.setBackground(p.getColor());
isBought(p);
}
}
}
else
{
if(p.buyProperty(cost, tile)){
JOptionPane.showMessageDialog(null,
"Congratulations! You got it!");
tile.setBackground(p.getColor());
isBought(p);
}
else
JOptionPane.showMessageDialog(null,
"You're too poor for this land.");
}
}
if(askBuy==JOptionPane.NO_OPTION){
//idk think of something to do
}
}
else{
JOptionPane.showMessageDialog(null,
"This tile is already owned by or you are too poor to buy it. Better luck next time");
}
}
|
diff --git a/mx.itesm.mexadl/src/mx/itesm/mexadl/metrics/MetricsProcessor.java b/mx.itesm.mexadl/src/mx/itesm/mexadl/metrics/MetricsProcessor.java
index d06384e..678e4b1 100644
--- a/mx.itesm.mexadl/src/mx/itesm/mexadl/metrics/MetricsProcessor.java
+++ b/mx.itesm.mexadl/src/mx/itesm/mexadl/metrics/MetricsProcessor.java
@@ -1,157 +1,157 @@
package mx.itesm.mexadl.metrics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mx.itesm.mexadl.MexAdlProcessor;
import mx.itesm.mexadl.util.Util;
import org.apache.velocity.Template;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
/**
* The MetricsProcessor class generates an aspect that introduces the
* implementation of the mx.itesm.mexadl.metrics.MaintainabilityMetrics
* interface, to specially marked components in an xADL architecture definition.
*
* @author jccastrejon
*
*/
public class MetricsProcessor implements MexAdlProcessor {
/**
* XPath expression to identify the MexADL quality metrics.
*/
private static XPath metricsPath;
/**
* AspectJ template that defines the quality metrics to be measured in the
* components of a system's architecture.
*/
private static Template aspectTemplate;
/**
* Interface that will hold the quality metrics to be measured in a
* component of a system's architecture.
*/
private static Template interfaceTemplate;
static {
try {
MetricsProcessor.aspectTemplate = Util.getVelocityTemplate(MetricsProcessor.class, "aspect");
MetricsProcessor.interfaceTemplate = Util.getVelocityTemplate(MetricsProcessor.class, "interface");
MetricsProcessor.metricsPath = XPath.newInstance("//mexadl:maintainabilityMetrics");
} catch (Exception e) {
System.out.println("Error loading MetricsProcessor");
e.printStackTrace();
}
}
@Override
@SuppressWarnings("unchecked")
public void processDocument(Document document, String xArchFilePath) throws Exception {
MetricsData metricsData;
Map<String, Object> metric;
Map<String, Object> metricSet;
Map<String, Object> definition;
Map<String, Object> properties;
List<Element> metricDefinitions;
List<Map<String, Object>> metrics;
List<Map<String, Object>> metricSets;
List<Map<String, Object>> definitionsList;
metricDefinitions = MetricsProcessor.metricsPath.selectNodes(document);
if ((metricDefinitions != null) && (!metricDefinitions.isEmpty())) {
definitionsList = new ArrayList<Map<String, Object>>();
for (Element metricDefinition : metricDefinitions) {
definition = new HashMap<String, Object>();
metricSets = new ArrayList<Map<String, Object>>();
metricsData = this.getMetricsData(document, metricDefinition);
// Process the file only if a valid xADL type is associated to
// the metrics definition
if (metricsData.getType() != null) {
definitionsList.add(definition);
definition.put("metricSets", metricSets);
definition.put("type", metricsData.getType());
definition.put("typeName", Util.getValidName(metricsData.getType()));
definition.put("metricsClass", MaintainabilityMetrics.class.getName());
for (MetricsData metricSetDefinition : metricsData.getMetrics()) {
metricSet = new HashMap<String, Object>();
metricSets.add(metricSet);
metrics = new ArrayList<Map<String, Object>>();
metricSet.put("name", metricSetDefinition.getType());
metricSet.put("type", metricSetDefinition.getType().substring(0, 1).toUpperCase()
+ metricSetDefinition.getType().substring(1));
metricSet.put("metrics", metrics);
for (String metricName : metricSetDefinition.getData().keySet()) {
metric = new HashMap<String, Object>();
metrics.add(metric);
metric.put("name", metricName);
metric.put("value", metricSetDefinition.getData().get(metricName));
}
}
// Create the metrics interface
Util.createJavaFile(document, xArchFilePath, MetricsProcessor.interfaceTemplate, definition,
- "MetricsInterface", definition.get("typeName").toString());
+ "Metrics", definition.get("typeName").toString());
}
}
// Create the metrics aspect only if valid associations were found
if (!definitionsList.isEmpty()) {
properties = new HashMap<String, Object>();
properties.put("definitionsList", definitionsList);
Util.createJavaFile(document, xArchFilePath, MetricsProcessor.aspectTemplate, properties,
"MetricsAspect", Util.getDocumentName(document));
}
}
}
/**
* Get the quality metrics associated the the specified element.
*
* @param element
* @throws JDOMException
*/
@SuppressWarnings("unchecked")
private MetricsData getMetricsData(final Document document, final Element element) throws JDOMException {
MetricsData metricSet;
MetricsData returnValue;
List<MetricsData> metricSets;
returnValue = null;
if (element != null) {
returnValue = new MetricsData();
metricSets = new ArrayList<MetricsData>();
returnValue.setType(Util.getLinkImplementationClass(document, Util.getIdValue(element.getParentElement())));
returnValue.setMetrics(metricSets);
for (Element child : (List<Element>) element.getChildren()) {
if (child.getNamespace() == Util.MEXADL_NAMESPACE) {
metricSet = new MetricsData();
metricSets.add(metricSet);
metricSet.setType(child.getName());
metricSet.setData(new HashMap<String, String>());
for (Attribute attribute : (List<Attribute>) child.getAttributes()) {
if (attribute.getNamespace() == Util.MEXADL_NAMESPACE) {
metricSet.getData().put(attribute.getName(), attribute.getValue());
}
}
}
}
}
return returnValue;
}
}
| true | true | public void processDocument(Document document, String xArchFilePath) throws Exception {
MetricsData metricsData;
Map<String, Object> metric;
Map<String, Object> metricSet;
Map<String, Object> definition;
Map<String, Object> properties;
List<Element> metricDefinitions;
List<Map<String, Object>> metrics;
List<Map<String, Object>> metricSets;
List<Map<String, Object>> definitionsList;
metricDefinitions = MetricsProcessor.metricsPath.selectNodes(document);
if ((metricDefinitions != null) && (!metricDefinitions.isEmpty())) {
definitionsList = new ArrayList<Map<String, Object>>();
for (Element metricDefinition : metricDefinitions) {
definition = new HashMap<String, Object>();
metricSets = new ArrayList<Map<String, Object>>();
metricsData = this.getMetricsData(document, metricDefinition);
// Process the file only if a valid xADL type is associated to
// the metrics definition
if (metricsData.getType() != null) {
definitionsList.add(definition);
definition.put("metricSets", metricSets);
definition.put("type", metricsData.getType());
definition.put("typeName", Util.getValidName(metricsData.getType()));
definition.put("metricsClass", MaintainabilityMetrics.class.getName());
for (MetricsData metricSetDefinition : metricsData.getMetrics()) {
metricSet = new HashMap<String, Object>();
metricSets.add(metricSet);
metrics = new ArrayList<Map<String, Object>>();
metricSet.put("name", metricSetDefinition.getType());
metricSet.put("type", metricSetDefinition.getType().substring(0, 1).toUpperCase()
+ metricSetDefinition.getType().substring(1));
metricSet.put("metrics", metrics);
for (String metricName : metricSetDefinition.getData().keySet()) {
metric = new HashMap<String, Object>();
metrics.add(metric);
metric.put("name", metricName);
metric.put("value", metricSetDefinition.getData().get(metricName));
}
}
// Create the metrics interface
Util.createJavaFile(document, xArchFilePath, MetricsProcessor.interfaceTemplate, definition,
"MetricsInterface", definition.get("typeName").toString());
}
}
// Create the metrics aspect only if valid associations were found
if (!definitionsList.isEmpty()) {
properties = new HashMap<String, Object>();
properties.put("definitionsList", definitionsList);
Util.createJavaFile(document, xArchFilePath, MetricsProcessor.aspectTemplate, properties,
"MetricsAspect", Util.getDocumentName(document));
}
}
}
| public void processDocument(Document document, String xArchFilePath) throws Exception {
MetricsData metricsData;
Map<String, Object> metric;
Map<String, Object> metricSet;
Map<String, Object> definition;
Map<String, Object> properties;
List<Element> metricDefinitions;
List<Map<String, Object>> metrics;
List<Map<String, Object>> metricSets;
List<Map<String, Object>> definitionsList;
metricDefinitions = MetricsProcessor.metricsPath.selectNodes(document);
if ((metricDefinitions != null) && (!metricDefinitions.isEmpty())) {
definitionsList = new ArrayList<Map<String, Object>>();
for (Element metricDefinition : metricDefinitions) {
definition = new HashMap<String, Object>();
metricSets = new ArrayList<Map<String, Object>>();
metricsData = this.getMetricsData(document, metricDefinition);
// Process the file only if a valid xADL type is associated to
// the metrics definition
if (metricsData.getType() != null) {
definitionsList.add(definition);
definition.put("metricSets", metricSets);
definition.put("type", metricsData.getType());
definition.put("typeName", Util.getValidName(metricsData.getType()));
definition.put("metricsClass", MaintainabilityMetrics.class.getName());
for (MetricsData metricSetDefinition : metricsData.getMetrics()) {
metricSet = new HashMap<String, Object>();
metricSets.add(metricSet);
metrics = new ArrayList<Map<String, Object>>();
metricSet.put("name", metricSetDefinition.getType());
metricSet.put("type", metricSetDefinition.getType().substring(0, 1).toUpperCase()
+ metricSetDefinition.getType().substring(1));
metricSet.put("metrics", metrics);
for (String metricName : metricSetDefinition.getData().keySet()) {
metric = new HashMap<String, Object>();
metrics.add(metric);
metric.put("name", metricName);
metric.put("value", metricSetDefinition.getData().get(metricName));
}
}
// Create the metrics interface
Util.createJavaFile(document, xArchFilePath, MetricsProcessor.interfaceTemplate, definition,
"Metrics", definition.get("typeName").toString());
}
}
// Create the metrics aspect only if valid associations were found
if (!definitionsList.isEmpty()) {
properties = new HashMap<String, Object>();
properties.put("definitionsList", definitionsList);
Util.createJavaFile(document, xArchFilePath, MetricsProcessor.aspectTemplate, properties,
"MetricsAspect", Util.getDocumentName(document));
}
}
}
|
diff --git a/src/wjhk/jupload2/upload/HttpConnect.java b/src/wjhk/jupload2/upload/HttpConnect.java
index 3027ddc..047606e 100644
--- a/src/wjhk/jupload2/upload/HttpConnect.java
+++ b/src/wjhk/jupload2/upload/HttpConnect.java
@@ -1,427 +1,428 @@
//
// $Id: HttpConnect.java 286 2007-06-17 09:03:29 +0000 (dim., 17 juin 2007)
// felfert $
//
// jupload - A file upload applet.
//
// Copyright 2007 The JUpload Team
//
// Created: 07.05.2007
// Creator: felfert
// Last modified: $Date$
//
// 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., 675 Mass Ave, Cambridge, MA 02139, USA.
package wjhk.jupload2.upload;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.Socket;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import wjhk.jupload2.exception.JUploadException;
import wjhk.jupload2.policies.UploadPolicy;
/**
* This class implements the task of connecting to a HTTP(S) url using a proxy.
*
* @author felfert
*/
public class HttpConnect {
private final static String DEFAULT_PROTOCOL = "HTTP/1.1";
/**
* The current upload policy. Used for logging, and to get the post URL.
* Also used to change this URL, when it has moved (301, 302 or 303 return
* code)
*/
private UploadPolicy uploadPolicy;
/**
* Helper function for perforing a proxy CONNECT request.
*
* @param proxy The proxy to use.
* @param host The destination's hostname.
* @param port The destination's port
* @return An established socket connection to the proxy.
* @throws ConnectException if the proxy response code is not 200
* @throws UnknownHostException
* @throws IOException
*/
private Socket HttpProxyConnect(Proxy proxy, String host, int port)
throws UnknownHostException, IOException, ConnectException {
InetSocketAddress sa = (InetSocketAddress) proxy.address();
String phost = (sa.isUnresolved()) ? sa.getHostName() : sa.getAddress()
.getHostAddress();
int pport = sa.getPort();
//
Socket proxysock = new Socket(phost, pport);
String req = "CONNECT " + host + ":" + port + " " + DEFAULT_PROTOCOL
+ "\r\n\r\n";
proxysock.getOutputStream().write(req.getBytes());
BufferedReader proxyIn = new BufferedReader(new InputStreamReader(
proxysock.getInputStream()));
// We expect exactly one line: the proxy response
String line = proxyIn.readLine();
if (!line.matches("^HTTP/\\d\\.\\d\\s200\\s.*"))
throw new ConnectException("Proxy response: " + line);
this.uploadPolicy.displayDebug("Proxy response: " + line, 40);
proxyIn.readLine(); // eat the header delimiter
// we now are connected ...
return proxysock;
}
/**
* Connects to a given URL.
*
* @param url The URL to connect to
* @param proxy The proxy to be used, may be null if direct connection is
* needed
* @return A socket, connected to the specified URL. May be null if an error
* occurs.
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws UnknownHostException
* @throws ConnectException
* @throws CertificateException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws IllegalArgumentException
*/
public Socket Connect(URL url, Proxy proxy)
throws NoSuchAlgorithmException, KeyManagementException,
ConnectException, UnknownHostException, IOException,
KeyStoreException, CertificateException, IllegalArgumentException,
UnrecoverableKeyException {
// Temporary socket for SOCKS support
Socket tsock;
Socket ret = null;
String host = url.getHost();
int port;
boolean useProxy = ((proxy != null) && (proxy.type() != Proxy.Type.DIRECT));
// Check if SSL connection is needed
if (url.getProtocol().equals("https")) {
port = (-1 == url.getPort()) ? 443 : url.getPort();
SSLContext context = SSLContext.getInstance("SSL");
// Allow all certificates
InteractiveTrustManager tm = new InteractiveTrustManager(
this.uploadPolicy, url.getHost(), null);
context.init(tm.getKeyManagers(), tm.getTrustManagers(),
SecureRandom.getInstance("SHA1PRNG"));
if (useProxy) {
if (proxy.type() == Proxy.Type.HTTP) {
// First establish a CONNECT, then do a normal SSL
// thru that connection.
this.uploadPolicy.displayDebug(
"Using SSL socket, via HTTP proxy", 20);
ret = context.getSocketFactory().createSocket(
HttpProxyConnect(proxy, host, port), host, port,
true);
} else if (proxy.type() == Proxy.Type.SOCKS) {
this.uploadPolicy.displayDebug(
"Using SSL socket, via SOCKS proxy", 20);
tsock = new Socket(proxy);
tsock.connect(new InetSocketAddress(host, port));
ret = context.getSocketFactory().createSocket(tsock, host,
port, true);
} else
throw new ConnectException("Unkown proxy type "
+ proxy.type());
} else {
// If port not specified then use default https port
// 443.
this.uploadPolicy.displayDebug(
"Using SSL socket, direct connection", 20);
ret = context.getSocketFactory().createSocket(host, port);
}
} else {
// If we are not in SSL, just use the old code.
port = (-1 == url.getPort()) ? 80 : url.getPort();
if (useProxy) {
if (proxy.type() == Proxy.Type.HTTP) {
InetSocketAddress sa = (InetSocketAddress) proxy.address();
host = (sa.isUnresolved()) ? sa.getHostName() : sa
.getAddress().getHostAddress();
port = sa.getPort();
this.uploadPolicy.displayDebug(
"Using non SSL socket, proxy=" + host + ":" + port,
20);
ret = new Socket(host, port);
} else if (proxy.type() == Proxy.Type.SOCKS) {
this.uploadPolicy.displayDebug(
"Using non SSL socket, via SOCKS proxy", 20);
tsock = new Socket(proxy);
tsock.connect(new InetSocketAddress(host, port));
ret = tsock;
} else
throw new ConnectException("Unkown proxy type "
+ proxy.type());
} else {
this.uploadPolicy.displayDebug(
"Using non SSL socket, direct connection", 20);
ret = new Socket(host, port);
}
}
return ret;
}
/**
* Connects to a given URL automatically using a proxy.
*
* @param url The URL to connect to
* @return A socket, connected to the specified URL. May be null if an error
* occurs.
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws UnknownHostException
* @throws ConnectException
* @throws URISyntaxException
* @throws UnrecoverableKeyException
* @throws CertificateException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws IllegalArgumentException
*/
public Socket Connect(URL url) throws NoSuchAlgorithmException,
KeyManagementException, ConnectException, UnknownHostException,
IOException, URISyntaxException, KeyStoreException,
CertificateException, IllegalArgumentException,
UnrecoverableKeyException {
Proxy proxy = ProxySelector.getDefault().select(url.toURI()).get(0);
return Connect(url, proxy);
}
/**
* Retrieve the protocol to be used for the postURL of the current policy.
* This method issues a HEAD request to the postURL and then examines the
* protocol version returned in the response.
*
* @return The string, describing the protocol (e.g. "HTTP/1.1")
* @throws URISyntaxException
* @throws IOException
* @throws UnrecoverableKeyException
* @throws IllegalArgumentException
* @throws CertificateException
* @throws KeyStoreException
* @throws UnknownHostException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws JUploadException
*/
public String getProtocol() throws URISyntaxException,
KeyManagementException, NoSuchAlgorithmException,
UnknownHostException, KeyStoreException, CertificateException,
IllegalArgumentException, UnrecoverableKeyException, IOException,
JUploadException {
String protocol = DEFAULT_PROTOCOL;
String returnCode = null;
// bRedirect indicates a return code of 301, 302 or 303.
boolean bRedirect = false;
URL url = new URL(this.uploadPolicy.getPostURL());
Proxy proxy = ProxySelector.getDefault().select(url.toURI()).get(0);
boolean useProxy = ((proxy != null) && (proxy.type() != Proxy.Type.DIRECT));
boolean useSSL = url.getProtocol().equals("https");
Socket s = Connect(url, proxy);
// BufferedReader in = new BufferedReader(new
// InputStreamReader(s.getInputStream()));
InputStream in = s.getInputStream();
StringBuffer req = new StringBuffer();
req.append("HEAD ");
if (useProxy && (!useSSL)) {
// with a proxy we need the absolute URL, but only if not
// using SSL. (with SSL, we first use the proxy CONNECT method,
// and then a plain request.)
req.append(url.getProtocol()).append("://").append(url.getHost());
}
req.append(url.getPath());
/*
* if (null != url.getQuery() && !"".equals(url.getQuery()))
* req.append("?").append(url.getQuery());
*/
req.append(" ").append(DEFAULT_PROTOCOL).append("\r\n");
req.append("Host: ").append(url.getHost()).append("\r\n");
req.append("Connection: close\r\n\r\n");
OutputStream os = s.getOutputStream();
os.write(req.toString().getBytes());
os.flush();
if (!(s instanceof SSLSocket)) {
s.shutdownOutput();
}
// Let's read the first line, and try to guess the HTTP protocol, and
// look for 301, 302 or 303 HTTP Return code.
String firstLine = FileUploadThreadHTTP.readLine(in, "US-ASCII", false);
if (null == firstLine) {
// Using default value. Already initialized.
- this.uploadPolicy.displayErr("EMPTY HEAD response");
+ //This can occur, for instance, when Kaspersky antivirus is on !
+ this.uploadPolicy.displayWarn("EMPTY HEAD response");
} else {
Matcher m = Pattern.compile("^(HTTP/\\d\\.\\d)\\s(.*)\\s.*")
.matcher(firstLine);
if (!m.matches()) {
// Using default value. Already initialized.
this.uploadPolicy.displayErr("Unexpected HEAD response: '"
+ firstLine + "'");
}
this.uploadPolicy.displayDebug("HEAD response: " + firstLine, 40);
// We will return the found protocol.
protocol = m.group(1);
// Do we have some URL to change ?
returnCode = m.group(2);
if (returnCode.equals("301") || returnCode.equals("302")
|| returnCode.equals("303")) {
bRedirect = true;
this.uploadPolicy.displayInfo("Received " + returnCode
+ " (current postURL: "
+ this.uploadPolicy.getPostURL() + ")");
}
}
// Let's check if we're facing an IIS server. The applet is compatible
// with IIS, only if allowHttpPersistent is false.
String nextLine = FileUploadThreadHTTP.readLine(in, "US-ASCII", false);
Pattern pLocation = Pattern.compile("^Location: (.*)$");
Matcher mLocation;
while ((nextLine = FileUploadThreadHTTP.readLine(in, "US-ASCII", false))
.length() > 0) {
if (nextLine.matches("^Server: .*IIS")) {
try {
uploadPolicy.setProperty(
UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT, "false");
uploadPolicy
.displayWarn(UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT
+ "' forced to false, for IIS compatibility (in HttpConnect.getProtocol())");
} catch (JUploadException e) {
uploadPolicy.displayWarn("Can't set property '"
+ UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT
+ "' to false, in HttpConnect.getProtocol()");
}
break;
} else if (bRedirect) {
mLocation = pLocation.matcher(nextLine);
if (mLocation.matches()) {
// We found the location where we should go instead of the
// original postURL
this.uploadPolicy.displayDebug("Location read: "
+ mLocation.group(1), 50);
changePostURL(mLocation.group(1));
}
}
}
// Let's look for the web server kind: the applet works IIS only if
// allowHttpPersistent is false
s.close();
return protocol;
} // getProtocol()
/**
* Reaction of the applet when a 301, 302 et 303 return code is returned.
* The postURL is changed according to the Location header returned.
*
* @param newLocation This new location may contain the
* http://host.name.domain part of the URL ... or not
*/
private void changePostURL(String newLocation) throws JUploadException {
String currentPostURL = this.uploadPolicy.getPostURL();
String newPostURL;
Pattern pHostName = Pattern.compile("http://([^/]*)/.*");
Matcher mOldPostURL = Pattern.compile("(.*)\\?(.*)").matcher(
currentPostURL);
// If there is an interrogation point in the original postURL, we'll
// keep the parameters, and just changed the URI part.
if (mOldPostURL.matches()) {
newPostURL = newLocation + '?' + mOldPostURL.group(2);
// Otherwise, we change the whole URL.
} else {
newPostURL = newLocation;
}
// There are three main cases or newLocation:
// 1- It's a full URL, with host name...
// 2- It's a local full path on the same server (begins with /)
// 3- It's a relative path (for instance, add of a prefix in the
// filename) (doesn't begin with /)
Matcher mHostOldPostURL = pHostName.matcher(currentPostURL);
if (!mHostOldPostURL.matches()) {
// Oups ! There is a little trouble here !
throw new JUploadException(
"[HttpConnect.changePostURL()] No host found in the old postURL !");
}
// Let's analyze the given newLocation for these three cases.
Matcher mHostNewLocation = pHostName.matcher(newLocation);
if (mHostNewLocation.matches()) {
// 1- It's a full URL, with host name. We already got this URL, in
// the newPostURL initialization.
} else if (newLocation.startsWith("/")) {
// 2- It's a local full path on the same server (begins with /)
newPostURL = "http://" + mHostOldPostURL.group(1) + newPostURL;
} else {
// 3- It's a relative path (for instance, add of a prefix in the
// filename) (doesn't begin with /)
Matcher mOldPostURLAllButFilename = Pattern
.compile("(.*)/([^/]*)$").matcher(currentPostURL);
if (!mOldPostURLAllButFilename.matches()) {
// Hum, that won't be easy.
throw new JUploadException(
"[HttpConnect.changePostURL()] Can't find the filename in the URL !");
}
newPostURL = mOldPostURLAllButFilename.group(1) + "/" + newPostURL;
}
// Let's store this new postURL, and display some info about the change
this.uploadPolicy.setPostURL(newPostURL);
this.uploadPolicy.displayInfo("postURL switched from " + currentPostURL
+ " to " + newPostURL);
}
/**
* Creates a new instance.
*
* @param policy The UploadPolicy to be used for logging.
*/
public HttpConnect(UploadPolicy policy) {
this.uploadPolicy = policy;
}
}
| true | true | public String getProtocol() throws URISyntaxException,
KeyManagementException, NoSuchAlgorithmException,
UnknownHostException, KeyStoreException, CertificateException,
IllegalArgumentException, UnrecoverableKeyException, IOException,
JUploadException {
String protocol = DEFAULT_PROTOCOL;
String returnCode = null;
// bRedirect indicates a return code of 301, 302 or 303.
boolean bRedirect = false;
URL url = new URL(this.uploadPolicy.getPostURL());
Proxy proxy = ProxySelector.getDefault().select(url.toURI()).get(0);
boolean useProxy = ((proxy != null) && (proxy.type() != Proxy.Type.DIRECT));
boolean useSSL = url.getProtocol().equals("https");
Socket s = Connect(url, proxy);
// BufferedReader in = new BufferedReader(new
// InputStreamReader(s.getInputStream()));
InputStream in = s.getInputStream();
StringBuffer req = new StringBuffer();
req.append("HEAD ");
if (useProxy && (!useSSL)) {
// with a proxy we need the absolute URL, but only if not
// using SSL. (with SSL, we first use the proxy CONNECT method,
// and then a plain request.)
req.append(url.getProtocol()).append("://").append(url.getHost());
}
req.append(url.getPath());
/*
* if (null != url.getQuery() && !"".equals(url.getQuery()))
* req.append("?").append(url.getQuery());
*/
req.append(" ").append(DEFAULT_PROTOCOL).append("\r\n");
req.append("Host: ").append(url.getHost()).append("\r\n");
req.append("Connection: close\r\n\r\n");
OutputStream os = s.getOutputStream();
os.write(req.toString().getBytes());
os.flush();
if (!(s instanceof SSLSocket)) {
s.shutdownOutput();
}
// Let's read the first line, and try to guess the HTTP protocol, and
// look for 301, 302 or 303 HTTP Return code.
String firstLine = FileUploadThreadHTTP.readLine(in, "US-ASCII", false);
if (null == firstLine) {
// Using default value. Already initialized.
this.uploadPolicy.displayErr("EMPTY HEAD response");
} else {
Matcher m = Pattern.compile("^(HTTP/\\d\\.\\d)\\s(.*)\\s.*")
.matcher(firstLine);
if (!m.matches()) {
// Using default value. Already initialized.
this.uploadPolicy.displayErr("Unexpected HEAD response: '"
+ firstLine + "'");
}
this.uploadPolicy.displayDebug("HEAD response: " + firstLine, 40);
// We will return the found protocol.
protocol = m.group(1);
// Do we have some URL to change ?
returnCode = m.group(2);
if (returnCode.equals("301") || returnCode.equals("302")
|| returnCode.equals("303")) {
bRedirect = true;
this.uploadPolicy.displayInfo("Received " + returnCode
+ " (current postURL: "
+ this.uploadPolicy.getPostURL() + ")");
}
}
// Let's check if we're facing an IIS server. The applet is compatible
// with IIS, only if allowHttpPersistent is false.
String nextLine = FileUploadThreadHTTP.readLine(in, "US-ASCII", false);
Pattern pLocation = Pattern.compile("^Location: (.*)$");
Matcher mLocation;
while ((nextLine = FileUploadThreadHTTP.readLine(in, "US-ASCII", false))
.length() > 0) {
if (nextLine.matches("^Server: .*IIS")) {
try {
uploadPolicy.setProperty(
UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT, "false");
uploadPolicy
.displayWarn(UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT
+ "' forced to false, for IIS compatibility (in HttpConnect.getProtocol())");
} catch (JUploadException e) {
uploadPolicy.displayWarn("Can't set property '"
+ UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT
+ "' to false, in HttpConnect.getProtocol()");
}
break;
} else if (bRedirect) {
mLocation = pLocation.matcher(nextLine);
if (mLocation.matches()) {
// We found the location where we should go instead of the
// original postURL
this.uploadPolicy.displayDebug("Location read: "
+ mLocation.group(1), 50);
changePostURL(mLocation.group(1));
}
}
}
// Let's look for the web server kind: the applet works IIS only if
// allowHttpPersistent is false
s.close();
return protocol;
} // getProtocol()
| public String getProtocol() throws URISyntaxException,
KeyManagementException, NoSuchAlgorithmException,
UnknownHostException, KeyStoreException, CertificateException,
IllegalArgumentException, UnrecoverableKeyException, IOException,
JUploadException {
String protocol = DEFAULT_PROTOCOL;
String returnCode = null;
// bRedirect indicates a return code of 301, 302 or 303.
boolean bRedirect = false;
URL url = new URL(this.uploadPolicy.getPostURL());
Proxy proxy = ProxySelector.getDefault().select(url.toURI()).get(0);
boolean useProxy = ((proxy != null) && (proxy.type() != Proxy.Type.DIRECT));
boolean useSSL = url.getProtocol().equals("https");
Socket s = Connect(url, proxy);
// BufferedReader in = new BufferedReader(new
// InputStreamReader(s.getInputStream()));
InputStream in = s.getInputStream();
StringBuffer req = new StringBuffer();
req.append("HEAD ");
if (useProxy && (!useSSL)) {
// with a proxy we need the absolute URL, but only if not
// using SSL. (with SSL, we first use the proxy CONNECT method,
// and then a plain request.)
req.append(url.getProtocol()).append("://").append(url.getHost());
}
req.append(url.getPath());
/*
* if (null != url.getQuery() && !"".equals(url.getQuery()))
* req.append("?").append(url.getQuery());
*/
req.append(" ").append(DEFAULT_PROTOCOL).append("\r\n");
req.append("Host: ").append(url.getHost()).append("\r\n");
req.append("Connection: close\r\n\r\n");
OutputStream os = s.getOutputStream();
os.write(req.toString().getBytes());
os.flush();
if (!(s instanceof SSLSocket)) {
s.shutdownOutput();
}
// Let's read the first line, and try to guess the HTTP protocol, and
// look for 301, 302 or 303 HTTP Return code.
String firstLine = FileUploadThreadHTTP.readLine(in, "US-ASCII", false);
if (null == firstLine) {
// Using default value. Already initialized.
//This can occur, for instance, when Kaspersky antivirus is on !
this.uploadPolicy.displayWarn("EMPTY HEAD response");
} else {
Matcher m = Pattern.compile("^(HTTP/\\d\\.\\d)\\s(.*)\\s.*")
.matcher(firstLine);
if (!m.matches()) {
// Using default value. Already initialized.
this.uploadPolicy.displayErr("Unexpected HEAD response: '"
+ firstLine + "'");
}
this.uploadPolicy.displayDebug("HEAD response: " + firstLine, 40);
// We will return the found protocol.
protocol = m.group(1);
// Do we have some URL to change ?
returnCode = m.group(2);
if (returnCode.equals("301") || returnCode.equals("302")
|| returnCode.equals("303")) {
bRedirect = true;
this.uploadPolicy.displayInfo("Received " + returnCode
+ " (current postURL: "
+ this.uploadPolicy.getPostURL() + ")");
}
}
// Let's check if we're facing an IIS server. The applet is compatible
// with IIS, only if allowHttpPersistent is false.
String nextLine = FileUploadThreadHTTP.readLine(in, "US-ASCII", false);
Pattern pLocation = Pattern.compile("^Location: (.*)$");
Matcher mLocation;
while ((nextLine = FileUploadThreadHTTP.readLine(in, "US-ASCII", false))
.length() > 0) {
if (nextLine.matches("^Server: .*IIS")) {
try {
uploadPolicy.setProperty(
UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT, "false");
uploadPolicy
.displayWarn(UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT
+ "' forced to false, for IIS compatibility (in HttpConnect.getProtocol())");
} catch (JUploadException e) {
uploadPolicy.displayWarn("Can't set property '"
+ UploadPolicy.PROP_ALLOW_HTTP_PERSISTENT
+ "' to false, in HttpConnect.getProtocol()");
}
break;
} else if (bRedirect) {
mLocation = pLocation.matcher(nextLine);
if (mLocation.matches()) {
// We found the location where we should go instead of the
// original postURL
this.uploadPolicy.displayDebug("Location read: "
+ mLocation.group(1), 50);
changePostURL(mLocation.group(1));
}
}
}
// Let's look for the web server kind: the applet works IIS only if
// allowHttpPersistent is false
s.close();
return protocol;
} // getProtocol()
|
diff --git a/collect-server/src/it/java/org/openforis/collect/CollectIntegrationTest.java b/collect-server/src/it/java/org/openforis/collect/CollectIntegrationTest.java
index fa9322c22..d2641b943 100644
--- a/collect-server/src/it/java/org/openforis/collect/CollectIntegrationTest.java
+++ b/collect-server/src/it/java/org/openforis/collect/CollectIntegrationTest.java
@@ -1,58 +1,59 @@
package org.openforis.collect;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.junit.runner.RunWith;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.collect.model.CollectSurveyContext;
import org.openforis.collect.persistence.SurveyDao;
import org.openforis.collect.persistence.SurveyImportException;
import org.openforis.collect.persistence.xml.UIOptionsBinder;
import org.openforis.idm.metamodel.xml.IdmlParseException;
import org.openforis.idm.metamodel.xml.SurveyIdmlBinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author S. Ricci
*
*/
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( locations = {"classpath:test-context.xml"} )
@TransactionConfiguration(defaultRollback=true)
@Transactional
public abstract class CollectIntegrationTest {
@Autowired
protected CollectSurveyContext collectSurveyContext;
@Autowired
protected SurveyDao surveyDao;
protected CollectSurvey loadSurvey() throws IdmlParseException, IOException {
URL idm = ClassLoader.getSystemResource("test.idm.xml");
InputStream is = idm.openStream();
SurveyIdmlBinder binder = new SurveyIdmlBinder(collectSurveyContext);
binder.addApplicationOptionsBinder(new UIOptionsBinder());
CollectSurvey survey = (CollectSurvey) binder.unmarshal(is);
survey.setName("archenland1");
+ survey.setWork(true);
return survey;
}
protected CollectSurvey importModel() throws SurveyImportException, IdmlParseException, IOException {
CollectSurvey survey = (CollectSurvey) loadSurvey();
surveyDao.importModel(survey);
return survey;
}
protected CollectSurvey createSurvey() {
CollectSurvey createSurvey = (CollectSurvey) collectSurveyContext.createSurvey();
return createSurvey;
}
}
| true | true | protected CollectSurvey loadSurvey() throws IdmlParseException, IOException {
URL idm = ClassLoader.getSystemResource("test.idm.xml");
InputStream is = idm.openStream();
SurveyIdmlBinder binder = new SurveyIdmlBinder(collectSurveyContext);
binder.addApplicationOptionsBinder(new UIOptionsBinder());
CollectSurvey survey = (CollectSurvey) binder.unmarshal(is);
survey.setName("archenland1");
return survey;
}
| protected CollectSurvey loadSurvey() throws IdmlParseException, IOException {
URL idm = ClassLoader.getSystemResource("test.idm.xml");
InputStream is = idm.openStream();
SurveyIdmlBinder binder = new SurveyIdmlBinder(collectSurveyContext);
binder.addApplicationOptionsBinder(new UIOptionsBinder());
CollectSurvey survey = (CollectSurvey) binder.unmarshal(is);
survey.setName("archenland1");
survey.setWork(true);
return survey;
}
|
diff --git a/src/java/ideah/compiler/HaskellSdkType.java b/src/java/ideah/compiler/HaskellSdkType.java
index 1fe5139..7b99f65 100644
--- a/src/java/ideah/compiler/HaskellSdkType.java
+++ b/src/java/ideah/compiler/HaskellSdkType.java
@@ -1,180 +1,181 @@
package ideah.compiler;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.containers.HashMap;
import ideah.util.ProcessLauncher;
import org.jdom.Element;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.*;
// todo: config page - do not include classpath/sourcepath/etc
public final class HaskellSdkType extends SdkType {
public static final HaskellSdkType INSTANCE = new HaskellSdkType();
private static final Icon GHC_ICON = IconLoader.getIcon("/ideah/haskell_16x16.png"); // todo: another icon?
public HaskellSdkType() {
super("GHC");
}
public String suggestHomePath() {
File haskellProgDir = null;
String[] ghcDirs = null;
if (SystemInfo.isLinux) {
haskellProgDir = new File("/usr/lib");
if (!haskellProgDir.exists())
return null;
ghcDirs = haskellProgDir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().startsWith("ghc") && new File(dir, name).isDirectory();
}
});
} else if (SystemInfo.isWindows) {
String progFiles = System.getenv("ProgramFiles(x86)");
if (progFiles == null) {
progFiles = System.getenv("ProgramFiles");
}
haskellProgDir = new File(progFiles, "Haskell Platform");
if (!haskellProgDir.exists())
return progFiles;
ghcDirs = haskellProgDir.list();
}
- return haskellProgDir == null
+ String latestVersion = getLatestVersion(ghcDirs);
+ return haskellProgDir == null || latestVersion == null
? null
- : new File(haskellProgDir, getLatestVersion(ghcDirs)).getAbsolutePath();
+ : new File(haskellProgDir, latestVersion).getAbsolutePath();
}
private static String getLatestVersion(String[] names) {
int length = names.length;
if (length == 0)
return null;
if (length == 1)
return names[0];
List<GHCDir> ghcDirs = new ArrayList<GHCDir>();
for (String name : names) {
ghcDirs.add(new GHCDir(name));
}
Collections.sort(ghcDirs, new Comparator<GHCDir>() {
public int compare(GHCDir d1, GHCDir d2) {
Integer[] version1 = d1.version;
Integer[] version2 = d2.version;
int minSize = Math.min(version1.length, version2.length);
for (int i = 0; i < minSize; i++) {
int compare = version1[i].compareTo(version2[i]);
if (compare != 0)
return compare;
}
return version1.length - version2.length;
}
});
return ghcDirs.get(ghcDirs.size() - 1).name;
}
public static boolean checkForGhc(File path) {
File bin = new File(path, "bin");
if (!bin.exists())
return false;
File[] children = bin.listFiles(new FileFilter() {
public boolean accept(File f) {
if (f.isDirectory())
return false;
return "ghc".equalsIgnoreCase(FileUtil.getNameWithoutExtension(f));
}
});
return children != null && children.length >= 1;
}
public boolean isValidSdkHome(String path) {
return checkForGhc(new File(path));
}
public String suggestSdkName(String currentSdkName, String sdkHome) {
String suggestedName;
if (currentSdkName != null && currentSdkName.length() > 0) {
suggestedName = currentSdkName;
} else {
String versionString = getVersionString(sdkHome);
if (versionString != null) {
suggestedName = "GHC " + versionString;
} else {
suggestedName = "Unknown";
}
}
return suggestedName;
}
private final Map<String, String> cachedVersionStrings = new HashMap<String, String>();
public String getVersionString(String sdkHome) {
if (cachedVersionStrings.containsKey(sdkHome)) {
return cachedVersionStrings.get(sdkHome);
}
String versionString = getGhcVersion(sdkHome);
if (versionString != null && versionString.length() == 0) {
versionString = null;
}
if (versionString != null) {
cachedVersionStrings.put(sdkHome, versionString);
}
return versionString;
}
@Nullable
public static String getGhcVersion(String homePath) {
if (homePath == null || !new File(homePath).exists()) {
return null;
}
try {
String output = new ProcessLauncher(
false, null,
homePath + File.separator + "bin" + File.separator + "ghc",
"--numeric-version"
).getStdOut();
return output.trim();
} catch (Exception ex) {
// ignore
}
return null;
}
public AdditionalDataConfigurable createAdditionalDataConfigurable(SdkModel sdkModel, SdkModificator sdkModificator) {
return null;
}
public void saveAdditionalData(SdkAdditionalData additionalData, Element additional) {
}
public String getPresentableName() {
return "GHC";
}
@Override
public Icon getIcon() {
return GHC_ICON;
}
@Override
public Icon getIconForAddAction() {
return getIcon();
}
@Override
public String adjustSelectedSdkHome(String homePath) {
return super.adjustSelectedSdkHome(homePath); // todo: if 'bin' or 'ghc' selected, choose parent folder
}
@Override
public void setupSdkPaths(Sdk sdk) {
// todo: ???
}
}
| false | true | public String suggestHomePath() {
File haskellProgDir = null;
String[] ghcDirs = null;
if (SystemInfo.isLinux) {
haskellProgDir = new File("/usr/lib");
if (!haskellProgDir.exists())
return null;
ghcDirs = haskellProgDir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().startsWith("ghc") && new File(dir, name).isDirectory();
}
});
} else if (SystemInfo.isWindows) {
String progFiles = System.getenv("ProgramFiles(x86)");
if (progFiles == null) {
progFiles = System.getenv("ProgramFiles");
}
haskellProgDir = new File(progFiles, "Haskell Platform");
if (!haskellProgDir.exists())
return progFiles;
ghcDirs = haskellProgDir.list();
}
return haskellProgDir == null
? null
: new File(haskellProgDir, getLatestVersion(ghcDirs)).getAbsolutePath();
}
| public String suggestHomePath() {
File haskellProgDir = null;
String[] ghcDirs = null;
if (SystemInfo.isLinux) {
haskellProgDir = new File("/usr/lib");
if (!haskellProgDir.exists())
return null;
ghcDirs = haskellProgDir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().startsWith("ghc") && new File(dir, name).isDirectory();
}
});
} else if (SystemInfo.isWindows) {
String progFiles = System.getenv("ProgramFiles(x86)");
if (progFiles == null) {
progFiles = System.getenv("ProgramFiles");
}
haskellProgDir = new File(progFiles, "Haskell Platform");
if (!haskellProgDir.exists())
return progFiles;
ghcDirs = haskellProgDir.list();
}
String latestVersion = getLatestVersion(ghcDirs);
return haskellProgDir == null || latestVersion == null
? null
: new File(haskellProgDir, latestVersion).getAbsolutePath();
}
|
diff --git a/bukkit/cpw/mods/fml/server/FMLBukkitHandler.java b/bukkit/cpw/mods/fml/server/FMLBukkitHandler.java
index f552501c..5e0286bb 100644
--- a/bukkit/cpw/mods/fml/server/FMLBukkitHandler.java
+++ b/bukkit/cpw/mods/fml/server/FMLBukkitHandler.java
@@ -1,514 +1,514 @@
/*
* The FML Forge Mod Loader suite. Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package cpw.mods.fml.server;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Random;
import java.util.logging.Logger;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.BaseMod;
import net.minecraft.server.BiomeBase;
import net.minecraft.server.CommonRegistry;
import net.minecraft.server.EntityItem;
import net.minecraft.server.EntityHuman;
import net.minecraft.server.IChunkProvider;
import net.minecraft.server.ICommandListener;
import net.minecraft.server.IInventory;
import net.minecraft.server.ItemStack;
import net.minecraft.server.NetworkManager;
import net.minecraft.server.Packet1Login;
import net.minecraft.server.Packet250CustomPayload;
import net.minecraft.server.Packet3Chat;
import net.minecraft.server.BukkitRegistry;
import net.minecraft.server.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.IFMLSidedHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
/**
* Handles primary communication from hooked code into the system
*
* The FML entry point is {@link #onPreLoad(MinecraftServer)} called from {@link MinecraftServer}
*
* Obfuscated code should focus on this class and other members of the "server" (or "client") code
*
* The actual mod loading is handled at arms length by {@link Loader}
*
* It is expected that a similar class will exist for each target environment: Bukkit and Client side.
*
* It should not be directly modified.
*
* @author cpw
*
*/
public class FMLBukkitHandler implements IFMLSidedHandler
{
/**
* The singleton
*/
private static final FMLBukkitHandler INSTANCE = new FMLBukkitHandler();
/**
* A reference to the server itself
*/
private MinecraftServer server;
/**
* A handy list of the default overworld biomes
*/
private BiomeBase[] defaultOverworldBiomes;
/**
* Called to start the whole game off from {@link MinecraftServer#startServer}
* @param minecraftServer
*/
public void onPreLoad(MinecraftServer minecraftServer)
{
try
{
Class.forName("BaseModMp", false, getClass().getClassLoader());
- MinecraftServer.field_6038_a.severe(""
+ MinecraftServer.log.severe(""
+ "Forge Mod Loader has detected that this server has an ModLoaderMP installed alongside Forge Mod Loader.\n"
+ "This will cause a serious problem with compatibility. To protect your worlds, this minecraft server will now shutdown.\n"
+ "You should follow the installation instructions of either Minecraft Forge of Forge Mod Loader and NOT install ModLoaderMP \n"
+ "into the minecraft_server.jar file "
+ "before this server will be allowed to start up.\n\nFailure to do so will simply result in more startup failures.\n\n"
+ "The authors of Minecraft Forge and Forge Mod Loader strongly suggest you talk to your mod's authors and get them to\nupdate their "
+ "requirements. ModLoaderMP is not compatible with Minecraft Forge on the server and they will need to update their mod\n"
+ "for Minecraft Forge and other server compatibility, unless they are Minecraft Forge mods, in which case they already\n"
+ "don't need ModLoaderMP and the mod author simply has failed to update his requirements and should be informed appropriately.\n\n"
+ "The authors of Forge Mod Loader would like to be compatible with ModLoaderMP but it is closed source and owned by SDK.\n"
+ "SDK, the author of ModLoaderMP, has a standing invitation to submit compatibility patches \n"
+ "to the open source community project that is Forge Mod Loader so that this incompatibility doesn't last. \n"
+ "Users who wish to enjoy mods of both types are "
+ "encouraged to request of SDK that he submit a\ncompatibility patch to the Forge Mod Loader project at \n"
+ "http://github.com/cpw/FML.\nPosting on the minecraft forums at\nhttp://www.minecraftforum.net/topic/86765- (the MLMP thread)\n"
+ "may encourage him in this effort. However, I ask that your requests be polite.\n"
+ "Now, the server has to shutdown so you can reinstall your minecraft_server.jar\nproperly, until such time as we can work together.");
throw new RuntimeException(
"This FML based server has detected an installation of ModLoaderMP alongside. This will cause serious compatibility issues, so the server will now shut down.");
}
catch (ClassNotFoundException e)
{
// We're safe. continue
}
server = minecraftServer;
FMLCommonHandler.instance().registerSidedDelegate(this);
CommonRegistry.registerRegistry(new BukkitRegistry());
Loader.instance().loadMods();
}
/**
* Called a bit later on during server initialization to finish loading mods
*/
public void onLoadComplete()
{
Loader.instance().initializeMods();
}
/**
* Every tick just before world and other ticks occur
*/
public void onPreTick()
{
FMLCommonHandler.instance().gameTickStart();
}
/**
* Every tick just after world and other ticks occur
*/
public void onPostTick()
{
FMLCommonHandler.instance().gameTickEnd();
}
/**
* Get the server instance
* @return
*/
public MinecraftServer getServer()
{
return server;
}
/**
* Get a handle to the server's logger instance
*/
public Logger getMinecraftLogger()
{
return MinecraftServer.log;
}
/**
* Called from ChunkProviderServer when a chunk needs to be populated
*
* To avoid polluting the worldgen seed, we generate a new random from the world seed and
* generate a seed from that
*
* @param chunkProvider
* @param chunkX
* @param chunkZ
* @param world
* @param generator
*/
public void onChunkPopulate(IChunkProvider chunkProvider, int chunkX, int chunkZ, World world, IChunkProvider generator)
{
Random fmlRandom = new Random(world.getSeed());
long xSeed = fmlRandom.nextLong() >> 2 + 1L;
long zSeed = fmlRandom.nextLong() >> 2 + 1L;
fmlRandom.setSeed((xSeed * chunkX + zSeed * chunkZ) ^ world.getSeed());
for (ModContainer mod : Loader.getModList())
{
if (mod.generatesWorld())
{
mod.getWorldGenerator().generate(fmlRandom, chunkX, chunkZ, world, generator, chunkProvider);
}
}
}
/**
* Called from the furnace to lookup fuel values
*
* @param itemId
* @param itemDamage
* @return
*/
public int fuelLookup(int itemId, int itemDamage)
{
int fv = 0;
for (ModContainer mod : Loader.getModList())
{
fv = Math.max(fv, mod.lookupFuelValue(itemId, itemDamage));
}
return fv;
}
/**
* Is the offered class and instance of BaseMod and therefore a ModLoader mod?
*/
public boolean isModLoaderMod(Class<?> clazz)
{
return BaseMod.class.isAssignableFrom(clazz);
}
/**
* Load the supplied mod class into a mod container
*/
public ModContainer loadBaseModMod(Class<?> clazz, File canonicalFile)
{
@SuppressWarnings("unchecked")
Class <? extends BaseMod > bmClazz = (Class <? extends BaseMod >) clazz;
return new ModLoaderModContainer(bmClazz, canonicalFile);
}
/**
* Called to notify that an item was picked up from the world
* @param entityItem
* @param entityPlayer
*/
public void notifyItemPickup(EntityItem entityItem, EntityHuman entityPlayer)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPickupNotification())
{
mod.getPickupNotifier().notifyPickup(entityItem, entityPlayer);
}
}
}
/**
* Raise an exception
* @param exception
* @param message
* @param stopGame
*/
public void raiseException(Throwable exception, String message, boolean stopGame)
{
FMLCommonHandler.instance().getFMLLogger().throwing("FMLHandler", "raiseException", exception);
throw new RuntimeException(exception);
}
/**
* Attempt to dispense the item as an entity other than just as a the item itself
*
* @param world
* @param x
* @param y
* @param z
* @param xVelocity
* @param zVelocity
* @param item
* @return
*/
public boolean tryDispensingEntity(World world, double x, double y, double z, byte xVelocity, byte zVelocity, ItemStack item)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsToDispense() && mod.getDispenseHandler().dispense(x, y, z, xVelocity, zVelocity, world, item))
{
return true;
}
}
return false;
}
/**
* @return the instance
*/
public static FMLBukkitHandler instance()
{
return INSTANCE;
}
/**
* Build a list of default overworld biomes
* @return
*/
public BiomeBase[] getDefaultOverworldBiomes()
{
if (defaultOverworldBiomes == null)
{
ArrayList<BiomeBase> biomes = new ArrayList<BiomeBase>(20);
for (int i = 0; i < 23; i++)
{
if ("Sky".equals(BiomeBase.biomes[i].y) || "Hell".equals(BiomeBase.biomes[i].y))
{
continue;
}
biomes.add(BiomeBase.biomes[i]);
}
defaultOverworldBiomes = new BiomeBase[biomes.size()];
biomes.toArray(defaultOverworldBiomes);
}
return defaultOverworldBiomes;
}
/**
* Called when an item is crafted
* @param player
* @param craftedItem
* @param craftingGrid
*/
public void onItemCrafted(EntityHuman player, ItemStack craftedItem, IInventory craftingGrid)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsCraftingNotification())
{
mod.getCraftingHandler().onCrafting(player, craftedItem, craftingGrid);
}
}
}
/**
* Called when an item is smelted
*
* @param player
* @param smeltedItem
*/
public void onItemSmelted(EntityHuman player, ItemStack smeltedItem)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsCraftingNotification())
{
mod.getCraftingHandler().onSmelting(player, smeltedItem);
}
}
}
/**
* Called when a chat packet is received
*
* @param chat
* @param player
* @return true if you want the packet to stop processing and not echo to the rest of the world
*/
public boolean handleChatPacket(Packet3Chat chat, EntityHuman player)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsNetworkPackets() && mod.getNetworkHandler().onChat(chat, player))
{
return true;
}
}
return false;
}
/**
* Called when a packet 250 packet is received from the player
* @param packet
* @param player
*/
public void handlePacket250(Packet250CustomPayload packet, EntityHuman player)
{
if ("REGISTER".equals(packet.tag) || "UNREGISTER".equals(packet.tag))
{
handleClientRegistration(packet, player);
return;
}
ModContainer mod = FMLCommonHandler.instance().getModForChannel(packet.tag);
if (mod != null)
{
mod.getNetworkHandler().onPacket250Packet(packet, player);
}
}
/**
* Handle register requests for packet 250 channels
* @param packet
*/
private void handleClientRegistration(Packet250CustomPayload packet, EntityHuman player)
{
if (packet.data==null) {
return;
}
try
{
for (String channel : new String(packet.data, "UTF8").split("\0"))
{
// Skip it if we don't know it
if (FMLCommonHandler.instance().getModForChannel(channel) == null)
{
continue;
}
if ("REGISTER".equals(packet.tag))
{
FMLCommonHandler.instance().activateChannel(player, channel);
}
else
{
FMLCommonHandler.instance().deactivateChannel(player, channel);
}
}
}
catch (UnsupportedEncodingException e)
{
getMinecraftLogger().warning("Received invalid registration packet");
}
}
/**
* Handle a login
* @param loginPacket
* @param networkManager
*/
public void handleLogin(Packet1Login loginPacket, NetworkManager networkManager)
{
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.tag = "REGISTER";
packet.data = FMLCommonHandler.instance().getPacketRegistry();
packet.length = packet.data.length;
if (packet.length>0) {
networkManager.queue(packet);
}
}
public void announceLogin(EntityHuman player) {
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPlayerTracking())
{
mod.getPlayerTracker().onPlayerLogin(player);
}
}
}
/**
* Are we a server?
*/
@Override
public boolean isServer()
{
return true;
}
/**
* Are we a client?
*/
@Override
public boolean isClient()
{
return false;
}
@Override
public File getMinecraftRootDirectory()
{
try {
return server.a(".").getCanonicalFile();
} catch (IOException ioe) {
return new File(".");
}
}
/**
* @param var2
* @return
*/
public boolean handleServerCommand(String command, String player, ICommandListener listener)
{
for (ModContainer mod : Loader.getModList()) {
if (mod.wantsConsoleCommands() && mod.getConsoleHandler().handleCommand(command, player, listener)) {
return true;
}
}
return false;
}
/**
* @param player
*/
public void announceLogout(EntityHuman player)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPlayerTracking())
{
mod.getPlayerTracker().onPlayerLogout(player);
}
}
}
/**
* @param p_28168_1_
*/
public void announceDimensionChange(EntityHuman player)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPlayerTracking())
{
mod.getPlayerTracker().onPlayerChangedDimension(player);
}
}
}
}
| true | true | public void onPreLoad(MinecraftServer minecraftServer)
{
try
{
Class.forName("BaseModMp", false, getClass().getClassLoader());
MinecraftServer.field_6038_a.severe(""
+ "Forge Mod Loader has detected that this server has an ModLoaderMP installed alongside Forge Mod Loader.\n"
+ "This will cause a serious problem with compatibility. To protect your worlds, this minecraft server will now shutdown.\n"
+ "You should follow the installation instructions of either Minecraft Forge of Forge Mod Loader and NOT install ModLoaderMP \n"
+ "into the minecraft_server.jar file "
+ "before this server will be allowed to start up.\n\nFailure to do so will simply result in more startup failures.\n\n"
+ "The authors of Minecraft Forge and Forge Mod Loader strongly suggest you talk to your mod's authors and get them to\nupdate their "
+ "requirements. ModLoaderMP is not compatible with Minecraft Forge on the server and they will need to update their mod\n"
+ "for Minecraft Forge and other server compatibility, unless they are Minecraft Forge mods, in which case they already\n"
+ "don't need ModLoaderMP and the mod author simply has failed to update his requirements and should be informed appropriately.\n\n"
+ "The authors of Forge Mod Loader would like to be compatible with ModLoaderMP but it is closed source and owned by SDK.\n"
+ "SDK, the author of ModLoaderMP, has a standing invitation to submit compatibility patches \n"
+ "to the open source community project that is Forge Mod Loader so that this incompatibility doesn't last. \n"
+ "Users who wish to enjoy mods of both types are "
+ "encouraged to request of SDK that he submit a\ncompatibility patch to the Forge Mod Loader project at \n"
+ "http://github.com/cpw/FML.\nPosting on the minecraft forums at\nhttp://www.minecraftforum.net/topic/86765- (the MLMP thread)\n"
+ "may encourage him in this effort. However, I ask that your requests be polite.\n"
+ "Now, the server has to shutdown so you can reinstall your minecraft_server.jar\nproperly, until such time as we can work together.");
throw new RuntimeException(
"This FML based server has detected an installation of ModLoaderMP alongside. This will cause serious compatibility issues, so the server will now shut down.");
}
catch (ClassNotFoundException e)
{
// We're safe. continue
}
server = minecraftServer;
FMLCommonHandler.instance().registerSidedDelegate(this);
CommonRegistry.registerRegistry(new BukkitRegistry());
Loader.instance().loadMods();
}
| public void onPreLoad(MinecraftServer minecraftServer)
{
try
{
Class.forName("BaseModMp", false, getClass().getClassLoader());
MinecraftServer.log.severe(""
+ "Forge Mod Loader has detected that this server has an ModLoaderMP installed alongside Forge Mod Loader.\n"
+ "This will cause a serious problem with compatibility. To protect your worlds, this minecraft server will now shutdown.\n"
+ "You should follow the installation instructions of either Minecraft Forge of Forge Mod Loader and NOT install ModLoaderMP \n"
+ "into the minecraft_server.jar file "
+ "before this server will be allowed to start up.\n\nFailure to do so will simply result in more startup failures.\n\n"
+ "The authors of Minecraft Forge and Forge Mod Loader strongly suggest you talk to your mod's authors and get them to\nupdate their "
+ "requirements. ModLoaderMP is not compatible with Minecraft Forge on the server and they will need to update their mod\n"
+ "for Minecraft Forge and other server compatibility, unless they are Minecraft Forge mods, in which case they already\n"
+ "don't need ModLoaderMP and the mod author simply has failed to update his requirements and should be informed appropriately.\n\n"
+ "The authors of Forge Mod Loader would like to be compatible with ModLoaderMP but it is closed source and owned by SDK.\n"
+ "SDK, the author of ModLoaderMP, has a standing invitation to submit compatibility patches \n"
+ "to the open source community project that is Forge Mod Loader so that this incompatibility doesn't last. \n"
+ "Users who wish to enjoy mods of both types are "
+ "encouraged to request of SDK that he submit a\ncompatibility patch to the Forge Mod Loader project at \n"
+ "http://github.com/cpw/FML.\nPosting on the minecraft forums at\nhttp://www.minecraftforum.net/topic/86765- (the MLMP thread)\n"
+ "may encourage him in this effort. However, I ask that your requests be polite.\n"
+ "Now, the server has to shutdown so you can reinstall your minecraft_server.jar\nproperly, until such time as we can work together.");
throw new RuntimeException(
"This FML based server has detected an installation of ModLoaderMP alongside. This will cause serious compatibility issues, so the server will now shut down.");
}
catch (ClassNotFoundException e)
{
// We're safe. continue
}
server = minecraftServer;
FMLCommonHandler.instance().registerSidedDelegate(this);
CommonRegistry.registerRegistry(new BukkitRegistry());
Loader.instance().loadMods();
}
|
diff --git a/src/main/java/org/mongolink/domain/mapper/CollectionMapper.java b/src/main/java/org/mongolink/domain/mapper/CollectionMapper.java
index 034cc79..693663b 100644
--- a/src/main/java/org/mongolink/domain/mapper/CollectionMapper.java
+++ b/src/main/java/org/mongolink/domain/mapper/CollectionMapper.java
@@ -1,87 +1,88 @@
/*
* MongoLink, Object Document Mapper for Java and MongoDB
*
* Copyright (c) 2012, Arpinum or third-party contributors as
* indicated by the @author tags
*
* MongoLink is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MongoLink 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
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public License
* along with MongoLink. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.mongolink.domain.mapper;
import com.mongodb.*;
import org.apache.log4j.Logger;
import org.mongolink.domain.converter.Converter;
import org.mongolink.utils.*;
import java.lang.reflect.*;
import java.util.Collection;
class CollectionMapper implements Mapper {
public CollectionMapper(MethodContainer methodContainer) {
this.name = methodContainer.shortName();
this.method = methodContainer.getMethod();
}
@Override
public void save(Object instance, DBObject into) {
try {
Collection collection = (Collection) method.invoke(instance);
BasicDBList list = new BasicDBList();
for (Object child : collection) {
Object childObject = context().converterFor(child.getClass()).toDbValue(child);
list.add(childObject);
}
into.put(name, list);
} catch (Exception e) {
LOGGER.error("Can't saveInto collection " + name, e);
}
}
@Override
public void populate(Object instance, DBObject from) {
try {
Field field = ReflectionUtils.findPrivateField(instance.getClass(), name);
field.setAccessible(true);
ParameterizedType elementType = (ParameterizedType) field.getGenericType();
Converter childMapper = context().converterFor((Class<?>) elementType.getActualTypeArguments()[0]);
BasicDBList list = (BasicDBList) from.get(name);
if (list != null) {
Collection collection = (Collection) field.get(instance);
+ collection.clear();
for (Object o : list) {
collection.add(childMapper.fromDbValue(o));
}
}
field.setAccessible(false);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
private MapperContext context() {
return mapper.getContext();
}
public void setMapper(ClassMapper<?> mapper) {
this.mapper = mapper;
}
private final Method method;
private final String name;
private ClassMapper<?> mapper;
private static final Logger LOGGER = Logger.getLogger(CollectionMapper.class);
}
| true | true | public void populate(Object instance, DBObject from) {
try {
Field field = ReflectionUtils.findPrivateField(instance.getClass(), name);
field.setAccessible(true);
ParameterizedType elementType = (ParameterizedType) field.getGenericType();
Converter childMapper = context().converterFor((Class<?>) elementType.getActualTypeArguments()[0]);
BasicDBList list = (BasicDBList) from.get(name);
if (list != null) {
Collection collection = (Collection) field.get(instance);
for (Object o : list) {
collection.add(childMapper.fromDbValue(o));
}
}
field.setAccessible(false);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
| public void populate(Object instance, DBObject from) {
try {
Field field = ReflectionUtils.findPrivateField(instance.getClass(), name);
field.setAccessible(true);
ParameterizedType elementType = (ParameterizedType) field.getGenericType();
Converter childMapper = context().converterFor((Class<?>) elementType.getActualTypeArguments()[0]);
BasicDBList list = (BasicDBList) from.get(name);
if (list != null) {
Collection collection = (Collection) field.get(instance);
collection.clear();
for (Object o : list) {
collection.add(childMapper.fromDbValue(o));
}
}
field.setAccessible(false);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
|
diff --git a/src/net/rptools/maptool/client/ui/MapToolFrame.java b/src/net/rptools/maptool/client/ui/MapToolFrame.java
index 08e984ba..030b0199 100644
--- a/src/net/rptools/maptool/client/ui/MapToolFrame.java
+++ b/src/net/rptools/maptool/client/ui/MapToolFrame.java
@@ -1,1186 +1,1186 @@
/* 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.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Observer;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import net.rptools.lib.FileUtil;
import net.rptools.lib.MD5Key;
import net.rptools.lib.image.ImageUtil;
import net.rptools.lib.swing.AboutDialog;
import net.rptools.lib.swing.ColorPicker;
import net.rptools.lib.swing.PositionalLayout;
import net.rptools.lib.swing.SwingUtil;
import net.rptools.lib.swing.preference.FramePreferences;
import net.rptools.maptool.client.AppActions;
import net.rptools.maptool.client.AppConstants;
import net.rptools.maptool.client.AppListeners;
import net.rptools.maptool.client.AppPreferences;
import net.rptools.maptool.client.AppStyle;
import net.rptools.maptool.client.AppUtil;
import net.rptools.maptool.client.MapTool;
import net.rptools.maptool.client.ServerDisconnectHandler;
import net.rptools.maptool.client.ZoneActivityListener;
import net.rptools.maptool.client.swing.CoordinateStatusBar;
import net.rptools.maptool.client.swing.GlassPane;
import net.rptools.maptool.client.swing.MemoryStatusBar;
import net.rptools.maptool.client.swing.PenWidthChooser;
import net.rptools.maptool.client.swing.ProgressStatusBar;
import net.rptools.maptool.client.swing.ScrollableFlowPanel;
import net.rptools.maptool.client.swing.SpacerStatusBar;
import net.rptools.maptool.client.swing.StatusPanel;
import net.rptools.maptool.client.tool.FacingTool;
import net.rptools.maptool.client.tool.GridTool;
import net.rptools.maptool.client.tool.MeasureTool;
import net.rptools.maptool.client.tool.PointerTool;
import net.rptools.maptool.client.tool.StampTool;
import net.rptools.maptool.client.tool.TextTool;
import net.rptools.maptool.client.tool.drawing.ConeTemplateTool;
import net.rptools.maptool.client.tool.drawing.FreehandExposeTool;
import net.rptools.maptool.client.tool.drawing.FreehandTool;
import net.rptools.maptool.client.tool.drawing.LineTemplateTool;
import net.rptools.maptool.client.tool.drawing.LineTool;
import net.rptools.maptool.client.tool.drawing.OvalExposeTool;
import net.rptools.maptool.client.tool.drawing.OvalTool;
import net.rptools.maptool.client.tool.drawing.PolygonExposeTool;
import net.rptools.maptool.client.tool.drawing.PolygonTopologyTool;
import net.rptools.maptool.client.tool.drawing.RadiusTemplateTool;
import net.rptools.maptool.client.tool.drawing.RectangleExposeTool;
import net.rptools.maptool.client.tool.drawing.RectangleTool;
import net.rptools.maptool.client.tool.drawing.RectangleTopologyTool;
import net.rptools.maptool.client.ui.assetpanel.AssetDirectory;
import net.rptools.maptool.client.ui.assetpanel.AssetPanel;
import net.rptools.maptool.client.ui.commandpanel.CommandPanel;
import net.rptools.maptool.client.ui.token.TokenPropertiesDialog;
import net.rptools.maptool.client.ui.tokenpanel.TokenPanelTreeCellRenderer;
import net.rptools.maptool.client.ui.tokenpanel.TokenPanelTreeModel;
import net.rptools.maptool.client.ui.zone.NewZoneDropPanel;
import net.rptools.maptool.client.ui.zone.NotificationOverlay;
import net.rptools.maptool.client.ui.zone.PointerOverlay;
import net.rptools.maptool.client.ui.zone.ZoneRenderer;
import net.rptools.maptool.client.ui.zone.ZoneSelectionPanel;
import net.rptools.maptool.model.Asset;
import net.rptools.maptool.model.AssetAvailableListener;
import net.rptools.maptool.model.AssetManager;
import net.rptools.maptool.model.GUID;
import net.rptools.maptool.model.ObservableList;
import net.rptools.maptool.model.TextMessage;
import net.rptools.maptool.model.Token;
import net.rptools.maptool.model.Zone;
import net.rptools.maptool.model.ZonePoint;
import net.rptools.maptool.model.drawing.Pen;
import net.rptools.maptool.util.ImageManager;
import org.flexdock.docking.Dockable;
import org.flexdock.docking.DockableFactory;
import org.flexdock.docking.DockingConstants;
import org.flexdock.docking.DockingManager;
import org.flexdock.docking.defaults.StandardBorderManager;
import org.flexdock.docking.state.PersistenceException;
import org.flexdock.perspective.LayoutSequence;
import org.flexdock.perspective.Perspective;
import org.flexdock.perspective.PerspectiveFactory;
import org.flexdock.perspective.PerspectiveManager;
import org.flexdock.perspective.persist.FilePersistenceHandler;
import org.flexdock.perspective.persist.PersistenceHandler;
import org.flexdock.plaf.common.border.ShadowBorder;
import org.flexdock.view.View;
import org.flexdock.view.Viewport;
/**
*/
public class MapToolFrame extends JFrame implements WindowListener {
private static final long serialVersionUID = 3905523813025329458L;
// TODO: parameterize this (or make it a preference)
private static final int WINDOW_WIDTH = 800;
private static final int WINDOW_HEIGHT = 600;
private Pen pen = new Pen(Pen.DEFAULT);
/**
* Are the drawing measurements being painted?
*/
private boolean paintDrawingMeasurement = true;
// Components
private ZoneRenderer currentRenderer;
private AssetPanel assetPanel;
private PointerOverlay pointerOverlay;
private CommandPanel commandPanel;
private AboutDialog aboutDialog;
private ColorPicker colorPicker;
private Toolbox toolbox;
private ZoneSelectionPanel zoneSelectionPanel;
private JPanel zoneRendererPanel;
private JPanel visibleControlPanel;
private FullScreenFrame fullScreenFrame;
private JPanel rendererBorderPanel;
private List<ZoneRenderer> zoneRendererList;
private JMenuBar menuBar;
private PenWidthChooser widthChooser = new PenWidthChooser();
private StatusPanel statusPanel;
private ActivityMonitorPanel activityMonitor = new ActivityMonitorPanel();
private ProgressStatusBar progressBar = new ProgressStatusBar();
private ConnectionStatusPanel connectionStatusPanel = new ConnectionStatusPanel();
private CoordinateStatusBar coordinateStatusBar;
private NewZoneDropPanel newZoneDropPanel;
private JLabel chatActionLabel;
private GlassPane glassPane;
private JPanel macroButtonPanel;
// Components
private JFileChooser loadFileChooser;
private JFileChooser saveFileChooser;
private TokenPropertiesDialog tokenPropertiesDialog = new TokenPropertiesDialog();
// TODO: I don't like this here, eventOverlay should be more abstracted
private NotificationOverlay notificationOverlay = new NotificationOverlay();
// TODO: Find a better pattern for this
private Timer repaintTimer;
public MapToolFrame() {
// Set up the frame
super(AppConstants.APP_NAME);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(this);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
SwingUtil.centerOnScreen(this);
setFocusTraversalPolicy(new MapToolFocusTraversalPolicy());
// Components
glassPane = new GlassPane();
assetPanel = createAssetPanel();
toolbox = new Toolbox();
zoneRendererList = new CopyOnWriteArrayList<ZoneRenderer>();
pointerOverlay = new PointerOverlay();
colorPicker = new ColorPicker(this);
String credits = "";
String version = "";
Image logo = null;
try {
credits = new String(FileUtil
.loadResource("net/rptools/maptool/client/credits.html"));
version = MapTool.getVersion();
credits = credits.replace("%VERSION%", version);
logo = ImageUtil.getImage("net/rptools/lib/image/rptools-logo.png");
} catch (Exception ioe) {
System.err.println("Unable to load credits or version");
}
aboutDialog = new AboutDialog(this, logo, credits);
aboutDialog.setSize(354, 400);
statusPanel = new StatusPanel();
statusPanel.addPanel(getCoordinateStatusBar());
statusPanel.addPanel(new MemoryStatusBar());
// statusPanel.addPanel(progressBar);
statusPanel.addPanel(connectionStatusPanel);
statusPanel.addPanel(activityMonitor);
statusPanel.addPanel(new SpacerStatusBar(25));
zoneSelectionPanel = new ZoneSelectionPanel();
zoneSelectionPanel.setSize(100, 100);
AppListeners.addZoneListener(zoneSelectionPanel);
newZoneDropPanel = new NewZoneDropPanel();
zoneRendererPanel = new JPanel(new PositionalLayout(5));
zoneRendererPanel.setBackground(Color.black);
zoneRendererPanel.add(newZoneDropPanel,
PositionalLayout.Position.CENTER);
zoneRendererPanel.add(zoneSelectionPanel, PositionalLayout.Position.SE);
zoneRendererPanel.add(getChatActionLabel(),
PositionalLayout.Position.SW);
commandPanel = new CommandPanel();
MapTool.getMessageList().addObserver(commandPanel);
MapTool.getMessageList().addObserver(createChatIconMessageObserver());
rendererBorderPanel = new JPanel(new GridLayout());
rendererBorderPanel.add(zoneRendererPanel);
// Docking
JPanel dockingPanel = new JPanel(new BorderLayout(0, 0));
dockingPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
Viewport viewport = new Viewport();
viewport.setBorderManager(new StandardBorderManager(new ShadowBorder()));
dockingPanel.add(viewport, BorderLayout.CENTER);
DockingManager.setDockableFactory(new MapToolViewFactory());
PerspectiveManager.setFactory(new MapToolPrespectiveFactory());
PerspectiveManager.getInstance().setCurrentPerspective(PERSPECTIVEID, true);
PerspectiveManager.setPersistenceHandler(new FilePersistenceHandler(AppUtil.getAppHome("config").getAbsolutePath() + "/layout.xml"));
-// try{
-// DockingManager.loadLayoutModel();
- DockingManager.restoreLayout();
-// } catch(IOException e) {
-// e.printStackTrace();
-// } catch (PersistenceException e) {
-// e.printStackTrace();
-// }
+ try{
+ DockingManager.loadLayoutModel();
+ } catch(IOException e) {
+ e.printStackTrace();
+ } catch (PersistenceException e) {
+ e.printStackTrace();
+ }
+ DockingManager.setAutoPersist(true);
EventQueue.invokeLater(new Runnable() {
public void run() {
- DockingManager.setAutoPersist(true);
+ DockingManager.restoreLayout();
}
});
// Put it all together
menuBar = new AppMenuBar();
setJMenuBar(menuBar);
setLayout(new BorderLayout());
add(BorderLayout.CENTER, dockingPanel);
add(BorderLayout.NORTH, new ToolbarPanel(toolbox));
add(BorderLayout.SOUTH, statusPanel);
setGlassPane(glassPane);
// TODO: Put together a class that handles adding in the listeners, just
// so that this doesn't
// get all cluttered
AppListeners.addZoneListener(new RequestZoneAssetsListener());
new FramePreferences(AppConstants.APP_NAME, "mainFrame", this);
// setSize(800, 600);
restorePreferences();
repaintTimer = new Timer(1000, new RepaintTimer());
repaintTimer.start();
}
public JPanel createMacroButtonPanel() {
JPanel panel = new ScrollableFlowPanel(FlowLayout.LEFT);
for (int i = 1; i < 40; i++) {
panel.add(new MacroButton(i, null, true));
}
return panel;
}
public TokenPropertiesDialog getTokenPropertiesDialog() {
return tokenPropertiesDialog;
}
public void refresh() {
if (getCurrentZoneRenderer() != null) {
getCurrentZoneRenderer().repaint();
}
}
public JFileChooser getLoadFileChooser() {
if (loadFileChooser == null) {
loadFileChooser = new JFileChooser();
loadFileChooser.setCurrentDirectory(AppPreferences.getLoadDir());
}
return loadFileChooser;
}
public JFileChooser getSaveFileChooser() {
if (saveFileChooser == null) {
saveFileChooser = new JFileChooser();
saveFileChooser.setCurrentDirectory(AppPreferences.getSaveDir());
}
return saveFileChooser;
}
public void showControlPanel(JPanel panel) {
panel.setSize(panel.getPreferredSize());
zoneRendererPanel.add(panel, PositionalLayout.Position.NE);
zoneRendererPanel.setComponentZOrder(panel, 0);
zoneRendererPanel.revalidate();
zoneRendererPanel.repaint();
visibleControlPanel = panel;
}
public CoordinateStatusBar getCoordinateStatusBar() {
if (coordinateStatusBar == null) {
coordinateStatusBar = new CoordinateStatusBar();
}
return coordinateStatusBar;
}
public void hideControlPanel() {
if (visibleControlPanel != null) {
if (zoneRendererPanel != null) {
zoneRendererPanel.remove(visibleControlPanel);
}
visibleControlPanel = null;
refresh();
}
}
public void showNonModalGlassPane(JComponent component, int x, int y) {
showGlassPane(component, x, y, false);
}
public void showModalGlassPane(JComponent component, int x, int y) {
showGlassPane(component, x, y, true);
}
private void showGlassPane(JComponent component, int x, int y, boolean modal) {
component.setSize(component.getPreferredSize());
component.setLocation(x, y);
glassPane.setLayout(null);
glassPane.add(component);
glassPane.setModel(modal);
glassPane.setVisible(true);
}
public void showFilledGlassPane(JComponent component) {
glassPane.setLayout(new GridLayout());
glassPane.add(component);
glassPane.setVisible(true);
}
public void hideGlassPane() {
glassPane.removeAll();
glassPane.setVisible(false);
}
@Override
public void setVisible(boolean b) {
// mainSplitPane.setInitialDividerPosition(150);
// rightSplitPane.setInitialDividerPosition(getSize().height-200);
// new SplitPanePreferences(AppConstants.APP_NAME, "mainSplitPane",
// mainSplitPane);
// new SplitPanePreferences(AppConstants.APP_NAME, "rightSplitPane",
// rightSplitPane);
super.setVisible(b);
hideCommandPanel();
}
public JLabel getChatActionLabel() {
if (chatActionLabel == null) {
chatActionLabel = new JLabel(new ImageIcon(AppStyle.chatImage));
chatActionLabel.setSize(chatActionLabel.getPreferredSize());
chatActionLabel.setVisible(false);
chatActionLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
showCommandPanel();
}
});
}
return chatActionLabel;
}
private Observer createChatIconMessageObserver() {
return new Observer() {
public void update(java.util.Observable o, Object arg) {
ObservableList<TextMessage> textList = MapTool.getMessageList();
ObservableList.Event event = (ObservableList.Event) arg;
// if (rightSplitPane.isBottomHidden() && event ==
// ObservableList.Event.append) {
//
// getChatActionLabel().setVisible(true);
// }
}
};
}
public void showCommandPanel() {
chatActionLabel.setVisible(false);
// rightSplitPane.showBottom();
commandPanel.requestFocus();
}
public void hideCommandPanel() {
// rightSplitPane.hideBottom();
}
public ColorPicker getColorPicker() {
return colorPicker;
}
public void showAboutDialog() {
aboutDialog.setVisible(true);
}
public ConnectionStatusPanel getConnectionStatusPanel() {
return connectionStatusPanel;
}
public NotificationOverlay getNotificationOverlay() {
return notificationOverlay;
}
private void restorePreferences() {
List<File> assetRootList = AppPreferences.getAssetRoots();
for (File file : assetRootList) {
addAssetRoot(file);
}
}
private TokenPanelTreeModel tokenPanelTreeModel;
private JComponent createTokenTreePanel() {
final JTree tree = new JTree();
tokenPanelTreeModel = new TokenPanelTreeModel(tree);
tree.setModel(tokenPanelTreeModel);
tree.setCellRenderer(new TokenPanelTreeCellRenderer());
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
tree.addMouseListener(new MouseAdapter() {
// TODO: Make this a handler class, not an aic
@Override
public void mousePressed(MouseEvent e) {
// tree.setSelectionPath(tree.getPathForLocation(e.getX(),
// e.getY()));
TreePath path = tree.getPathForLocation(e.getX(), e.getY());
if (path == null) {
return;
}
Object row = path.getLastPathComponent();
int rowIndex = tree.getRowForLocation(e.getX(), e.getY());
if (SwingUtilities.isLeftMouseButton(e)) {
if (!SwingUtil.isShiftDown(e)) {
tree.clearSelection();
}
tree.addSelectionInterval(rowIndex, rowIndex);
if (row instanceof Token) {
if (e.getClickCount() == 2) {
Token token = (Token) row;
getCurrentZoneRenderer().clearSelectedTokens();
getCurrentZoneRenderer().centerOn(
new ZonePoint(token.getX(), token.getY()));
// Pick an appropriate tool
if (token.isToken()) {
getToolbox().setSelectedTool(PointerTool.class);
} else {
getCurrentZoneRenderer().setActiveLayer(
token.isStamp() ? Zone.Layer.OBJECT
: Zone.Layer.BACKGROUND);
getToolbox().setSelectedTool(StampTool.class);
}
getCurrentZoneRenderer().selectToken(token.getId());
getCurrentZoneRenderer().requestFocusInWindow();
}
}
}
if (SwingUtilities.isRightMouseButton(e)) {
if (!isRowSelected(tree.getSelectionRows(), rowIndex)
&& !SwingUtil.isShiftDown(e)) {
tree.clearSelection();
tree.addSelectionInterval(rowIndex, rowIndex);
}
final int x = e.getX();
final int y = e.getY();
EventQueue.invokeLater(new Runnable() {
public void run() {
Token firstToken = null;
Set<GUID> selectedTokenSet = new HashSet<GUID>();
for (TreePath path : tree.getSelectionPaths()) {
if (path.getLastPathComponent() instanceof Token) {
Token token = (Token) path
.getLastPathComponent();
if (firstToken == null) {
firstToken = token;
}
if (AppUtil.playerOwns(token)) {
selectedTokenSet.add(token.getId());
}
}
}
if (selectedTokenSet.size() > 0) {
if (firstToken.isStamp()
|| firstToken.isBackground()) {
new StampPopupMenu(selectedTokenSet, x, y,
getCurrentZoneRenderer(),
firstToken).showPopup(tree);
} else {
new TokenPopupMenu(selectedTokenSet, x, y,
getCurrentZoneRenderer(),
firstToken).showPopup(tree);
}
}
}
});
}
}
});
AppListeners.addZoneListener(new ZoneActivityListener() {
public void zoneActivated(Zone zone) {
tokenPanelTreeModel.setZone(zone);
}
public void zoneAdded(Zone zone) {
// nothing to do
}
});
return tree;
}
public void updateTokenTree() {
if (tokenPanelTreeModel != null) {
tokenPanelTreeModel.update();
}
}
private boolean isRowSelected(int[] selectedRows, int row) {
if (selectedRows == null) {
return false;
}
for (int selectedRow : selectedRows) {
if (row == selectedRow) {
return true;
}
}
return false;
}
private AssetPanel createAssetPanel() {
final AssetPanel panel = new AssetPanel("mainAssetPanel");
panel.addImagePanelMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO use for real popup logic
if (SwingUtilities.isLeftMouseButton(e)) {
if (e.getClickCount() == 2) {
List<Object> idList = panel.getSelectedIds();
if (idList == null || idList.size() == 0) {
return;
}
final int index = (Integer) idList.get(0);
createZone(panel.getAsset(index), Zone.Type.MAP);
}
}
if (SwingUtilities.isRightMouseButton(e)) {
List<Object> idList = panel.getSelectedIds();
if (idList == null || idList.size() == 0) {
return;
}
final int index = (Integer) idList.get(0);
JPopupMenu menu = new JPopupMenu();
menu.add(new JMenuItem(new AbstractAction() {
{
putValue(NAME, "New Bounded Map");
}
public void actionPerformed(ActionEvent e) {
createZone(panel.getAsset(index), Zone.Type.MAP);
}
}));
menu.add(new JMenuItem(new AbstractAction() {
{
putValue(NAME, "New Unbounded Map");
}
public void actionPerformed(ActionEvent e) {
createZone(panel.getAsset(index),
Zone.Type.INFINITE);
}
}));
panel.showImagePanelPopup(menu, e.getX(), e.getY());
}
}
private void createZone(Asset asset, int type) {
NewMapDialog newMapDialog = new NewMapDialog(MapTool.getFrame());
newMapDialog.setSelectedAsset(asset);
newMapDialog.setZoneType(type);
newMapDialog.setVisible(true);
}
});
return panel;
}
public PointerOverlay getPointerOverlay() {
return pointerOverlay;
}
public void setStatusMessage(final String message) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
statusPanel.setStatus(" " + message);
}
});
}
protected JComponent createPlayerList() {
ClientConnectionPanel panel = new ClientConnectionPanel();
return panel;
}
public ActivityMonitorPanel getActivityMonitor() {
return activityMonitor;
}
public void startIndeterminateAction() {
progressBar.startIndeterminate();
}
public void endIndeterminateAction() {
progressBar.endIndeterminate();
}
public void startDeterminateAction(int totalWork) {
progressBar.startDeterminate(totalWork);
}
public void updateDeterminateActionProgress(int additionalWorkCompleted) {
progressBar.updateDeterminateProgress(additionalWorkCompleted);
}
public void endDeterminateAction() {
progressBar.endDeterminate();
}
public ZoneSelectionPanel getZoneSelectionPanel() {
return zoneSelectionPanel;
}
// /////////////////////////////////////////////////////////////////////////
// static methods
// /////////////////////////////////////////////////////////////////////////
public void toggleAssetTree() {
// if (mainSplitPane.isLeftHidden()) {
// mainSplitPane.showLeft();
// } else {
// mainSplitPane.hideLeft();
// }
}
public boolean isAssetTreeVisible() {
// return !mainSplitPane.isLeftHidden();
return true;
}
public CommandPanel getCommandPanel() {
return commandPanel;
}
public AssetPanel getAssetPanel() {
return assetPanel;
}
public void addAssetRoot(File rootDir) {
assetPanel.addAssetRoot(new AssetDirectory(rootDir,
AppConstants.IMAGE_FILE_FILTER));
// if (mainSplitPane.isLeftHidden()) {
// mainSplitPane.showLeft();
// }
}
public Pen getPen() {
pen.setColor(colorPicker.getForegroundColor().getRGB());
pen.setBackgroundColor(colorPicker.getBackgroundColor().getRGB());
pen.setThickness((Integer) widthChooser.getSelectedItem());
return pen;
}
public List<ZoneRenderer> getZoneRenderers() {
// TODO: This should prob be immutable
return zoneRendererList;
}
public ZoneRenderer getCurrentZoneRenderer() {
return currentRenderer;
}
public void addZoneRenderer(ZoneRenderer renderer) {
zoneRendererList.add(renderer);
}
public void removeZoneRenderer(ZoneRenderer renderer) {
boolean isCurrent = renderer == getCurrentZoneRenderer();
zoneRendererList.remove(renderer);
if (isCurrent) {
setCurrentZoneRenderer(zoneRendererList.size() > 0 ? zoneRendererList
.get(0)
: null);
}
zoneSelectionPanel.flush();
zoneSelectionPanel.repaint();
}
public void clearZoneRendererList() {
zoneRendererList.clear();
zoneSelectionPanel.flush();
zoneSelectionPanel.repaint();
}
public void setCurrentZoneRenderer(ZoneRenderer renderer) {
// Handle new renderers
// TODO: should this be here ?
if (renderer != null && !zoneRendererList.contains(renderer)) {
zoneRendererList.add(renderer);
}
// Handle first renderer
if (newZoneDropPanel != null) {
zoneRendererPanel.remove(newZoneDropPanel);
newZoneDropPanel = null;
}
if (currentRenderer != null) {
currentRenderer.flush();
zoneRendererPanel.remove(currentRenderer);
currentRenderer.setRepaintTimer(null);
}
// Back to the pointer
getToolbox().setSelectedTool(PointerTool.class);
if (renderer != null) {
zoneRendererPanel.add(renderer, PositionalLayout.Position.CENTER);
zoneRendererPanel.doLayout();
}
currentRenderer = renderer;
toolbox.setTargetRenderer(renderer);
if (renderer != null) {
AppListeners.fireZoneActivated(renderer.getZone());
renderer.requestFocusInWindow();
renderer.setRepaintTimer(repaintTimer);
}
updateTokenTree();
AppActions.updateActions();
repaint();
}
public Toolbox getToolbox() {
return toolbox;
}
public ZoneRenderer getZoneRenderer(Zone zone) {
for (ZoneRenderer renderer : zoneRendererList) {
if (zone == renderer.getZone()) {
return renderer;
}
}
return null;
}
public ZoneRenderer getZoneRenderer(GUID zoneGUID) {
for (ZoneRenderer renderer : zoneRendererList) {
if (zoneGUID.equals(renderer.getZone().getId())) {
return renderer;
}
}
return null;
}
/**
* Get the paintDrawingMeasurements for this MapToolClient.
*
* @return Returns the current value of paintDrawingMeasurements.
*/
public boolean isPaintDrawingMeasurement() {
return paintDrawingMeasurement;
}
/**
* Set the value of paintDrawingMeasurements for this MapToolClient.
*
* @param aPaintDrawingMeasurements
* The paintDrawingMeasurements to set.
*/
public void setPaintDrawingMeasurement(boolean aPaintDrawingMeasurements) {
paintDrawingMeasurement = aPaintDrawingMeasurements;
}
public void showFullScreen() {
GraphicsConfiguration graphicsConfig = getGraphicsConfiguration();
GraphicsDevice device = graphicsConfig.getDevice();
Rectangle bounds = graphicsConfig.getBounds();
fullScreenFrame = new FullScreenFrame();
fullScreenFrame.add(zoneRendererPanel);
fullScreenFrame.setBounds(bounds.x, bounds.y, bounds.width,
bounds.height);
fullScreenFrame.setJMenuBar(menuBar);
menuBar.setVisible(false);
fullScreenFrame.setVisible(true);
this.setVisible(false);
}
public boolean isFullScreen() {
return fullScreenFrame != null;
}
public void showWindowed() {
if (fullScreenFrame == null) {
return;
}
rendererBorderPanel.add(zoneRendererPanel);
setJMenuBar(menuBar);
menuBar.setVisible(true);
this.setVisible(true);
fullScreenFrame.dispose();
fullScreenFrame = null;
}
public class FullScreenFrame extends JFrame {
public FullScreenFrame() {
setUndecorated(true);
}
}
private class RequestZoneAssetsListener implements ZoneActivityListener {
public void zoneActivated(final Zone zone) {
AssetAvailableListener listener = new AssetAvailableListener() {
public void assetAvailable(net.rptools.lib.MD5Key key) {
ZoneRenderer renderer = getCurrentZoneRenderer();
if (renderer.getZone() == zone) {
ImageManager.getImage(AssetManager.getAsset(key),
renderer);
}
}
};
// Let's add all the assets, starting with the backgrounds
for (Token token : zone.getBackgroundTokens()) {
MD5Key key = token.getAssetID();
if (AssetManager.hasAsset(key)) {
ImageManager.getImage(AssetManager.getAsset(key));
} else {
if (!AssetManager.isAssetRequested(key)) {
AssetManager.addAssetListener(token.getAssetID(),
listener);
// This will force a server request if we don't already
// have it
AssetManager.getAsset(token.getAssetID());
}
}
}
// Now the stamps
for (Token token : zone.getStampTokens()) {
MD5Key key = token.getAssetID();
if (AssetManager.hasAsset(key)) {
ImageManager.getImage(AssetManager.getAsset(key));
} else {
if (!AssetManager.isAssetRequested(key)) {
AssetManager.addAssetListener(token.getAssetID(),
listener);
// This will force a server request if we don't already
// have it
AssetManager.getAsset(token.getAssetID());
}
}
}
// Now add the rest
for (Token token : zone.getAllTokens()) {
MD5Key key = token.getAssetID();
if (AssetManager.hasAsset(key)) {
ImageManager.getImage(AssetManager.getAsset(key));
} else {
if (!AssetManager.isAssetRequested(key)) {
AssetManager.addAssetListener(key, listener);
// This will force a server request if we don't already
// have it
AssetManager.getAsset(token.getAssetID());
}
}
}
}
public void zoneAdded(Zone zone) {
}
}
// //
// WINDOW LISTENER
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
if (MapTool.isHostingServer()) {
if (!MapTool
.confirm("You are hosting a server. Shutting down will disconnect all players. Are you sure?")) {
return;
}
}
ServerDisconnectHandler.disconnectExpected = true;
MapTool.disconnect();
// We're done
EventQueue.invokeLater(new Runnable() {
public void run() {
System.exit(0);
}
});
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
// //
// REPAINT TIMER
private class RepaintTimer implements ActionListener {
public void actionPerformed(ActionEvent e) {
ZoneRenderer renderer = getCurrentZoneRenderer();
if (renderer != null) {
renderer.repaint();
}
}
}
// //
// DOCKABLE FACTORY
public enum MapToolView {
ZONE_RENDERER("Zone"),
CONNECTIONS("Connections"),
TOKEN_TREE("Tokens"),
IMAGE_EXPLORER("Image Explorer"),
CHAT("Chat"),
MACROS("Macros");
private String displayName;
private MapToolView(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
private class MapToolViewFactory implements DockableFactory {
private Map<MapToolView, View> viewMap = new HashMap<MapToolView, View>();
public Dockable getDockable(String viewId) {
MapToolView view = MapToolView.valueOf(viewId);
View dockable = viewMap.get(view);
if (dockable != null) {
return dockable;
}
JComponent component = null;
switch (MapToolView.valueOf(viewId)) {
case ZONE_RENDERER: component = rendererBorderPanel; break;
case CONNECTIONS: component = new JScrollPane(createPlayerList()); break;
case TOKEN_TREE: component = new JScrollPane(createTokenTreePanel(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); break;
case IMAGE_EXPLORER: component = assetPanel; break;
case CHAT: component = commandPanel; break;
case MACROS: component = new JScrollPane(createMacroButtonPanel(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);break;
}
if (component == null) {
throw new IllegalArgumentException("Could not find component for: " + viewId);
}
dockable = createView(view, component);
viewMap.put(view, dockable);
// Special case setup
if (view == MapToolView.ZONE_RENDERER) {
dockable.setTitlebar(null);
}
return dockable;
}
public Component getDockableComponent(String arg0) {
return null;
}
private View createView(MapToolView viewType, JComponent panel) {
View view = new View(viewType.name(), viewType.getDisplayName());
view.addAction(DockingConstants.CLOSE_ACTION);
view.addAction(DockingConstants.PIN_ACTION);
JPanel p = new JPanel(new GridLayout());
p.add(panel);
view.setContentPane(p);
return view;
}
}
////
// PERSPECTIVE FACTORY
public static final String PERSPECTIVEID = "default";
private static class MapToolPrespectiveFactory implements PerspectiveFactory {
public Perspective getPerspective(String persistentId) {
Perspective perspective = null;
if (PERSPECTIVEID.equals(persistentId)) {
perspective = new Perspective(PERSPECTIVEID, "Default");
LayoutSequence seq = perspective.getInitialSequence(true);
seq.add(MapToolView.IMAGE_EXPLORER.name());
seq.add(MapToolView.ZONE_RENDERER.name(), MapToolView.IMAGE_EXPLORER.name(), DockingConstants.EAST_REGION, .25f);
seq.add(MapToolView.TOKEN_TREE.name(), MapToolView.IMAGE_EXPLORER.name(), DockingConstants.SOUTH_REGION, .3f);
seq.add(MapToolView.CONNECTIONS.name(), MapToolView.TOKEN_TREE.name(), DockingConstants.SOUTH_REGION, .5f);
seq.add(MapToolView.CHAT.name(), MapToolView.ZONE_RENDERER.name(), DockingConstants.SOUTH_REGION, .75f);
seq.add(MapToolView.MACROS.name(), MapToolView.CHAT.name(), DockingConstants.EAST_REGION, .75f);
}
return perspective;
}
}
}
| false | true | public MapToolFrame() {
// Set up the frame
super(AppConstants.APP_NAME);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(this);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
SwingUtil.centerOnScreen(this);
setFocusTraversalPolicy(new MapToolFocusTraversalPolicy());
// Components
glassPane = new GlassPane();
assetPanel = createAssetPanel();
toolbox = new Toolbox();
zoneRendererList = new CopyOnWriteArrayList<ZoneRenderer>();
pointerOverlay = new PointerOverlay();
colorPicker = new ColorPicker(this);
String credits = "";
String version = "";
Image logo = null;
try {
credits = new String(FileUtil
.loadResource("net/rptools/maptool/client/credits.html"));
version = MapTool.getVersion();
credits = credits.replace("%VERSION%", version);
logo = ImageUtil.getImage("net/rptools/lib/image/rptools-logo.png");
} catch (Exception ioe) {
System.err.println("Unable to load credits or version");
}
aboutDialog = new AboutDialog(this, logo, credits);
aboutDialog.setSize(354, 400);
statusPanel = new StatusPanel();
statusPanel.addPanel(getCoordinateStatusBar());
statusPanel.addPanel(new MemoryStatusBar());
// statusPanel.addPanel(progressBar);
statusPanel.addPanel(connectionStatusPanel);
statusPanel.addPanel(activityMonitor);
statusPanel.addPanel(new SpacerStatusBar(25));
zoneSelectionPanel = new ZoneSelectionPanel();
zoneSelectionPanel.setSize(100, 100);
AppListeners.addZoneListener(zoneSelectionPanel);
newZoneDropPanel = new NewZoneDropPanel();
zoneRendererPanel = new JPanel(new PositionalLayout(5));
zoneRendererPanel.setBackground(Color.black);
zoneRendererPanel.add(newZoneDropPanel,
PositionalLayout.Position.CENTER);
zoneRendererPanel.add(zoneSelectionPanel, PositionalLayout.Position.SE);
zoneRendererPanel.add(getChatActionLabel(),
PositionalLayout.Position.SW);
commandPanel = new CommandPanel();
MapTool.getMessageList().addObserver(commandPanel);
MapTool.getMessageList().addObserver(createChatIconMessageObserver());
rendererBorderPanel = new JPanel(new GridLayout());
rendererBorderPanel.add(zoneRendererPanel);
// Docking
JPanel dockingPanel = new JPanel(new BorderLayout(0, 0));
dockingPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
Viewport viewport = new Viewport();
viewport.setBorderManager(new StandardBorderManager(new ShadowBorder()));
dockingPanel.add(viewport, BorderLayout.CENTER);
DockingManager.setDockableFactory(new MapToolViewFactory());
PerspectiveManager.setFactory(new MapToolPrespectiveFactory());
PerspectiveManager.getInstance().setCurrentPerspective(PERSPECTIVEID, true);
PerspectiveManager.setPersistenceHandler(new FilePersistenceHandler(AppUtil.getAppHome("config").getAbsolutePath() + "/layout.xml"));
// try{
// DockingManager.loadLayoutModel();
DockingManager.restoreLayout();
// } catch(IOException e) {
// e.printStackTrace();
// } catch (PersistenceException e) {
// e.printStackTrace();
// }
EventQueue.invokeLater(new Runnable() {
public void run() {
DockingManager.setAutoPersist(true);
}
});
// Put it all together
menuBar = new AppMenuBar();
setJMenuBar(menuBar);
setLayout(new BorderLayout());
add(BorderLayout.CENTER, dockingPanel);
add(BorderLayout.NORTH, new ToolbarPanel(toolbox));
add(BorderLayout.SOUTH, statusPanel);
setGlassPane(glassPane);
// TODO: Put together a class that handles adding in the listeners, just
// so that this doesn't
// get all cluttered
AppListeners.addZoneListener(new RequestZoneAssetsListener());
new FramePreferences(AppConstants.APP_NAME, "mainFrame", this);
// setSize(800, 600);
restorePreferences();
repaintTimer = new Timer(1000, new RepaintTimer());
repaintTimer.start();
}
| public MapToolFrame() {
// Set up the frame
super(AppConstants.APP_NAME);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(this);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
SwingUtil.centerOnScreen(this);
setFocusTraversalPolicy(new MapToolFocusTraversalPolicy());
// Components
glassPane = new GlassPane();
assetPanel = createAssetPanel();
toolbox = new Toolbox();
zoneRendererList = new CopyOnWriteArrayList<ZoneRenderer>();
pointerOverlay = new PointerOverlay();
colorPicker = new ColorPicker(this);
String credits = "";
String version = "";
Image logo = null;
try {
credits = new String(FileUtil
.loadResource("net/rptools/maptool/client/credits.html"));
version = MapTool.getVersion();
credits = credits.replace("%VERSION%", version);
logo = ImageUtil.getImage("net/rptools/lib/image/rptools-logo.png");
} catch (Exception ioe) {
System.err.println("Unable to load credits or version");
}
aboutDialog = new AboutDialog(this, logo, credits);
aboutDialog.setSize(354, 400);
statusPanel = new StatusPanel();
statusPanel.addPanel(getCoordinateStatusBar());
statusPanel.addPanel(new MemoryStatusBar());
// statusPanel.addPanel(progressBar);
statusPanel.addPanel(connectionStatusPanel);
statusPanel.addPanel(activityMonitor);
statusPanel.addPanel(new SpacerStatusBar(25));
zoneSelectionPanel = new ZoneSelectionPanel();
zoneSelectionPanel.setSize(100, 100);
AppListeners.addZoneListener(zoneSelectionPanel);
newZoneDropPanel = new NewZoneDropPanel();
zoneRendererPanel = new JPanel(new PositionalLayout(5));
zoneRendererPanel.setBackground(Color.black);
zoneRendererPanel.add(newZoneDropPanel,
PositionalLayout.Position.CENTER);
zoneRendererPanel.add(zoneSelectionPanel, PositionalLayout.Position.SE);
zoneRendererPanel.add(getChatActionLabel(),
PositionalLayout.Position.SW);
commandPanel = new CommandPanel();
MapTool.getMessageList().addObserver(commandPanel);
MapTool.getMessageList().addObserver(createChatIconMessageObserver());
rendererBorderPanel = new JPanel(new GridLayout());
rendererBorderPanel.add(zoneRendererPanel);
// Docking
JPanel dockingPanel = new JPanel(new BorderLayout(0, 0));
dockingPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
Viewport viewport = new Viewport();
viewport.setBorderManager(new StandardBorderManager(new ShadowBorder()));
dockingPanel.add(viewport, BorderLayout.CENTER);
DockingManager.setDockableFactory(new MapToolViewFactory());
PerspectiveManager.setFactory(new MapToolPrespectiveFactory());
PerspectiveManager.getInstance().setCurrentPerspective(PERSPECTIVEID, true);
PerspectiveManager.setPersistenceHandler(new FilePersistenceHandler(AppUtil.getAppHome("config").getAbsolutePath() + "/layout.xml"));
try{
DockingManager.loadLayoutModel();
} catch(IOException e) {
e.printStackTrace();
} catch (PersistenceException e) {
e.printStackTrace();
}
DockingManager.setAutoPersist(true);
EventQueue.invokeLater(new Runnable() {
public void run() {
DockingManager.restoreLayout();
}
});
// Put it all together
menuBar = new AppMenuBar();
setJMenuBar(menuBar);
setLayout(new BorderLayout());
add(BorderLayout.CENTER, dockingPanel);
add(BorderLayout.NORTH, new ToolbarPanel(toolbox));
add(BorderLayout.SOUTH, statusPanel);
setGlassPane(glassPane);
// TODO: Put together a class that handles adding in the listeners, just
// so that this doesn't
// get all cluttered
AppListeners.addZoneListener(new RequestZoneAssetsListener());
new FramePreferences(AppConstants.APP_NAME, "mainFrame", this);
// setSize(800, 600);
restorePreferences();
repaintTimer = new Timer(1000, new RepaintTimer());
repaintTimer.start();
}
|
diff --git a/beam-geotiff/src/main/java/org/esa/beam/dataio/geotiff/internal/TiffIFD.java b/beam-geotiff/src/main/java/org/esa/beam/dataio/geotiff/internal/TiffIFD.java
index 0d377a310..2e998a1a9 100644
--- a/beam-geotiff/src/main/java/org/esa/beam/dataio/geotiff/internal/TiffIFD.java
+++ b/beam-geotiff/src/main/java/org/esa/beam/dataio/geotiff/internal/TiffIFD.java
@@ -1,359 +1,363 @@
package org.esa.beam.dataio.geotiff.internal;
import org.esa.beam.framework.datamodel.Band;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.datamodel.ProductData;
import org.esa.beam.util.Guardian;
import org.esa.beam.util.ProductUtils;
import org.esa.beam.util.geotiff.GeoTIFFMetadata;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.DataBuffer;
import java.io.IOException;
import java.util.ArrayList;
/**
* A TIFF IFD implementation for the GeoTIFF format.
*
* @author Marco Peters
* @author Sabine Embacher
* @author Norman Fomferra
* @version $Revision: 2932 $ $Date: 2008-08-28 16:43:48 +0200 (Do, 28 Aug 2008) $
*/
public class TiffIFD {
private final TiffDirectoryEntrySet entrySet;
private static final int BYTES_FOR_NEXT_IFD_OFFSET = 4;
private static final int BYTES_FOR_NUMBER_OF_ENTRIES = 2;
private int maxElemSizeBandDataType;
public TiffIFD(final Product product) {
entrySet = new TiffDirectoryEntrySet();
initEntrys(product);
}
public void write(final ImageOutputStream ios, final long ifdOffset, final long nextIfdOffset) throws IOException {
Guardian.assertGreaterThan("ifdOffset", ifdOffset, -1);
computeOffsets(ifdOffset);
ios.seek(ifdOffset);
final TiffDirectoryEntry[] entries = entrySet.getEntries();
new TiffShort(entries.length).write(ios);
long entryPosition = ios.getStreamPosition();
for (TiffDirectoryEntry entry : entries) {
ios.seek(entryPosition);
entry.write(ios);
entryPosition += TiffDirectoryEntry.BYTES_PER_ENTRY;
}
writeNextIfdOffset(ios, ifdOffset, nextIfdOffset);
}
private void writeNextIfdOffset(final ImageOutputStream ios, final long ifdOffset, final long nextIfdOffset) throws
IOException {
ios.seek(getPosForNextIfdOffset(ifdOffset));
new TiffLong(nextIfdOffset).write(ios);
}
private long getPosForNextIfdOffset(final long ifdOffset) {
return ifdOffset + getRequiredIfdSize() - 4;
}
public TiffDirectoryEntry getEntry(final TiffShort tag) {
return entrySet.getEntry(tag);
}
public long getRequiredIfdSize() {
final TiffDirectoryEntry[] entries = entrySet.getEntries();
return BYTES_FOR_NUMBER_OF_ENTRIES + entries.length * TiffDirectoryEntry.BYTES_PER_ENTRY + BYTES_FOR_NEXT_IFD_OFFSET;
}
public long getRequiredReferencedValuesSize() {
final TiffDirectoryEntry[] entries = entrySet.getEntries();
long size = 0;
for (final TiffDirectoryEntry entry : entries) {
if (entry.mustValuesBeReferenced()) {
size += entry.getValuesSizeInBytes();
}
}
return size;
}
public long getRequiredSizeForStrips() {
final TiffLong[] counts = (TiffLong[]) getEntry(TiffTag.STRIP_BYTE_COUNTS).getValues();
long size = 0;
for (TiffLong count : counts) {
size += count.getValue();
}
return size;
}
public long getRequiredEntireSize() {
return getRequiredIfdSize() + getRequiredReferencedValuesSize() + getRequiredSizeForStrips();
}
private void computeOffsets(final long ifdOffset) {
final TiffDirectoryEntry[] entries = entrySet.getEntries();
long valuesOffset = computeStartOffsetForValues(entries.length, ifdOffset);
for (final TiffDirectoryEntry entry : entries) {
if (entry.mustValuesBeReferenced()) {
entry.setValuesOffset(valuesOffset);
valuesOffset += entry.getValuesSizeInBytes();
}
}
moveStripsTo(valuesOffset);
}
private void moveStripsTo(final long stripsStart) {
final TiffLong[] values = (TiffLong[]) getEntry(TiffTag.STRIP_OFFSETS).getValues();
for (int i = 0; i < values.length; i++) {
final long oldValue = values[i].getValue();
final long newValue = oldValue + stripsStart;
values[i] = new TiffLong(newValue);
}
}
private long computeStartOffsetForValues(final int numEntries, final long ifdOffset) {
final short bytesPerEntry = TiffDirectoryEntry.BYTES_PER_ENTRY;
final int bytesForEntries = numEntries * bytesPerEntry;
return ifdOffset + BYTES_FOR_NUMBER_OF_ENTRIES + bytesForEntries + BYTES_FOR_NEXT_IFD_OFFSET;
}
private void setEntry(final TiffDirectoryEntry entry) {
entrySet.set(entry);
}
public int getBandDataType() {
return maxElemSizeBandDataType;
}
private void initEntrys(final Product product) {
maxElemSizeBandDataType = getMaxElemSizeBandDataType(product.getBands());
final int width = product.getSceneRasterWidth();
final int height = product.getSceneRasterHeight();
setEntry(new TiffDirectoryEntry(TiffTag.IMAGE_WIDTH, new TiffLong(width)));
setEntry(new TiffDirectoryEntry(TiffTag.IMAGE_LENGTH, new TiffLong(height)));
setEntry(new TiffDirectoryEntry(TiffTag.BITS_PER_SAMPLE, calculateBitsPerSample(product)));
setEntry(new TiffDirectoryEntry(TiffTag.COMPRESSION, new TiffShort(1)));
setEntry(new TiffDirectoryEntry(TiffTag.PHOTOMETRIC_INTERPRETATION, TiffCode.PHOTOMETRIC_BLACK_IS_ZERO));
setEntry(new TiffDirectoryEntry(TiffTag.IMAGE_DESCRIPTION, new TiffAscii(product.getName())));
setEntry(new TiffDirectoryEntry(TiffTag.SAMPLES_PER_PIXEL, new TiffShort(product.getNumBands())));
setEntry(new TiffDirectoryEntry(TiffTag.STRIP_OFFSETS, calculateStripOffsets()));
setEntry(new TiffDirectoryEntry(TiffTag.ROWS_PER_STRIP, new TiffLong(height)));
setEntry(new TiffDirectoryEntry(TiffTag.STRIP_BYTE_COUNTS, calculateStripByteCounts()));
setEntry(new TiffDirectoryEntry(TiffTag.X_RESOLUTION, new TiffRational(1, 1)));
setEntry(new TiffDirectoryEntry(TiffTag.Y_RESOLUTION, new TiffRational(1, 1)));
setEntry(new TiffDirectoryEntry(TiffTag.RESOLUTION_UNIT, new TiffShort(1)));
setEntry(new TiffDirectoryEntry(TiffTag.PLANAR_CONFIGURATION, TiffCode.PLANAR_CONFIG_PLANAR));
setEntry(new TiffDirectoryEntry(TiffTag.SAMPLE_FORMAT, calculateSampleFormat(product)));
setEntry(new TiffDirectoryEntry(TiffTag.BEAM_METADATA, getBeamMetadata(product)));
addGeoTiffTags(product);
}
private TiffAscii getBeamMetadata(final Product product) {
final BeamMetadata.Metadata metadata = BeamMetadata.createMetadata(product);
return new TiffAscii(metadata.getAsString());
}
private void addGeoTiffTags(final Product product) {
final GeoTIFFMetadata geoTIFFMetadata = ProductUtils.createGeoTIFFMetadata(product);
if (geoTIFFMetadata == null) {
return;
}
// for debug purpose
// final PrintWriter writer = new PrintWriter(System.out);
// geoTIFFMetadata.dump(writer);
// writer.close();
final int numEntries = geoTIFFMetadata.getNumGeoKeyEntries();
final TiffShort[] directoryTagValues = new TiffShort[numEntries * 4];
final ArrayList<TiffDouble> doubleValues = new ArrayList<TiffDouble>();
- final ArrayList<GeoTiffAscii> asciiValues = new ArrayList<GeoTiffAscii>();
+ final ArrayList<String> asciiValues = new ArrayList<String>();
for (int i = 0; i < numEntries; i++) {
final GeoTIFFMetadata.KeyEntry entry = geoTIFFMetadata.getGeoKeyEntryAt(i);
final int[] data = entry.getData();
for (int j = 0; j < data.length; j++) {
directoryTagValues[i * 4 + j] = new TiffShort(data[j]);
}
if (data[1] == TiffTag.GeoDoubleParamsTag.getValue()) {
directoryTagValues[i * 4 + 3] = new TiffShort(doubleValues.size());
final double[] geoDoubleParams = geoTIFFMetadata.getGeoDoubleParams(data[0]);
for (double geoDoubleParam : geoDoubleParams) {
doubleValues.add(new TiffDouble(geoDoubleParam));
}
}
if (data[1] == TiffTag.GeoAsciiParamsTag.getValue()) {
- directoryTagValues[i * 4 + 3] = new TiffShort(asciiValues.size());
- asciiValues.add(new GeoTiffAscii(geoTIFFMetadata.getGeoAsciiParam(data[0])));
+ int sizeInBytes = 0;
+ for (String asciiValue : asciiValues) {
+ sizeInBytes = asciiValue.length() + 1;
+ }
+ directoryTagValues[i * 4 + 3] = new TiffShort(sizeInBytes);
+ asciiValues.add(geoTIFFMetadata.getGeoAsciiParam(data[0]));
}
}
setEntry(new TiffDirectoryEntry(TiffTag.GeoKeyDirectoryTag, directoryTagValues));
- if (doubleValues.size() > 0) {
+ if (!doubleValues.isEmpty()) {
final TiffDouble[] tiffDoubles = doubleValues.toArray(new TiffDouble[doubleValues.size()]);
setEntry(new TiffDirectoryEntry(TiffTag.GeoDoubleParamsTag, tiffDoubles));
}
- if (asciiValues.size() > 0) {
- final GeoTiffAscii[] tiffAsciies = asciiValues.toArray(new GeoTiffAscii[asciiValues.size()]);
- setEntry(new TiffDirectoryEntry(TiffTag.GeoAsciiParamsTag, tiffAsciies));
+ if (!asciiValues.isEmpty()) {
+ final String[] tiffAsciies = asciiValues.toArray(new String[asciiValues.size()]);
+ setEntry(new TiffDirectoryEntry(TiffTag.GeoAsciiParamsTag, new GeoTiffAscii(tiffAsciies)));
}
double[] modelTransformation = geoTIFFMetadata.getModelTransformation();
if (!isZeroArray(modelTransformation)) {
setEntry(new TiffDirectoryEntry(TiffTag.ModelTransformationTag, toTiffDoubles(modelTransformation)));
} else {
double[] modelPixelScale = geoTIFFMetadata.getModelPixelScale();
if (!isZeroArray(modelPixelScale)) {
setEntry(new TiffDirectoryEntry(TiffTag.ModelPixelScaleTag, toTiffDoubles(modelPixelScale)));
}
final int numModelTiePoints = geoTIFFMetadata.getNumModelTiePoints();
if (numModelTiePoints > 0) {
final TiffDouble[] tiePoints = new TiffDouble[numModelTiePoints * 6];
for (int i = 0; i < numModelTiePoints; i++) {
final GeoTIFFMetadata.TiePoint modelTiePoint = geoTIFFMetadata.getModelTiePointAt(i);
final double[] data = modelTiePoint.getData();
for (int j = 0; j < data.length; j++) {
tiePoints[i * 6 + j] = new TiffDouble(data[j]);
}
}
setEntry(new TiffDirectoryEntry(TiffTag.ModelTiepointTag, tiePoints));
}
}
}
private static TiffDouble[] toTiffDoubles(double[] a) {
final TiffDouble[] td = new TiffDouble[a.length];
for (int i = 0; i < a.length; i++) {
td[i] = new TiffDouble(a[i]);
}
return td;
}
private static boolean isZeroArray(double[] a) {
for (double v : a) {
if (v != 0.0) {
return false;
}
}
return true;
}
static int getMaxElemSizeBandDataType(final Band[] bands) {
int maxSignedIntType = -1;
int maxUnsignedIntType = -1;
int maxFloatType = -1;
for (Band band : bands) {
int dt = band.getDataType();
if (ProductData.isIntType(dt)) {
if (ProductData.isUIntType(dt)) {
maxUnsignedIntType = Math.max(maxUnsignedIntType, dt);
} else {
maxSignedIntType = Math.max(maxSignedIntType, dt);
}
}
if (ProductData.isFloatingPointType(dt)) {
maxFloatType = Math.max(maxFloatType, dt);
}
}
if (maxFloatType == ProductData.TYPE_FLOAT64) {
return ProductData.TYPE_FLOAT64;
}
if (maxFloatType != -1) {
if (maxSignedIntType > ProductData.TYPE_INT16 || maxUnsignedIntType > ProductData.TYPE_UINT16) {
return ProductData.TYPE_FLOAT64;
} else {
return ProductData.TYPE_FLOAT32;
}
}
if (maxUnsignedIntType != -1) {
if (maxSignedIntType == -1) {
return maxUnsignedIntType;
}
if (ProductData.getElemSize(maxUnsignedIntType) >= ProductData.getElemSize(maxSignedIntType)) {
int returnType = maxUnsignedIntType - 10 + 1;
if (returnType > 12) {
return ProductData.TYPE_FLOAT64;
} else {
return returnType;
}
}
}
if (maxSignedIntType != -1) {
return maxSignedIntType;
}
return DataBuffer.TYPE_UNDEFINED;
}
private TiffShort[] calculateSampleFormat(final Product product) {
int dataType = getBandDataType();
TiffShort sampleFormat;
if (ProductData.isUIntType(dataType)) {
sampleFormat = TiffCode.SAMPLE_FORMAT_UINT;
} else if (ProductData.isIntType(dataType)) {
sampleFormat = TiffCode.SAMPLE_FORMAT_INT;
} else {
sampleFormat = TiffCode.SAMPLE_FORMAT_FLOAT;
}
final TiffShort[] tiffValues = new TiffShort[product.getNumBands()];
for (int i = 0; i < tiffValues.length; i++) {
tiffValues[i] = sampleFormat;
}
return tiffValues;
}
private TiffLong[] calculateStripByteCounts() {
TiffValue[] bitsPerSample = getBitsPerSampleValues();
final TiffLong[] tiffValues = new TiffLong[bitsPerSample.length];
for (int i = 0; i < tiffValues.length; i++) {
long byteCount = getByteCount(bitsPerSample, i);
tiffValues[i] = new TiffLong(byteCount);
}
return tiffValues;
}
private TiffLong[] calculateStripOffsets() {
TiffValue[] bitsPerSample = getBitsPerSampleValues();
final TiffLong[] tiffValues = new TiffLong[bitsPerSample.length];
long offset = 0;
for (int i = 0; i < tiffValues.length; i++) {
tiffValues[i] = new TiffLong(offset);
long byteCount = getByteCount(bitsPerSample, i);
offset += byteCount;
}
return tiffValues;
}
private long getByteCount(TiffValue[] bitsPerSample, int i) {
long bytesPerSample = ((TiffShort) bitsPerSample[i]).getValue() / 8;
long byteCount = getWidth() * getHeight() * bytesPerSample;
return byteCount;
}
private TiffShort[] calculateBitsPerSample(final Product product) {
int dataType = getBandDataType();
int elemSize = ProductData.getElemSize(dataType);
final TiffShort[] tiffValues = new TiffShort[product.getNumBands()];
for (int i = 0; i < tiffValues.length; i++) {
tiffValues[i] = new TiffShort(8 * elemSize);
}
return tiffValues;
}
private TiffValue[] getBitsPerSampleValues() {
return getEntry(TiffTag.BITS_PER_SAMPLE).getValues();
}
private long getHeight() {
return ((TiffLong) getEntry(TiffTag.IMAGE_LENGTH).getValues()[0]).getValue();
}
private long getWidth() {
return ((TiffLong) getEntry(TiffTag.IMAGE_WIDTH).getValues()[0]).getValue();
}
}
| false | true | private void addGeoTiffTags(final Product product) {
final GeoTIFFMetadata geoTIFFMetadata = ProductUtils.createGeoTIFFMetadata(product);
if (geoTIFFMetadata == null) {
return;
}
// for debug purpose
// final PrintWriter writer = new PrintWriter(System.out);
// geoTIFFMetadata.dump(writer);
// writer.close();
final int numEntries = geoTIFFMetadata.getNumGeoKeyEntries();
final TiffShort[] directoryTagValues = new TiffShort[numEntries * 4];
final ArrayList<TiffDouble> doubleValues = new ArrayList<TiffDouble>();
final ArrayList<GeoTiffAscii> asciiValues = new ArrayList<GeoTiffAscii>();
for (int i = 0; i < numEntries; i++) {
final GeoTIFFMetadata.KeyEntry entry = geoTIFFMetadata.getGeoKeyEntryAt(i);
final int[] data = entry.getData();
for (int j = 0; j < data.length; j++) {
directoryTagValues[i * 4 + j] = new TiffShort(data[j]);
}
if (data[1] == TiffTag.GeoDoubleParamsTag.getValue()) {
directoryTagValues[i * 4 + 3] = new TiffShort(doubleValues.size());
final double[] geoDoubleParams = geoTIFFMetadata.getGeoDoubleParams(data[0]);
for (double geoDoubleParam : geoDoubleParams) {
doubleValues.add(new TiffDouble(geoDoubleParam));
}
}
if (data[1] == TiffTag.GeoAsciiParamsTag.getValue()) {
directoryTagValues[i * 4 + 3] = new TiffShort(asciiValues.size());
asciiValues.add(new GeoTiffAscii(geoTIFFMetadata.getGeoAsciiParam(data[0])));
}
}
setEntry(new TiffDirectoryEntry(TiffTag.GeoKeyDirectoryTag, directoryTagValues));
if (doubleValues.size() > 0) {
final TiffDouble[] tiffDoubles = doubleValues.toArray(new TiffDouble[doubleValues.size()]);
setEntry(new TiffDirectoryEntry(TiffTag.GeoDoubleParamsTag, tiffDoubles));
}
if (asciiValues.size() > 0) {
final GeoTiffAscii[] tiffAsciies = asciiValues.toArray(new GeoTiffAscii[asciiValues.size()]);
setEntry(new TiffDirectoryEntry(TiffTag.GeoAsciiParamsTag, tiffAsciies));
}
double[] modelTransformation = geoTIFFMetadata.getModelTransformation();
if (!isZeroArray(modelTransformation)) {
setEntry(new TiffDirectoryEntry(TiffTag.ModelTransformationTag, toTiffDoubles(modelTransformation)));
} else {
double[] modelPixelScale = geoTIFFMetadata.getModelPixelScale();
if (!isZeroArray(modelPixelScale)) {
setEntry(new TiffDirectoryEntry(TiffTag.ModelPixelScaleTag, toTiffDoubles(modelPixelScale)));
}
final int numModelTiePoints = geoTIFFMetadata.getNumModelTiePoints();
if (numModelTiePoints > 0) {
final TiffDouble[] tiePoints = new TiffDouble[numModelTiePoints * 6];
for (int i = 0; i < numModelTiePoints; i++) {
final GeoTIFFMetadata.TiePoint modelTiePoint = geoTIFFMetadata.getModelTiePointAt(i);
final double[] data = modelTiePoint.getData();
for (int j = 0; j < data.length; j++) {
tiePoints[i * 6 + j] = new TiffDouble(data[j]);
}
}
setEntry(new TiffDirectoryEntry(TiffTag.ModelTiepointTag, tiePoints));
}
}
}
| private void addGeoTiffTags(final Product product) {
final GeoTIFFMetadata geoTIFFMetadata = ProductUtils.createGeoTIFFMetadata(product);
if (geoTIFFMetadata == null) {
return;
}
// for debug purpose
// final PrintWriter writer = new PrintWriter(System.out);
// geoTIFFMetadata.dump(writer);
// writer.close();
final int numEntries = geoTIFFMetadata.getNumGeoKeyEntries();
final TiffShort[] directoryTagValues = new TiffShort[numEntries * 4];
final ArrayList<TiffDouble> doubleValues = new ArrayList<TiffDouble>();
final ArrayList<String> asciiValues = new ArrayList<String>();
for (int i = 0; i < numEntries; i++) {
final GeoTIFFMetadata.KeyEntry entry = geoTIFFMetadata.getGeoKeyEntryAt(i);
final int[] data = entry.getData();
for (int j = 0; j < data.length; j++) {
directoryTagValues[i * 4 + j] = new TiffShort(data[j]);
}
if (data[1] == TiffTag.GeoDoubleParamsTag.getValue()) {
directoryTagValues[i * 4 + 3] = new TiffShort(doubleValues.size());
final double[] geoDoubleParams = geoTIFFMetadata.getGeoDoubleParams(data[0]);
for (double geoDoubleParam : geoDoubleParams) {
doubleValues.add(new TiffDouble(geoDoubleParam));
}
}
if (data[1] == TiffTag.GeoAsciiParamsTag.getValue()) {
int sizeInBytes = 0;
for (String asciiValue : asciiValues) {
sizeInBytes = asciiValue.length() + 1;
}
directoryTagValues[i * 4 + 3] = new TiffShort(sizeInBytes);
asciiValues.add(geoTIFFMetadata.getGeoAsciiParam(data[0]));
}
}
setEntry(new TiffDirectoryEntry(TiffTag.GeoKeyDirectoryTag, directoryTagValues));
if (!doubleValues.isEmpty()) {
final TiffDouble[] tiffDoubles = doubleValues.toArray(new TiffDouble[doubleValues.size()]);
setEntry(new TiffDirectoryEntry(TiffTag.GeoDoubleParamsTag, tiffDoubles));
}
if (!asciiValues.isEmpty()) {
final String[] tiffAsciies = asciiValues.toArray(new String[asciiValues.size()]);
setEntry(new TiffDirectoryEntry(TiffTag.GeoAsciiParamsTag, new GeoTiffAscii(tiffAsciies)));
}
double[] modelTransformation = geoTIFFMetadata.getModelTransformation();
if (!isZeroArray(modelTransformation)) {
setEntry(new TiffDirectoryEntry(TiffTag.ModelTransformationTag, toTiffDoubles(modelTransformation)));
} else {
double[] modelPixelScale = geoTIFFMetadata.getModelPixelScale();
if (!isZeroArray(modelPixelScale)) {
setEntry(new TiffDirectoryEntry(TiffTag.ModelPixelScaleTag, toTiffDoubles(modelPixelScale)));
}
final int numModelTiePoints = geoTIFFMetadata.getNumModelTiePoints();
if (numModelTiePoints > 0) {
final TiffDouble[] tiePoints = new TiffDouble[numModelTiePoints * 6];
for (int i = 0; i < numModelTiePoints; i++) {
final GeoTIFFMetadata.TiePoint modelTiePoint = geoTIFFMetadata.getModelTiePointAt(i);
final double[] data = modelTiePoint.getData();
for (int j = 0; j < data.length; j++) {
tiePoints[i * 6 + j] = new TiffDouble(data[j]);
}
}
setEntry(new TiffDirectoryEntry(TiffTag.ModelTiepointTag, tiePoints));
}
}
}
|
diff --git a/src/main/java/me/greatman/plugins/inn/IBlockListener.java b/src/main/java/me/greatman/plugins/inn/IBlockListener.java
index 6064760..5ff055e 100644
--- a/src/main/java/me/greatman/plugins/inn/IBlockListener.java
+++ b/src/main/java/me/greatman/plugins/inn/IBlockListener.java
@@ -1,43 +1,43 @@
package me.greatman.plugins.inn;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockListener;
public class IBlockListener extends BlockListener{
private final Inn plugin;
public IBlockListener(Inn instance) {
plugin = instance;
}
@Override
public void onBlockBreak(BlockBreakEvent event){
if (event.getBlock().getType() == Material.WOODEN_DOOR){
int x,y,z;
Location loc = event.getBlock().getLocation();
x = loc.getBlockX();
y = loc.getBlockY();
z = loc.getBlockZ();
- if (Inn.doorAlreadyExists(x,y,z) && Inn.getOwner(x,y,z) != event.getPlayer().getName() || IPermissions.permission(event.getPlayer(), "inn.bypass", event.getPlayer().isOp())){
+ if (Inn.doorAlreadyExists(x,y,z) || Inn.doorAlreadyExists(x, y-1, z) || Inn.doorAlreadyExists(x,y+1,z) && Inn.getOwner(x,y,z) != event.getPlayer().getName() || IPermissions.permission(event.getPlayer(), "inn.bypass", event.getPlayer().isOp())){
event.getPlayer().sendMessage(ChatColor.RED + "[Inn] You doesn't own this door!");
event.setCancelled(true);
}else{
String query = "DELETE FROM doors WHERE x=" + x + " AND y=" + y + " AND z=" + z +"";
Inn.manageSQLite.deleteQuery(query);
if (Inn.doorAlreadyExists(x,y-1,z)){
int y2 = y - 1;
query = "DELETE FROM doors WHERE x=" + x + " AND y=" + y2 + " AND z=" + z +"";
Inn.manageSQLite.deleteQuery(query);
}else if (Inn.doorAlreadyExists(x,y+1,z)){
int y2 = y + 1;
query = "DELETE FROM doors WHERE x=" + x + " AND y=" + y2 + " AND z=" + z +"";
Inn.manageSQLite.deleteQuery(query);
}
event.getPlayer().sendMessage(ChatColor.RED + "[Inn] Door unregistered!");
}
}
}
}
| true | true | public void onBlockBreak(BlockBreakEvent event){
if (event.getBlock().getType() == Material.WOODEN_DOOR){
int x,y,z;
Location loc = event.getBlock().getLocation();
x = loc.getBlockX();
y = loc.getBlockY();
z = loc.getBlockZ();
if (Inn.doorAlreadyExists(x,y,z) && Inn.getOwner(x,y,z) != event.getPlayer().getName() || IPermissions.permission(event.getPlayer(), "inn.bypass", event.getPlayer().isOp())){
event.getPlayer().sendMessage(ChatColor.RED + "[Inn] You doesn't own this door!");
event.setCancelled(true);
}else{
String query = "DELETE FROM doors WHERE x=" + x + " AND y=" + y + " AND z=" + z +"";
Inn.manageSQLite.deleteQuery(query);
if (Inn.doorAlreadyExists(x,y-1,z)){
int y2 = y - 1;
query = "DELETE FROM doors WHERE x=" + x + " AND y=" + y2 + " AND z=" + z +"";
Inn.manageSQLite.deleteQuery(query);
}else if (Inn.doorAlreadyExists(x,y+1,z)){
int y2 = y + 1;
query = "DELETE FROM doors WHERE x=" + x + " AND y=" + y2 + " AND z=" + z +"";
Inn.manageSQLite.deleteQuery(query);
}
event.getPlayer().sendMessage(ChatColor.RED + "[Inn] Door unregistered!");
}
}
}
| public void onBlockBreak(BlockBreakEvent event){
if (event.getBlock().getType() == Material.WOODEN_DOOR){
int x,y,z;
Location loc = event.getBlock().getLocation();
x = loc.getBlockX();
y = loc.getBlockY();
z = loc.getBlockZ();
if (Inn.doorAlreadyExists(x,y,z) || Inn.doorAlreadyExists(x, y-1, z) || Inn.doorAlreadyExists(x,y+1,z) && Inn.getOwner(x,y,z) != event.getPlayer().getName() || IPermissions.permission(event.getPlayer(), "inn.bypass", event.getPlayer().isOp())){
event.getPlayer().sendMessage(ChatColor.RED + "[Inn] You doesn't own this door!");
event.setCancelled(true);
}else{
String query = "DELETE FROM doors WHERE x=" + x + " AND y=" + y + " AND z=" + z +"";
Inn.manageSQLite.deleteQuery(query);
if (Inn.doorAlreadyExists(x,y-1,z)){
int y2 = y - 1;
query = "DELETE FROM doors WHERE x=" + x + " AND y=" + y2 + " AND z=" + z +"";
Inn.manageSQLite.deleteQuery(query);
}else if (Inn.doorAlreadyExists(x,y+1,z)){
int y2 = y + 1;
query = "DELETE FROM doors WHERE x=" + x + " AND y=" + y2 + " AND z=" + z +"";
Inn.manageSQLite.deleteQuery(query);
}
event.getPlayer().sendMessage(ChatColor.RED + "[Inn] Door unregistered!");
}
}
}
|
diff --git a/src/java/main/org/jaxen/function/SubstringAfterFunction.java b/src/java/main/org/jaxen/function/SubstringAfterFunction.java
index 3608aaf..5adb65b 100644
--- a/src/java/main/org/jaxen/function/SubstringAfterFunction.java
+++ b/src/java/main/org/jaxen/function/SubstringAfterFunction.java
@@ -1,51 +1,51 @@
package org.jaxen.function;
import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.FunctionCallException;
import org.jaxen.Navigator;
import java.util.List;
/**
* <p><b>4.2</b> <code><i>string</i> substring-after(<i>string</i>,<i>string</i>)</code>
*
* @author bob mcwhirter (bob @ werken.com)
*/
public class SubstringAfterFunction implements Function
{
public Object call(Context context,
List args) throws FunctionCallException
{
if (args.size() == 2)
{
return evaluate( args.get(0),
args.get(1),
context.getNavigator() );
}
throw new FunctionCallException( "substring-after() requires two arguments." );
}
public static String evaluate(Object strArg,
Object matchArg,
Navigator nav)
{
String str = StringFunction.evaluate( strArg,
nav );
String match = StringFunction.evaluate( matchArg,
nav );
int loc = str.indexOf(match);
if ( loc < 0 )
{
return "";
}
- return str.substring(loc+1);
+ return str.substring(loc+match.length());
}
}
| true | true | public static String evaluate(Object strArg,
Object matchArg,
Navigator nav)
{
String str = StringFunction.evaluate( strArg,
nav );
String match = StringFunction.evaluate( matchArg,
nav );
int loc = str.indexOf(match);
if ( loc < 0 )
{
return "";
}
return str.substring(loc+1);
}
| public static String evaluate(Object strArg,
Object matchArg,
Navigator nav)
{
String str = StringFunction.evaluate( strArg,
nav );
String match = StringFunction.evaluate( matchArg,
nav );
int loc = str.indexOf(match);
if ( loc < 0 )
{
return "";
}
return str.substring(loc+match.length());
}
|
diff --git a/src/com/jgaap/classifiers/AuthorCentroidDriver.java b/src/com/jgaap/classifiers/AuthorCentroidDriver.java
index cfbfb54..2036138 100644
--- a/src/com/jgaap/classifiers/AuthorCentroidDriver.java
+++ b/src/com/jgaap/classifiers/AuthorCentroidDriver.java
@@ -1,113 +1,113 @@
/**
* JGAAP -- Java Graphical Authorship Attribution Program
* Copyright (C) 2009 Patrick Juola
*
* 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 under version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
**/
package com.jgaap.classifiers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import com.jgaap.jgaapConstants;
import com.jgaap.generics.Event;
import com.jgaap.generics.EventHistogram;
import com.jgaap.generics.EventSet;
import com.jgaap.generics.NeighborAnalysisDriver;
import com.jgaap.generics.Pair;
/**
* Assigns authorship labels by using a nearest-neighbor approach on a given
* distance/divergence function.
*
*/
public class AuthorCentroidDriver extends NeighborAnalysisDriver {
public String displayName() {
return "Author Centroid Driver" + getDistanceName();
}
public String tooltipText() {
return " ";
}
public boolean showInGUI() {
return false;
}
@Override
public List<Pair<String, Double>> analyze(EventSet unknown, List<EventSet> known) {
List<Pair<String, Double>> results = new ArrayList<Pair<String, Double>>();
List<EventSet> knownCentroids = new ArrayList<EventSet>();
Map<String, List<EventSet>> knownAuthors = new HashMap<String, List<EventSet>>();
for (EventSet eventSet : known) {
if (knownAuthors.containsKey(eventSet.getAuthor())) {
knownAuthors.get(eventSet.getAuthor()).add(eventSet);
} else {
List<EventSet> tmp = new ArrayList<EventSet>();
tmp.add(eventSet);
knownAuthors.put(eventSet.getAuthor(), tmp);
}
}
for (String author : knownAuthors.keySet()) {
EventSet centroid = new EventSet(author);
try {
Writer writer = new BufferedWriter(new FileWriter(new File(jgaapConstants.tmpDir()+ author + ".centroid")));
double count = 0;
EventHistogram hist = new EventHistogram();
for (EventSet eventSet : knownAuthors.get(author)) {
for (Event event : eventSet) {
hist.add(event);
}
count++;
}
for (Event event : hist) {
- writer.write(event.getEvent()+"\t"+hist.getRelativeFrequency(event)+"\n");
+ writer.write(event.getEvent()+"\t"+hist.getAbsoluteFrequency(event)/count+"\n");
for (int i = 0; i < Math.round(hist.getAbsoluteFrequency(event) / count); i++) {
centroid.addEvent(event);
}
}
knownCentroids.add(centroid);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < knownCentroids.size(); i++) {
double current = distance.distance(unknown, knownCentroids.get(i));
results.add(new Pair<String, Double>(knownCentroids.get(i).getAuthor(), current, 2));
if (jgaapConstants.JGAAP_DEBUG_VERBOSITY) {
System.out.print(unknown.getDocumentName() + "(Unknown)");
System.out.print(":");
System.out.print(knownCentroids.get(i).getDocumentName() + "("
+ knownCentroids.get(i).getAuthor() + ")\t");
System.out.println("Distance is " + current);
}
}
Collections.sort(results);
return results;
}
}
| true | true | public List<Pair<String, Double>> analyze(EventSet unknown, List<EventSet> known) {
List<Pair<String, Double>> results = new ArrayList<Pair<String, Double>>();
List<EventSet> knownCentroids = new ArrayList<EventSet>();
Map<String, List<EventSet>> knownAuthors = new HashMap<String, List<EventSet>>();
for (EventSet eventSet : known) {
if (knownAuthors.containsKey(eventSet.getAuthor())) {
knownAuthors.get(eventSet.getAuthor()).add(eventSet);
} else {
List<EventSet> tmp = new ArrayList<EventSet>();
tmp.add(eventSet);
knownAuthors.put(eventSet.getAuthor(), tmp);
}
}
for (String author : knownAuthors.keySet()) {
EventSet centroid = new EventSet(author);
try {
Writer writer = new BufferedWriter(new FileWriter(new File(jgaapConstants.tmpDir()+ author + ".centroid")));
double count = 0;
EventHistogram hist = new EventHistogram();
for (EventSet eventSet : knownAuthors.get(author)) {
for (Event event : eventSet) {
hist.add(event);
}
count++;
}
for (Event event : hist) {
writer.write(event.getEvent()+"\t"+hist.getRelativeFrequency(event)+"\n");
for (int i = 0; i < Math.round(hist.getAbsoluteFrequency(event) / count); i++) {
centroid.addEvent(event);
}
}
knownCentroids.add(centroid);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < knownCentroids.size(); i++) {
double current = distance.distance(unknown, knownCentroids.get(i));
results.add(new Pair<String, Double>(knownCentroids.get(i).getAuthor(), current, 2));
if (jgaapConstants.JGAAP_DEBUG_VERBOSITY) {
System.out.print(unknown.getDocumentName() + "(Unknown)");
System.out.print(":");
System.out.print(knownCentroids.get(i).getDocumentName() + "("
+ knownCentroids.get(i).getAuthor() + ")\t");
System.out.println("Distance is " + current);
}
}
Collections.sort(results);
return results;
}
| public List<Pair<String, Double>> analyze(EventSet unknown, List<EventSet> known) {
List<Pair<String, Double>> results = new ArrayList<Pair<String, Double>>();
List<EventSet> knownCentroids = new ArrayList<EventSet>();
Map<String, List<EventSet>> knownAuthors = new HashMap<String, List<EventSet>>();
for (EventSet eventSet : known) {
if (knownAuthors.containsKey(eventSet.getAuthor())) {
knownAuthors.get(eventSet.getAuthor()).add(eventSet);
} else {
List<EventSet> tmp = new ArrayList<EventSet>();
tmp.add(eventSet);
knownAuthors.put(eventSet.getAuthor(), tmp);
}
}
for (String author : knownAuthors.keySet()) {
EventSet centroid = new EventSet(author);
try {
Writer writer = new BufferedWriter(new FileWriter(new File(jgaapConstants.tmpDir()+ author + ".centroid")));
double count = 0;
EventHistogram hist = new EventHistogram();
for (EventSet eventSet : knownAuthors.get(author)) {
for (Event event : eventSet) {
hist.add(event);
}
count++;
}
for (Event event : hist) {
writer.write(event.getEvent()+"\t"+hist.getAbsoluteFrequency(event)/count+"\n");
for (int i = 0; i < Math.round(hist.getAbsoluteFrequency(event) / count); i++) {
centroid.addEvent(event);
}
}
knownCentroids.add(centroid);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < knownCentroids.size(); i++) {
double current = distance.distance(unknown, knownCentroids.get(i));
results.add(new Pair<String, Double>(knownCentroids.get(i).getAuthor(), current, 2));
if (jgaapConstants.JGAAP_DEBUG_VERBOSITY) {
System.out.print(unknown.getDocumentName() + "(Unknown)");
System.out.print(":");
System.out.print(knownCentroids.get(i).getDocumentName() + "("
+ knownCentroids.get(i).getAuthor() + ")\t");
System.out.println("Distance is " + current);
}
}
Collections.sort(results);
return results;
}
|
diff --git a/app/controllers/FeatureController.java b/app/controllers/FeatureController.java
index e0f4e48..6e5575e 100644
--- a/app/controllers/FeatureController.java
+++ b/app/controllers/FeatureController.java
@@ -1,215 +1,215 @@
package controllers;
import com.avaje.ebean.*;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import models.*;
import org.codehaus.jackson.JsonNode;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;
import java.sql.Timestamp;
import java.util.*;
@Security.Authenticated(Secured.class)
public class FeatureController extends Controller {
public static final double WEIGHT_ENG_COST = 2;
public static final double WEIGHT_REVENUE_BENEFIT = 3;
public static final double WEIGHT_RETENTION_BENEFIT = 1.5;
public static final double WEIGHT_POSITIONING_BENEFIT = 2.5;
public static final double MAX_SCORE = WEIGHT_ENG_COST * Size.NONE.getCostWeight() +
WEIGHT_REVENUE_BENEFIT * Size.XLARGE.getBenefitWeight() +
WEIGHT_RETENTION_BENEFIT * Size.XLARGE.getBenefitWeight() +
WEIGHT_POSITIONING_BENEFIT * Size.XLARGE.getBenefitWeight();
public static Result getFeature(Long id) {
Feature feature = Feature.find.byId(id);
if (feature == null) {
return notFound();
}
// get the tags
feature.tags = new HashSet<>();
SqlQuery query = Ebean.createSqlQuery("select tag from feature_tags where feature_id = :feature_id");
query.setParameter("feature_id", id);
List<SqlRow> list = query.findList();
for (SqlRow row : list) {
feature.tags.add(row.getString("tag"));
}
return ok(Json.toJson(feature));
}
@play.db.ebean.Transactional
public static Result updateFeature(Long id) {
Feature original = Feature.find.byId(id);
if (original == null) {
return notFound();
}
JsonNode json = request().body().asJson();
Feature update = Json.fromJson(json, Feature.class);
original.lastModified = new Timestamp(System.currentTimeMillis());
original.lastModifiedBy = User.findByEmail(request().username());
original.title = update.title;
original.title = update.title;
original.description = update.description;
original.state = update.state;
original.engineeringCost = update.engineeringCost;
original.revenueBenefit = update.revenueBenefit;
original.retentionBenefit = update.retentionBenefit;
original.positioningBenefit = update.positioningBenefit;
original.score = 0; // todo: do we even need this?
original.team = update.team;
original.quarter = update.quarter;
original.save();
// delete tag and then re-add
SqlUpdate delete = Ebean.createSqlUpdate("delete from feature_tags where feature_id = :feature_id");
delete.setParameter("feature_id", id);
delete.execute();
insertTags(update);
return ok(Json.toJson(dressFeature(original)));
}
public static Result find() {
if (!request().queryString().containsKey("query")) {
// todo: not sure this is a good idea, might get too large
return ok(Json.toJson(dressFeatures(Feature.find.all())));
}
String query = request().queryString().get("query")[0];
if (query.equals("")) {
// todo: same as above
- return ok(Json.toJson(Feature.find.all()));
+ return ok(Json.toJson(dressFeatures(Feature.find.all())));
}
ExpressionList<Feature> where = Feature.find.where();
String[] terms = query.split(",");
int tagsSeen = 0;
Multimap<Long, Boolean> tagMatchCount = LinkedListMultimap.create();
for (String term : terms) {
if (term.startsWith("state:")) {
FeatureState state = FeatureState.valueOf(term.substring(6).toUpperCase());
where.eq("state", state);
} else if (term.startsWith("title:")) {
where.ilike("title", "%" + term.substring(6) + "%");
} else if (term.startsWith("description:")) {
where.ilike("description", "%" + term.substring(12) + "%");
} else if (term.startsWith("createdBy:")) {
where.ilike("creator.email", "%" + term.substring(10) + "%");
} else if (term.startsWith("team:")) {
where.ilike("team.name", "%" + term.substring(5) + "%");
} else if (term.startsWith("quarter:")) {
where.ilike("quarter", "%" + term.substring(8) + "%");
} else {
// no prefix? assume a tag then
tagsSeen++;
SqlQuery tagQuery = Ebean.createSqlQuery("select feature_id from feature_tags where tag = :tag");
tagQuery.setParameter("tag", term);
List<SqlRow> list = tagQuery.findList();
for (SqlRow row : list) {
Long featureId = row.getLong("feature_id");
tagMatchCount.put(featureId, true);
}
}
}
if (tagsSeen > 0) {
Set<Long> featureIds = new HashSet<>();
for (Long featureId : tagMatchCount.keySet()) {
if (tagMatchCount.get(featureId).size() == tagsSeen) {
featureIds.add(featureId);
}
}
if (!featureIds.isEmpty()) {
where.in("id", featureIds);
} else {
// nothing matched, game over man!
return ok();
}
}
return ok(Json.toJson(dressFeatures(where.findList())));
//return ok(Json.toJson(where.findList()));
}
public static Feature dressFeature(Feature feature) {
return dressFeatures(Collections.singletonList(feature)).get(0);
}
public static List<Feature> dressFeatures(List<Feature> features) {
// first, get all the feature IDs so we can get all problems in a single query
final Map<Long, Feature> featureMap = new HashMap<>();
for (Feature feature : features) {
featureMap.put(feature.id, feature);
// also calculate a score
double score = 0d;
score += WEIGHT_ENG_COST * (feature.engineeringCost == null ? 0 : feature.engineeringCost.getCostWeight());
score += WEIGHT_REVENUE_BENEFIT * (feature.revenueBenefit == null ? 0 : feature.revenueBenefit.getBenefitWeight());
score += WEIGHT_RETENTION_BENEFIT * (feature.retentionBenefit == null ? 0 : feature.retentionBenefit.getBenefitWeight());
score += WEIGHT_POSITIONING_BENEFIT * (feature.positioningBenefit == null ? 0 : feature.positioningBenefit.getBenefitWeight());
// normalize to max score
feature.score = (int) (score / MAX_SCORE * 100);
}
// now query all problems
List<Problem> problems = Problem.find.where().in("feature_id", featureMap.keySet()).findList();
for (Problem problem : problems) {
Feature feature = featureMap.get(problem.feature.id);
if (feature.problemCount == null) {
feature.problemCount = 0;
}
if (feature.problemRevenue == null) {
feature.problemRevenue = 0;
}
feature.problemCount++;
if (problem.annualRevenue != null) {
feature.problemRevenue += problem.annualRevenue;
}
}
return features;
}
public static Result create() {
JsonNode json = request().body().asJson();
Feature feature = Json.fromJson(json, Feature.class);
feature.lastModified = new Timestamp(System.currentTimeMillis());
feature.creator = feature.lastModifiedBy = User.findByEmail(request().username());
feature.state = FeatureState.OPEN;
feature.save();
insertTags(feature);
return ok(Json.toJson(dressFeature(feature)));
}
private static void insertTags(Feature feature) {
// now save the tags
if (feature.tags != null && !feature.tags.isEmpty()) {
SqlUpdate update = Ebean.createSqlUpdate("insert into feature_tags (feature_id, tag) values (:feature_id, :tag)");
for (String tag : feature.tags) {
update.setParameter("feature_id", feature.id);
update.setParameter("tag", tag);
update.execute();
}
}
}
}
| true | true | public static Result find() {
if (!request().queryString().containsKey("query")) {
// todo: not sure this is a good idea, might get too large
return ok(Json.toJson(dressFeatures(Feature.find.all())));
}
String query = request().queryString().get("query")[0];
if (query.equals("")) {
// todo: same as above
return ok(Json.toJson(Feature.find.all()));
}
ExpressionList<Feature> where = Feature.find.where();
String[] terms = query.split(",");
int tagsSeen = 0;
Multimap<Long, Boolean> tagMatchCount = LinkedListMultimap.create();
for (String term : terms) {
if (term.startsWith("state:")) {
FeatureState state = FeatureState.valueOf(term.substring(6).toUpperCase());
where.eq("state", state);
} else if (term.startsWith("title:")) {
where.ilike("title", "%" + term.substring(6) + "%");
} else if (term.startsWith("description:")) {
where.ilike("description", "%" + term.substring(12) + "%");
} else if (term.startsWith("createdBy:")) {
where.ilike("creator.email", "%" + term.substring(10) + "%");
} else if (term.startsWith("team:")) {
where.ilike("team.name", "%" + term.substring(5) + "%");
} else if (term.startsWith("quarter:")) {
where.ilike("quarter", "%" + term.substring(8) + "%");
} else {
// no prefix? assume a tag then
tagsSeen++;
SqlQuery tagQuery = Ebean.createSqlQuery("select feature_id from feature_tags where tag = :tag");
tagQuery.setParameter("tag", term);
List<SqlRow> list = tagQuery.findList();
for (SqlRow row : list) {
Long featureId = row.getLong("feature_id");
tagMatchCount.put(featureId, true);
}
}
}
if (tagsSeen > 0) {
Set<Long> featureIds = new HashSet<>();
for (Long featureId : tagMatchCount.keySet()) {
if (tagMatchCount.get(featureId).size() == tagsSeen) {
featureIds.add(featureId);
}
}
if (!featureIds.isEmpty()) {
where.in("id", featureIds);
} else {
// nothing matched, game over man!
return ok();
}
}
return ok(Json.toJson(dressFeatures(where.findList())));
//return ok(Json.toJson(where.findList()));
}
| public static Result find() {
if (!request().queryString().containsKey("query")) {
// todo: not sure this is a good idea, might get too large
return ok(Json.toJson(dressFeatures(Feature.find.all())));
}
String query = request().queryString().get("query")[0];
if (query.equals("")) {
// todo: same as above
return ok(Json.toJson(dressFeatures(Feature.find.all())));
}
ExpressionList<Feature> where = Feature.find.where();
String[] terms = query.split(",");
int tagsSeen = 0;
Multimap<Long, Boolean> tagMatchCount = LinkedListMultimap.create();
for (String term : terms) {
if (term.startsWith("state:")) {
FeatureState state = FeatureState.valueOf(term.substring(6).toUpperCase());
where.eq("state", state);
} else if (term.startsWith("title:")) {
where.ilike("title", "%" + term.substring(6) + "%");
} else if (term.startsWith("description:")) {
where.ilike("description", "%" + term.substring(12) + "%");
} else if (term.startsWith("createdBy:")) {
where.ilike("creator.email", "%" + term.substring(10) + "%");
} else if (term.startsWith("team:")) {
where.ilike("team.name", "%" + term.substring(5) + "%");
} else if (term.startsWith("quarter:")) {
where.ilike("quarter", "%" + term.substring(8) + "%");
} else {
// no prefix? assume a tag then
tagsSeen++;
SqlQuery tagQuery = Ebean.createSqlQuery("select feature_id from feature_tags where tag = :tag");
tagQuery.setParameter("tag", term);
List<SqlRow> list = tagQuery.findList();
for (SqlRow row : list) {
Long featureId = row.getLong("feature_id");
tagMatchCount.put(featureId, true);
}
}
}
if (tagsSeen > 0) {
Set<Long> featureIds = new HashSet<>();
for (Long featureId : tagMatchCount.keySet()) {
if (tagMatchCount.get(featureId).size() == tagsSeen) {
featureIds.add(featureId);
}
}
if (!featureIds.isEmpty()) {
where.in("id", featureIds);
} else {
// nothing matched, game over man!
return ok();
}
}
return ok(Json.toJson(dressFeatures(where.findList())));
//return ok(Json.toJson(where.findList()));
}
|
diff --git a/org.eclipse.mylyn/src/org/eclipse/mylyn/core/net/WebClientUtil.java b/org.eclipse.mylyn/src/org/eclipse/mylyn/core/net/WebClientUtil.java
index 272c4b12..92c1cca1 100644
--- a/org.eclipse.mylyn/src/org/eclipse/mylyn/core/net/WebClientUtil.java
+++ b/org.eclipse.mylyn/src/org/eclipse/mylyn/core/net/WebClientUtil.java
@@ -1,184 +1,184 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.core.net;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
/**
* @author Mik Kersten
* @author Steffen Pingel
*/
public class WebClientUtil {
public static final int CONNNECT_TIMEOUT = 30000;
public static final int SOCKET_TIMEOUT = 10000;
private static final int HTTP_PORT = 80;
private static final int HTTPS_PORT = 443;
public static void initCommonsLoggingSettings() {
// TODO: move?
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "off");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "off");
}
/**
* public for testing
*/
public static boolean repositoryUsesHttps(String repositoryUrl) {
return repositoryUrl.matches("https.*");
}
public static int getPort(String repositoryUrl) {
int colonSlashSlash = repositoryUrl.indexOf("://");
int colonPort = repositoryUrl.indexOf(':', colonSlashSlash + 1);
if (colonPort < 0)
return repositoryUsesHttps(repositoryUrl) ? HTTPS_PORT : HTTP_PORT;
int requestPath = repositoryUrl.indexOf('/', colonPort + 1);
int end;
if (requestPath < 0)
end = repositoryUrl.length();
else
end = requestPath;
return Integer.parseInt(repositoryUrl.substring(colonPort + 1, end));
}
public static String getDomain(String repositoryUrl) {
String result = repositoryUrl;
int colonSlashSlash = repositoryUrl.indexOf("://");
if (colonSlashSlash >= 0) {
result = repositoryUrl.substring(colonSlashSlash + 3);
}
int colonPort = result.indexOf(':');
int requestPath = result.indexOf('/');
int substringEnd;
// minimum positive, or string length
if (colonPort > 0 && requestPath > 0)
substringEnd = Math.min(colonPort, requestPath);
else if (colonPort > 0)
substringEnd = colonPort;
else if (requestPath > 0)
substringEnd = requestPath;
else
substringEnd = result.length();
return result.substring(0, substringEnd);
}
public static String getRequestPath(String repositoryUrl) {
int colonSlashSlash = repositoryUrl.indexOf("://");
int requestPath = repositoryUrl.indexOf('/', colonSlashSlash + 3);
if (requestPath < 0) {
return "";
} else {
return repositoryUrl.substring(requestPath);
}
}
public static void setupHttpClient(HttpClient client, Proxy proxySettings, String repositoryUrl, String user,
String password) {
// Note: The following debug code requires http commons-logging and
// commons-logging-api jars
// System.setProperty("org.apache.commons.logging.Log",
// "org.apache.commons.logging.impl.SimpleLog");
- System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
- System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
- System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "debug");
- System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");
- System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient.HttpConnection", "trace");
+// System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
+// System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
+// System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "debug");
+// System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");
+// System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient.HttpConnection", "trace");
client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
client.getHttpConnectionManager().getParams().setSoTimeout(WebClientUtil.SOCKET_TIMEOUT);
client.getHttpConnectionManager().getParams().setConnectionTimeout(WebClientUtil.CONNNECT_TIMEOUT);
if (proxySettings != null && !Proxy.NO_PROXY.equals(proxySettings)
/* && !WebClientUtil.repositoryUsesHttps(repositoryUrl) */
&& proxySettings.address() instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) proxySettings.address();
client.getHostConfiguration().setProxy(WebClientUtil.getDomain(address.getHostName()), address.getPort());
if (proxySettings instanceof AuthenticatedProxy) {
AuthenticatedProxy authProxy = (AuthenticatedProxy) proxySettings;
Credentials credentials = getCredentials(authProxy, address);
AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(), AuthScope.ANY_REALM);
client.getState().setProxyCredentials(proxyAuthScope, credentials);
}
}
if (user != null && password != null) {
AuthScope authScope = new AuthScope(WebClientUtil.getDomain(repositoryUrl), WebClientUtil
.getPort(repositoryUrl), AuthScope.ANY_REALM);
client.getState().setCredentials(authScope, new UsernamePasswordCredentials(user, password));
}
if (WebClientUtil.repositoryUsesHttps(repositoryUrl)) {
Protocol acceptAllSsl = new Protocol("https", (ProtocolSocketFactory) SslProtocolSocketFactory
.getInstance(), WebClientUtil.getPort(repositoryUrl));
client.getHostConfiguration().setHost(WebClientUtil.getDomain(repositoryUrl),
WebClientUtil.getPort(repositoryUrl), acceptAllSsl);
// Protocol.registerProtocol("https", acceptAllSsl);
} else {
client.getHostConfiguration().setHost(WebClientUtil.getDomain(repositoryUrl),
WebClientUtil.getPort(repositoryUrl));
}
}
public static Credentials getCredentials(AuthenticatedProxy authProxy, InetSocketAddress address) {
String username = authProxy.getUserName();
int i = username.indexOf("\\");
if (i > 0 && i < username.length() - 1) {
return new NTCredentials(username.substring(i + 1), authProxy.getPassword(), address.getHostName(),
username.substring(0, i));
} else {
return new UsernamePasswordCredentials(username, authProxy.getPassword());
}
}
/** utility method, should use TaskRepository.getProxy() */
public static Proxy getProxy(String proxyHost, String proxyPort, String proxyUsername, String proxyPassword) {
boolean authenticated = (proxyUsername != null && proxyPassword != null && proxyUsername.length() > 0 && proxyPassword
.length() > 0);
if (proxyHost != null && proxyHost.length() > 0 && proxyPort != null && proxyPort.length() > 0) {
int proxyPortNum = Integer.parseInt(proxyPort);
InetSocketAddress sockAddr = new InetSocketAddress(proxyHost, proxyPortNum);
if (authenticated) {
return new AuthenticatedProxy(Type.HTTP, sockAddr, proxyUsername, proxyPassword);
} else {
return new Proxy(Type.HTTP, sockAddr);
}
}
return Proxy.NO_PROXY;
}
}
| true | true | public static void setupHttpClient(HttpClient client, Proxy proxySettings, String repositoryUrl, String user,
String password) {
// Note: The following debug code requires http commons-logging and
// commons-logging-api jars
// System.setProperty("org.apache.commons.logging.Log",
// "org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "debug");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient.HttpConnection", "trace");
client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
client.getHttpConnectionManager().getParams().setSoTimeout(WebClientUtil.SOCKET_TIMEOUT);
client.getHttpConnectionManager().getParams().setConnectionTimeout(WebClientUtil.CONNNECT_TIMEOUT);
if (proxySettings != null && !Proxy.NO_PROXY.equals(proxySettings)
/* && !WebClientUtil.repositoryUsesHttps(repositoryUrl) */
&& proxySettings.address() instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) proxySettings.address();
client.getHostConfiguration().setProxy(WebClientUtil.getDomain(address.getHostName()), address.getPort());
if (proxySettings instanceof AuthenticatedProxy) {
AuthenticatedProxy authProxy = (AuthenticatedProxy) proxySettings;
Credentials credentials = getCredentials(authProxy, address);
AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(), AuthScope.ANY_REALM);
client.getState().setProxyCredentials(proxyAuthScope, credentials);
}
}
if (user != null && password != null) {
AuthScope authScope = new AuthScope(WebClientUtil.getDomain(repositoryUrl), WebClientUtil
.getPort(repositoryUrl), AuthScope.ANY_REALM);
client.getState().setCredentials(authScope, new UsernamePasswordCredentials(user, password));
}
if (WebClientUtil.repositoryUsesHttps(repositoryUrl)) {
Protocol acceptAllSsl = new Protocol("https", (ProtocolSocketFactory) SslProtocolSocketFactory
.getInstance(), WebClientUtil.getPort(repositoryUrl));
client.getHostConfiguration().setHost(WebClientUtil.getDomain(repositoryUrl),
WebClientUtil.getPort(repositoryUrl), acceptAllSsl);
// Protocol.registerProtocol("https", acceptAllSsl);
} else {
client.getHostConfiguration().setHost(WebClientUtil.getDomain(repositoryUrl),
WebClientUtil.getPort(repositoryUrl));
}
}
| public static void setupHttpClient(HttpClient client, Proxy proxySettings, String repositoryUrl, String user,
String password) {
// Note: The following debug code requires http commons-logging and
// commons-logging-api jars
// System.setProperty("org.apache.commons.logging.Log",
// "org.apache.commons.logging.impl.SimpleLog");
// System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
// System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
// System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "debug");
// System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");
// System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient.HttpConnection", "trace");
client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
client.getHttpConnectionManager().getParams().setSoTimeout(WebClientUtil.SOCKET_TIMEOUT);
client.getHttpConnectionManager().getParams().setConnectionTimeout(WebClientUtil.CONNNECT_TIMEOUT);
if (proxySettings != null && !Proxy.NO_PROXY.equals(proxySettings)
/* && !WebClientUtil.repositoryUsesHttps(repositoryUrl) */
&& proxySettings.address() instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) proxySettings.address();
client.getHostConfiguration().setProxy(WebClientUtil.getDomain(address.getHostName()), address.getPort());
if (proxySettings instanceof AuthenticatedProxy) {
AuthenticatedProxy authProxy = (AuthenticatedProxy) proxySettings;
Credentials credentials = getCredentials(authProxy, address);
AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(), AuthScope.ANY_REALM);
client.getState().setProxyCredentials(proxyAuthScope, credentials);
}
}
if (user != null && password != null) {
AuthScope authScope = new AuthScope(WebClientUtil.getDomain(repositoryUrl), WebClientUtil
.getPort(repositoryUrl), AuthScope.ANY_REALM);
client.getState().setCredentials(authScope, new UsernamePasswordCredentials(user, password));
}
if (WebClientUtil.repositoryUsesHttps(repositoryUrl)) {
Protocol acceptAllSsl = new Protocol("https", (ProtocolSocketFactory) SslProtocolSocketFactory
.getInstance(), WebClientUtil.getPort(repositoryUrl));
client.getHostConfiguration().setHost(WebClientUtil.getDomain(repositoryUrl),
WebClientUtil.getPort(repositoryUrl), acceptAllSsl);
// Protocol.registerProtocol("https", acceptAllSsl);
} else {
client.getHostConfiguration().setHost(WebClientUtil.getDomain(repositoryUrl),
WebClientUtil.getPort(repositoryUrl));
}
}
|
diff --git a/src/mysqljavacat/dialogs/ExportToExcel.java b/src/mysqljavacat/dialogs/ExportToExcel.java
index 0ea3847..8660799 100644
--- a/src/mysqljavacat/dialogs/ExportToExcel.java
+++ b/src/mysqljavacat/dialogs/ExportToExcel.java
@@ -1,152 +1,152 @@
/*
* ExportToExcel.java
*
* Created on Dec 13, 2010, 1:28:25 PM
*/
package mysqljavacat.dialogs;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JTable;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.TableModel;
import mysqljavacat.MysqlJavaCatApp;
import mysqljavacat.MysqlJavaCatView;
import org.jdesktop.application.Task;
/**
*
* @author strelok
*/
public class ExportToExcel extends javax.swing.JDialog {
/** Creates new form ExportToExcel */
public ExportToExcel(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
jFileChooser1.addChoosableFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.getName().endsWith(".xml");
}
@Override
public String getDescription() {
return "XML file";
}
});
final ExportToExcel dialog = this;
jFileChooser1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("CancelSelection")){
dialog.dispose();
}else if(e.getActionCommand().equals("ApproveSelection")){
Task task = new Task(MysqlJavaCatApp.getApplication()) {
@Override
protected Object doInBackground() throws Exception {
MysqlJavaCatView view = MysqlJavaCatApp.getApplication().getView();
PrintWriter fw = null;
try {
fw = new PrintWriter(jFileChooser1.getSelectedFile());
StringBuffer out = new StringBuffer("<?xml version=\"1.0\"?>\n"
+"<?mso-application progid=\"Excel.Sheet\"?>\n"
+"<Workbook\n"
+"xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\n"
+"xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\n"
+"xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">\n"
+"<Worksheet ss:Name=\"Sheet1\">\n"
+"<ss:Table>\n");
JTable table = view.getResultTable();
TableModel model = table.getModel();
out.append("<ss:Row>\n");
for(int col = 1;col <= model.getColumnCount();col = col + 1){
- out.append("<ss:Cell><Data ss:Type=\"String\">");
+ out.append("<ss:Cell><ss:Data ss:Type=\"String\">");
out.append(model.getColumnName(col));
- out.append("</Data></ss:Cell>\n");
+ out.append("</ss:Data></ss:Cell>\n");
}
out.append("</ss:Row>\n");
fw.write(out.toString());
dialog.dispose();
out = new StringBuffer();
int buffer = 0;
for(int row = 0;row < model.getRowCount();row = row + 1){
out.append("<ss:Row>\n");
for(int col = 0;col < model.getColumnCount();col = col + 1){
out.append("<ss:Cell><Data ss:Type=\"String\">");
out.append(model.getValueAt(row, col));
out.append("</Data></ss:Cell>\n");
}
out.append("</ss:Row>\n");
if(buffer >= 10000){
fw.write(out.toString());
buffer = 0;
out = new StringBuffer();
}
buffer = buffer + 1;
setMessage("Exported: " + row);
}
- out.append("</Table>\n"
+ out.append("</ss:Table>\n"
+ "</Worksheet>\n"
+ "</Workbook>\n");
fw.write(out.toString());
fw.close();
} catch (IOException ex) {
MysqlJavaCatApp.getApplication().showError(ex.getMessage());
}
return null;
}
};
MysqlJavaCatApp.getApplication().getContext().getTaskService().execute(task);
MysqlJavaCatApp.getApplication().getContext().getTaskMonitor().setForegroundTask(task);
}
};
});
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jFileChooser1 = new javax.swing.JFileChooser();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setName("Form"); // NOI18N
jFileChooser1.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
jFileChooser1.setName("jFileChooser1"); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jFileChooser1, javax.swing.GroupLayout.DEFAULT_SIZE, 716, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jFileChooser1, javax.swing.GroupLayout.DEFAULT_SIZE, 410, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JFileChooser jFileChooser1;
// End of variables declaration//GEN-END:variables
}
| false | true | public ExportToExcel(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
jFileChooser1.addChoosableFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.getName().endsWith(".xml");
}
@Override
public String getDescription() {
return "XML file";
}
});
final ExportToExcel dialog = this;
jFileChooser1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("CancelSelection")){
dialog.dispose();
}else if(e.getActionCommand().equals("ApproveSelection")){
Task task = new Task(MysqlJavaCatApp.getApplication()) {
@Override
protected Object doInBackground() throws Exception {
MysqlJavaCatView view = MysqlJavaCatApp.getApplication().getView();
PrintWriter fw = null;
try {
fw = new PrintWriter(jFileChooser1.getSelectedFile());
StringBuffer out = new StringBuffer("<?xml version=\"1.0\"?>\n"
+"<?mso-application progid=\"Excel.Sheet\"?>\n"
+"<Workbook\n"
+"xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\n"
+"xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\n"
+"xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">\n"
+"<Worksheet ss:Name=\"Sheet1\">\n"
+"<ss:Table>\n");
JTable table = view.getResultTable();
TableModel model = table.getModel();
out.append("<ss:Row>\n");
for(int col = 1;col <= model.getColumnCount();col = col + 1){
out.append("<ss:Cell><Data ss:Type=\"String\">");
out.append(model.getColumnName(col));
out.append("</Data></ss:Cell>\n");
}
out.append("</ss:Row>\n");
fw.write(out.toString());
dialog.dispose();
out = new StringBuffer();
int buffer = 0;
for(int row = 0;row < model.getRowCount();row = row + 1){
out.append("<ss:Row>\n");
for(int col = 0;col < model.getColumnCount();col = col + 1){
out.append("<ss:Cell><Data ss:Type=\"String\">");
out.append(model.getValueAt(row, col));
out.append("</Data></ss:Cell>\n");
}
out.append("</ss:Row>\n");
if(buffer >= 10000){
fw.write(out.toString());
buffer = 0;
out = new StringBuffer();
}
buffer = buffer + 1;
setMessage("Exported: " + row);
}
out.append("</Table>\n"
+ "</Worksheet>\n"
+ "</Workbook>\n");
fw.write(out.toString());
fw.close();
} catch (IOException ex) {
MysqlJavaCatApp.getApplication().showError(ex.getMessage());
}
return null;
}
};
MysqlJavaCatApp.getApplication().getContext().getTaskService().execute(task);
MysqlJavaCatApp.getApplication().getContext().getTaskMonitor().setForegroundTask(task);
}
};
});
}
| public ExportToExcel(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
jFileChooser1.addChoosableFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.getName().endsWith(".xml");
}
@Override
public String getDescription() {
return "XML file";
}
});
final ExportToExcel dialog = this;
jFileChooser1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("CancelSelection")){
dialog.dispose();
}else if(e.getActionCommand().equals("ApproveSelection")){
Task task = new Task(MysqlJavaCatApp.getApplication()) {
@Override
protected Object doInBackground() throws Exception {
MysqlJavaCatView view = MysqlJavaCatApp.getApplication().getView();
PrintWriter fw = null;
try {
fw = new PrintWriter(jFileChooser1.getSelectedFile());
StringBuffer out = new StringBuffer("<?xml version=\"1.0\"?>\n"
+"<?mso-application progid=\"Excel.Sheet\"?>\n"
+"<Workbook\n"
+"xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\n"
+"xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\n"
+"xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">\n"
+"<Worksheet ss:Name=\"Sheet1\">\n"
+"<ss:Table>\n");
JTable table = view.getResultTable();
TableModel model = table.getModel();
out.append("<ss:Row>\n");
for(int col = 1;col <= model.getColumnCount();col = col + 1){
out.append("<ss:Cell><ss:Data ss:Type=\"String\">");
out.append(model.getColumnName(col));
out.append("</ss:Data></ss:Cell>\n");
}
out.append("</ss:Row>\n");
fw.write(out.toString());
dialog.dispose();
out = new StringBuffer();
int buffer = 0;
for(int row = 0;row < model.getRowCount();row = row + 1){
out.append("<ss:Row>\n");
for(int col = 0;col < model.getColumnCount();col = col + 1){
out.append("<ss:Cell><Data ss:Type=\"String\">");
out.append(model.getValueAt(row, col));
out.append("</Data></ss:Cell>\n");
}
out.append("</ss:Row>\n");
if(buffer >= 10000){
fw.write(out.toString());
buffer = 0;
out = new StringBuffer();
}
buffer = buffer + 1;
setMessage("Exported: " + row);
}
out.append("</ss:Table>\n"
+ "</Worksheet>\n"
+ "</Workbook>\n");
fw.write(out.toString());
fw.close();
} catch (IOException ex) {
MysqlJavaCatApp.getApplication().showError(ex.getMessage());
}
return null;
}
};
MysqlJavaCatApp.getApplication().getContext().getTaskService().execute(task);
MysqlJavaCatApp.getApplication().getContext().getTaskMonitor().setForegroundTask(task);
}
};
});
}
|
diff --git a/MODSRC/vazkii/tinkerer/tile/TileEntityFluxCollector.java b/MODSRC/vazkii/tinkerer/tile/TileEntityFluxCollector.java
index 9ca6fb5c..b4135508 100644
--- a/MODSRC/vazkii/tinkerer/tile/TileEntityFluxCollector.java
+++ b/MODSRC/vazkii/tinkerer/tile/TileEntityFluxCollector.java
@@ -1,244 +1,243 @@
/**
* This class was created by <Vazkii>. It's distributed as
* part of the ThaumicTinkerer Mod.
*
* ThaumicTinkerer is Open Source and distributed under a
* Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License
* (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB)
*
* ThaumicTinkerer is a Derivative Work on Thaumcraft 3.
* Thaumcraft 3 � Azanor 2012
* (http://www.minecraftforum.net/topic/1585216-)
*
* File Created @ [1 Jun 2013, 22:59:38 (GMT)]
*/
package vazkii.tinkerer.tile;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.packet.Packet;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import thaumcraft.api.EnumTag;
import thaumcraft.api.ObjectTags;
import thaumcraft.api.aura.AuraNode;
import thaumcraft.common.Config;
import thaumcraft.common.aura.AuraManager;
import vazkii.tinkerer.lib.LibBlockNames;
import vazkii.tinkerer.lib.LibFeatures;
import vazkii.tinkerer.network.PacketManager;
import vazkii.tinkerer.network.packet.PacketFluxCollectorSync;
import vazkii.tinkerer.util.helper.ItemNBTHelper;
import vazkii.tinkerer.util.helper.MiscHelper;
import cpw.mods.fml.common.network.PacketDispatcher;
public class TileEntityFluxCollector extends TileEntity implements ISidedInventory, net.minecraftforge.common.ISidedInventory {
private static final String TAG_ASPECT = "aspect";
private static final String TAG_TICKS_EXISTED = "ticksExisted";
ItemStack[] inventorySlots = new ItemStack[2];
public double ticksExisted = 0;
public int aspect = -1;
@Override
public void updateEntity() {
if(getStackInSlot(1) != null) {
ItemStack stack = getStackInSlot(1);
aspect = stack.getItemDamage();
PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket());
setInventorySlotContents(1, null);
}
if(ticksExisted % LibFeatures.FLUX_CONDENSER_INTERVAL == 0) {
ItemStack jar = getStackInSlot(0);
if(aspect >= 0 && jar != null) {
EnumTag tag = EnumTag.get(aspect);
AuraNode node = MiscHelper.getClosestNode(worldObj, xCoord, yCoord, zCoord);
if(node != null && node.level > 0) {
ObjectTags flux = node.flux;
if(flux != null && flux.getAmount(tag) > 0) {
flux.getAmount(tag);
boolean emptyJar = jar.itemID == Config.blockJar.blockID;
boolean can = emptyJar;
if(!can) {
NBTTagCompound cmp = jar.getTagCompound();
int aspect = cmp.getByte("tag");
int jarAmount = cmp.getByte("amount");
can = aspect == this.aspect && jarAmount < 64;
}
if(can) {
node.flux.reduceAmount(tag, 1);
if(worldObj.rand.nextInt(LibFeatures.FLUX_CONDENSER_VIS_CHANCE) == 0)
- node.level--;
- AuraManager.addToAuraUpdateList(node);
+ AuraManager.decreaseClosestAura(worldObj, xCoord, yCoord, zCoord, 1);
if(emptyJar) {
jar.itemID = Config.itemJarFilled.itemID;
ItemNBTHelper.setByte(jar, "tag", (byte) aspect);
ItemNBTHelper.setByte(jar, "amount", (byte) 1);
} else ItemNBTHelper.setByte(jar, "amount", (byte) (ItemNBTHelper.getByte(jar, "amount", (byte) 0) + 1));
}
}
}
}
}
++ticksExisted;
}
@Override
public void readFromNBT(NBTTagCompound par1NBTTagCompound) {
super.readFromNBT(par1NBTTagCompound);
aspect = par1NBTTagCompound.getInteger(TAG_ASPECT);
ticksExisted = par1NBTTagCompound.getInteger(TAG_TICKS_EXISTED);
NBTTagList var2 = par1NBTTagCompound.getTagList("Items");
inventorySlots = new ItemStack[getSizeInventory()];
for (int var3 = 0; var3 < var2.tagCount(); ++var3) {
NBTTagCompound var4 = (NBTTagCompound)var2.tagAt(var3);
byte var5 = var4.getByte("Slot");
if (var5 >= 0 && var5 < inventorySlots.length)
inventorySlots[var5] = ItemStack.loadItemStackFromNBT(var4);
}
}
@Override
public void writeToNBT(NBTTagCompound par1NBTTagCompound) {
super.writeToNBT(par1NBTTagCompound);
par1NBTTagCompound.setInteger(TAG_ASPECT, aspect);
par1NBTTagCompound.setDouble(TAG_TICKS_EXISTED, ticksExisted);
NBTTagList var2 = new NBTTagList();
for (int var3 = 0; var3 < inventorySlots.length; ++var3) {
if (inventorySlots[var3] != null) {
NBTTagCompound var4 = new NBTTagCompound();
var4.setByte("Slot", (byte)var3);
inventorySlots[var3].writeToNBT(var4);
var2.appendTag(var4);
}
}
par1NBTTagCompound.setTag("Items", var2);
}
@Override
public int getSizeInventory() {
return inventorySlots.length;
}
@Override
public ItemStack getStackInSlot(int i) {
if(i >= inventorySlots.length)
return null;
return inventorySlots[i];
}
@Override
public ItemStack decrStackSize(int par1, int par2) {
if (inventorySlots[par1] != null) {
ItemStack stackAt;
if (inventorySlots[par1].stackSize <= par2) {
stackAt = inventorySlots[par1];
inventorySlots[par1] = null;
return stackAt;
} else {
stackAt = inventorySlots[par1].splitStack(par2);
if (inventorySlots[par1].stackSize == 0)
inventorySlots[par1] = null;
return stackAt;
}
}
return null;
}
@Override
public ItemStack getStackInSlotOnClosing(int i) {
return getStackInSlot(i);
}
@Override
public void setInventorySlotContents(int i, ItemStack itemstack) {
inventorySlots[i] = itemstack;
}
@Override
public String getInvName() {
return LibBlockNames.FLUX_COLLECTOR_D;
}
@Override
public boolean isInvNameLocalized() {
return false;
}
@Override
public int getInventoryStackLimit() {
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer) {
return worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) != this ? false : entityplayer.getDistanceSq(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D) <= 64;
}
@Override
public void openChest() {
// NO-OP
}
@Override
public void closeChest() {
// NO-OP
}
@Override
public Packet getDescriptionPacket() {
return PacketManager.generatePacket(new PacketFluxCollectorSync(this));
}
@Override
public boolean isStackValidForSlot(int i, ItemStack itemstack) {
return false;
}
@Override
public int[] getAccessibleSlotsFromSide(int var1) {
return new int[0];
}
@Override
public boolean canInsertItem(int i, ItemStack itemstack, int j) {
return false;
}
@Override
public boolean canExtractItem(int i, ItemStack itemstack, int j) {
return canInsertItem(i, itemstack, j);
}
@Override
@Deprecated
public int getStartInventorySide(ForgeDirection side) {
return 0;
}
@Override
@Deprecated
public int getSizeInventorySide(ForgeDirection side) {
return 0;
}
}
| true | true | public void updateEntity() {
if(getStackInSlot(1) != null) {
ItemStack stack = getStackInSlot(1);
aspect = stack.getItemDamage();
PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket());
setInventorySlotContents(1, null);
}
if(ticksExisted % LibFeatures.FLUX_CONDENSER_INTERVAL == 0) {
ItemStack jar = getStackInSlot(0);
if(aspect >= 0 && jar != null) {
EnumTag tag = EnumTag.get(aspect);
AuraNode node = MiscHelper.getClosestNode(worldObj, xCoord, yCoord, zCoord);
if(node != null && node.level > 0) {
ObjectTags flux = node.flux;
if(flux != null && flux.getAmount(tag) > 0) {
flux.getAmount(tag);
boolean emptyJar = jar.itemID == Config.blockJar.blockID;
boolean can = emptyJar;
if(!can) {
NBTTagCompound cmp = jar.getTagCompound();
int aspect = cmp.getByte("tag");
int jarAmount = cmp.getByte("amount");
can = aspect == this.aspect && jarAmount < 64;
}
if(can) {
node.flux.reduceAmount(tag, 1);
if(worldObj.rand.nextInt(LibFeatures.FLUX_CONDENSER_VIS_CHANCE) == 0)
node.level--;
AuraManager.addToAuraUpdateList(node);
if(emptyJar) {
jar.itemID = Config.itemJarFilled.itemID;
ItemNBTHelper.setByte(jar, "tag", (byte) aspect);
ItemNBTHelper.setByte(jar, "amount", (byte) 1);
} else ItemNBTHelper.setByte(jar, "amount", (byte) (ItemNBTHelper.getByte(jar, "amount", (byte) 0) + 1));
}
}
}
}
}
++ticksExisted;
}
| public void updateEntity() {
if(getStackInSlot(1) != null) {
ItemStack stack = getStackInSlot(1);
aspect = stack.getItemDamage();
PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket());
setInventorySlotContents(1, null);
}
if(ticksExisted % LibFeatures.FLUX_CONDENSER_INTERVAL == 0) {
ItemStack jar = getStackInSlot(0);
if(aspect >= 0 && jar != null) {
EnumTag tag = EnumTag.get(aspect);
AuraNode node = MiscHelper.getClosestNode(worldObj, xCoord, yCoord, zCoord);
if(node != null && node.level > 0) {
ObjectTags flux = node.flux;
if(flux != null && flux.getAmount(tag) > 0) {
flux.getAmount(tag);
boolean emptyJar = jar.itemID == Config.blockJar.blockID;
boolean can = emptyJar;
if(!can) {
NBTTagCompound cmp = jar.getTagCompound();
int aspect = cmp.getByte("tag");
int jarAmount = cmp.getByte("amount");
can = aspect == this.aspect && jarAmount < 64;
}
if(can) {
node.flux.reduceAmount(tag, 1);
if(worldObj.rand.nextInt(LibFeatures.FLUX_CONDENSER_VIS_CHANCE) == 0)
AuraManager.decreaseClosestAura(worldObj, xCoord, yCoord, zCoord, 1);
if(emptyJar) {
jar.itemID = Config.itemJarFilled.itemID;
ItemNBTHelper.setByte(jar, "tag", (byte) aspect);
ItemNBTHelper.setByte(jar, "amount", (byte) 1);
} else ItemNBTHelper.setByte(jar, "amount", (byte) (ItemNBTHelper.getByte(jar, "amount", (byte) 0) + 1));
}
}
}
}
}
++ticksExisted;
}
|
diff --git a/src/main/java/com/inmobi/databus/consume/DataConsumer.java b/src/main/java/com/inmobi/databus/consume/DataConsumer.java
index 719f281d..0ed86c87 100644
--- a/src/main/java/com/inmobi/databus/consume/DataConsumer.java
+++ b/src/main/java/com/inmobi/databus/consume/DataConsumer.java
@@ -1,219 +1,216 @@
package com.inmobi.databus.consume;
import com.inmobi.databus.AbstractCopier;
import com.inmobi.databus.DatabusConfig;
import com.inmobi.databus.DatabusConfig.Cluster;
import com.inmobi.databus.DatabusConfig.Stream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
public class DataConsumer extends AbstractCopier {
private static final Log LOG = LogFactory.getLog(DataConsumer.class);
private Path tmpPath;
private Path tmpJobInputPath;
private Path tmpJobOutputPath;
public DataConsumer(DatabusConfig config, Cluster cluster) {
super(config, cluster, cluster);
this.tmpPath = new Path(cluster.getTmpPath(), getName());
this.tmpJobInputPath = new Path(tmpPath, "jobIn");
this.tmpJobOutputPath = new Path(tmpPath, "jobOut");
}
protected void addStreamsToFetch() {
for (Stream s : getConfig().getStreams().values()) {
if (s.getSourceClusters().contains(getSrcCluster())) {
streamsToFetch.add(s);
}
}
}
@Override
protected void fetch() throws Exception {
Map<FileStatus, String> fileListing = new HashMap<FileStatus, String>();
createMRInput(tmpJobInputPath, fileListing);
if (fileListing.size() == 0) {
LOG.info("Nothing to do!");
return;
}
Job job = createJob(tmpJobInputPath);
job.waitForCompletion(true);
if (job.isSuccessful()) {
long commitTime = System.currentTimeMillis();
Map<Path, Path> commitPaths = prepareForCommit(commitTime, fileListing);
commit(commitPaths);
LOG.info("Committed successfully for " + commitTime);
}
}
private Map<Path, Path> prepareForCommit(long commitTime,
Map<FileStatus, String> fileListing) throws IOException {
FileSystem fs = FileSystem.get(getSrcCluster().getHadoopConf());
// find final destination paths
Map<Path, Path> mvPaths = new LinkedHashMap<Path, Path>();
FileStatus[] categories = fs.listStatus(tmpJobOutputPath);
for (FileStatus categoryDir : categories) {
Path destDir = new Path(getSrcCluster().getFinalDestDir(
categoryDir.getPath().getName(), commitTime));
FileStatus[] files = fs.listStatus(categoryDir.getPath());
for (FileStatus file : files) {
Path destPath = new Path(destDir, file.getPath().getName());
mvPaths.put(file.getPath(), destPath);
}
}
// find input files for consumers
Map<Path, Path> consumerCommitPaths = new HashMap<Path, Path>();
for (Cluster cluster : getConfig().getClusters().values()) {
if (cluster.getName().equals(getSrcCluster().getName())) {
continue;
}
Set<String> consumeStreams = cluster.getConsumeStreams().keySet();
boolean consumeCluster = false;
for(String stream : consumeStreams) {
if (getSrcCluster().getSourceStreams().contains(stream)){
consumeCluster = true;
break;
}
}
if (consumeCluster) {
Path tmpConsumerPath = new Path(tmpPath, cluster.getName());
FSDataOutputStream out = fs.create(tmpConsumerPath);
for (Path destPath : mvPaths.values()) {
String category = getCategoryFromDestPath(destPath);
if (cluster.getConsumeStreams().containsKey(category)) {
out.writeBytes(destPath.toString());
out.writeBytes("\n");
}
}
out.close();
Path finalConsumerPath = new Path(getSrcCluster().getConsumePath(
cluster),
Long.toString(commitTime));
consumerCommitPaths.put(tmpConsumerPath, finalConsumerPath);
}
}
// find trash paths
Map<Path, Path> trashPaths = new LinkedHashMap<Path, Path>();
Path trash = getSrcCluster().getTrashPath();
for (FileStatus src : fileListing.keySet()) {
String category = getCategoryFromSrcPath(src.getPath());
Path target = null;
- synchronized (DataConsumer.class) {
- //trash path can conflict if we run multiple consumer
- target = new Path(trash, src.getPath().getName() + "-" + System.currentTimeMillis());
- }
+ target = new Path(trash, src.getPath().getParent().getName() + "-" + src.getPath().getName());
LOG.debug("Trashing [" + src.getPath() + "] to [" + target + "]");
trashPaths.put(src.getPath(), target);
}
Map<Path, Path> commitPaths = new LinkedHashMap<Path, Path>();
if (mvPaths.size() == trashPaths.size()) {// validate the no of files
commitPaths.putAll(mvPaths);
commitPaths.putAll(consumerCommitPaths);
// TODO:
LOG.debug("Adding trash paths for commit");
commitPaths.putAll(trashPaths);
}
return commitPaths;
}
private void commit(Map<Path, Path> commitPaths) throws IOException {
LOG.info("Committing " + commitPaths.size() + " paths.");
FileSystem fs = FileSystem.get(getSrcCluster().getHadoopConf());
for (Map.Entry<Path, Path> entry : commitPaths.entrySet()) {
LOG.info("Renaming " + entry.getKey() + " to " + entry.getValue());
fs.mkdirs(entry.getValue().getParent());
fs.rename(entry.getKey(), entry.getValue());
}
}
private void createMRInput(Path inputPath, Map<FileStatus, String> fileListing)
throws IOException {
FileSystem fs = FileSystem.get(getSrcCluster().getHadoopConf());
createListing(fs, fs.getFileStatus(getSrcCluster().getDataDir()), fileListing,
new HashSet<String>());
FSDataOutputStream out = fs.create(inputPath);
Iterator<Entry<FileStatus, String>> it = fileListing.entrySet().iterator();
while (it.hasNext()) {
Entry<FileStatus, String> entry = it.next();
out.writeBytes(entry.getKey().getPath().toString());
out.writeBytes("\t");
out.writeBytes(entry.getValue());
out.writeBytes("\n");
}
out.close();
}
private void createListing(FileSystem fs, FileStatus fileStatus,
Map<FileStatus, String> results, Set<String> excludes) throws IOException {
if (fileStatus.isDir()) {
for (FileStatus stat : fs.listStatus(fileStatus.getPath())) {
createListing(fs, stat, results, excludes);
}
} else {
String fileName = fileStatus.getPath().getName();
if (fileName.endsWith("current")) {
FSDataInputStream in = fs.open(fileStatus.getPath());
String currentFileName = in.readLine();
in.close();
excludes.add(currentFileName);
} else if ("scribe_stats".equalsIgnoreCase(fileName.trim())) {
excludes.add(fileName);
} else if (!excludes.contains(fileName)) {
Path src = fileStatus.getPath().makeQualified(fs);
String category = getCategoryFromSrcPath(src);
String destDir = getCategoryJobOutTmpPath(category).toString();
// String destDir = getConfig().getDestDir(category);
results.put(fileStatus, destDir);
}
}
}
private String getCategoryFromSrcPath(Path src) {
return src.getParent().getParent().getName();
}
private String getCategoryFromDestPath(Path dest) {
return dest.getParent().getParent().getParent().getParent().getParent()
.getParent().getName();
}
private Path getCategoryJobOutTmpPath(String category) {
return new Path(tmpJobOutputPath, category);
}
private Job createJob(Path inputPath) throws IOException {
String jobName = "consumer";
Configuration conf = getSrcCluster().getHadoopConf();
Job job = new Job(conf);
job.setJobName(jobName);
KeyValueTextInputFormat.setInputPaths(job, inputPath);
job.setInputFormatClass(KeyValueTextInputFormat.class);
job.setJarByClass(CopyMapper.class);
job.setMapperClass(CopyMapper.class);
job.setNumReduceTasks(0);
job.setOutputFormatClass(NullOutputFormat.class);
job.getConfiguration().set("mapred.map.tasks.speculative.execution",
"false");
return job;
}
}
| true | true | private Map<Path, Path> prepareForCommit(long commitTime,
Map<FileStatus, String> fileListing) throws IOException {
FileSystem fs = FileSystem.get(getSrcCluster().getHadoopConf());
// find final destination paths
Map<Path, Path> mvPaths = new LinkedHashMap<Path, Path>();
FileStatus[] categories = fs.listStatus(tmpJobOutputPath);
for (FileStatus categoryDir : categories) {
Path destDir = new Path(getSrcCluster().getFinalDestDir(
categoryDir.getPath().getName(), commitTime));
FileStatus[] files = fs.listStatus(categoryDir.getPath());
for (FileStatus file : files) {
Path destPath = new Path(destDir, file.getPath().getName());
mvPaths.put(file.getPath(), destPath);
}
}
// find input files for consumers
Map<Path, Path> consumerCommitPaths = new HashMap<Path, Path>();
for (Cluster cluster : getConfig().getClusters().values()) {
if (cluster.getName().equals(getSrcCluster().getName())) {
continue;
}
Set<String> consumeStreams = cluster.getConsumeStreams().keySet();
boolean consumeCluster = false;
for(String stream : consumeStreams) {
if (getSrcCluster().getSourceStreams().contains(stream)){
consumeCluster = true;
break;
}
}
if (consumeCluster) {
Path tmpConsumerPath = new Path(tmpPath, cluster.getName());
FSDataOutputStream out = fs.create(tmpConsumerPath);
for (Path destPath : mvPaths.values()) {
String category = getCategoryFromDestPath(destPath);
if (cluster.getConsumeStreams().containsKey(category)) {
out.writeBytes(destPath.toString());
out.writeBytes("\n");
}
}
out.close();
Path finalConsumerPath = new Path(getSrcCluster().getConsumePath(
cluster),
Long.toString(commitTime));
consumerCommitPaths.put(tmpConsumerPath, finalConsumerPath);
}
}
// find trash paths
Map<Path, Path> trashPaths = new LinkedHashMap<Path, Path>();
Path trash = getSrcCluster().getTrashPath();
for (FileStatus src : fileListing.keySet()) {
String category = getCategoryFromSrcPath(src.getPath());
Path target = null;
synchronized (DataConsumer.class) {
//trash path can conflict if we run multiple consumer
target = new Path(trash, src.getPath().getName() + "-" + System.currentTimeMillis());
}
LOG.debug("Trashing [" + src.getPath() + "] to [" + target + "]");
trashPaths.put(src.getPath(), target);
}
Map<Path, Path> commitPaths = new LinkedHashMap<Path, Path>();
if (mvPaths.size() == trashPaths.size()) {// validate the no of files
commitPaths.putAll(mvPaths);
commitPaths.putAll(consumerCommitPaths);
// TODO:
LOG.debug("Adding trash paths for commit");
commitPaths.putAll(trashPaths);
}
return commitPaths;
}
| private Map<Path, Path> prepareForCommit(long commitTime,
Map<FileStatus, String> fileListing) throws IOException {
FileSystem fs = FileSystem.get(getSrcCluster().getHadoopConf());
// find final destination paths
Map<Path, Path> mvPaths = new LinkedHashMap<Path, Path>();
FileStatus[] categories = fs.listStatus(tmpJobOutputPath);
for (FileStatus categoryDir : categories) {
Path destDir = new Path(getSrcCluster().getFinalDestDir(
categoryDir.getPath().getName(), commitTime));
FileStatus[] files = fs.listStatus(categoryDir.getPath());
for (FileStatus file : files) {
Path destPath = new Path(destDir, file.getPath().getName());
mvPaths.put(file.getPath(), destPath);
}
}
// find input files for consumers
Map<Path, Path> consumerCommitPaths = new HashMap<Path, Path>();
for (Cluster cluster : getConfig().getClusters().values()) {
if (cluster.getName().equals(getSrcCluster().getName())) {
continue;
}
Set<String> consumeStreams = cluster.getConsumeStreams().keySet();
boolean consumeCluster = false;
for(String stream : consumeStreams) {
if (getSrcCluster().getSourceStreams().contains(stream)){
consumeCluster = true;
break;
}
}
if (consumeCluster) {
Path tmpConsumerPath = new Path(tmpPath, cluster.getName());
FSDataOutputStream out = fs.create(tmpConsumerPath);
for (Path destPath : mvPaths.values()) {
String category = getCategoryFromDestPath(destPath);
if (cluster.getConsumeStreams().containsKey(category)) {
out.writeBytes(destPath.toString());
out.writeBytes("\n");
}
}
out.close();
Path finalConsumerPath = new Path(getSrcCluster().getConsumePath(
cluster),
Long.toString(commitTime));
consumerCommitPaths.put(tmpConsumerPath, finalConsumerPath);
}
}
// find trash paths
Map<Path, Path> trashPaths = new LinkedHashMap<Path, Path>();
Path trash = getSrcCluster().getTrashPath();
for (FileStatus src : fileListing.keySet()) {
String category = getCategoryFromSrcPath(src.getPath());
Path target = null;
target = new Path(trash, src.getPath().getParent().getName() + "-" + src.getPath().getName());
LOG.debug("Trashing [" + src.getPath() + "] to [" + target + "]");
trashPaths.put(src.getPath(), target);
}
Map<Path, Path> commitPaths = new LinkedHashMap<Path, Path>();
if (mvPaths.size() == trashPaths.size()) {// validate the no of files
commitPaths.putAll(mvPaths);
commitPaths.putAll(consumerCommitPaths);
// TODO:
LOG.debug("Adding trash paths for commit");
commitPaths.putAll(trashPaths);
}
return commitPaths;
}
|
diff --git a/opentripplanner-analyst/src/main/java/org/opentripplanner/analyst/batch/BasicPopulation.java b/opentripplanner-analyst/src/main/java/org/opentripplanner/analyst/batch/BasicPopulation.java
index 1c9c74739..210426fc3 100644
--- a/opentripplanner-analyst/src/main/java/org/opentripplanner/analyst/batch/BasicPopulation.java
+++ b/opentripplanner-analyst/src/main/java/org/opentripplanner/analyst/batch/BasicPopulation.java
@@ -1,188 +1,190 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.analyst.batch;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.csvreader.CsvWriter;
public class BasicPopulation implements Population {
private static final Logger LOG = LoggerFactory.getLogger(BasicPopulation.class);
@Setter
public String sourceFilename;
@Setter @Getter
public List<Individual> individuals = new ArrayList<Individual>();
@Setter @Getter
public List<IndividualFilter> filterChain = null;
private boolean[] skip = null;
public BasicPopulation() { }
public BasicPopulation(Individual... individuals) {
this.individuals = Arrays.asList(individuals);
}
public BasicPopulation(Collection<Individual> individuals) {
this.individuals = new ArrayList<Individual>(individuals);
}
@Override
public void addIndividual(Individual individual) {
this.individuals.add(individual);
}
@Override
public Iterator<Individual> iterator() {
return new PopulationIterator();
}
@Override
public void clearIndividuals(List<Individual> individuals) {
this.individuals.clear();
}
@Override
public void createIndividuals() {
// nothing to do in the basic population case
}
@Override
public int size() {
return this.individuals.size();
}
protected void writeCsv(String outFileName, ResultSet results) {
LOG.debug("Writing population to CSV: {}", outFileName);
try {
CsvWriter writer = new CsvWriter(outFileName, ',', Charset.forName("UTF8"));
writer.writeRecord( new String[] {"label", "lat", "lon", "input", "output"} );
int i = 0;
+ int j = 0;
// using internal list rather than filtered iterator
for (Individual indiv : this.individuals) {
if ( ! this.skip[i]) {
String[] entries = new String[] {
indiv.label, Double.toString(indiv.lat), Double.toString(indiv.lon),
- Double.toString(indiv.input), Double.toString(results.results[i])
+ Double.toString(indiv.input), Double.toString(results.results[j])
};
writer.writeRecord(entries);
+ j++;
}
i++;
}
writer.close(); // flush writes and close
} catch (Exception e) {
LOG.error("Error while writing to CSV file: {}", e.getMessage());
return;
}
LOG.debug("Done writing population to CSV at {}.", outFileName);
}
@Override
public void writeAppropriateFormat(String outFileName, ResultSet results) {
// as a default, save to CSV. override this method in subclasses when more is known about data structure.
this.writeCsv(outFileName, results);
}
// TODO maybe store skip values in the samples themselves?
/**
* If a filter chain is specified, apply it to the individuals. Must be called after loading
* or generating the individuals. Filtering does not actually remove individuals from the
* population, it merely tags them as rejected. This is important for structured populations
* like rasters, where we may need to write out all individuals including those that were
* skipped.
*/
private void applyFilterChain() {
this.skip = new boolean[individuals.size()]; // initialized to false
if (filterChain == null) // no filter chain, do not reject any individuals
return;
for (IndividualFilter filter : filterChain) {
LOG.info("applying filter {}", filter);
int rejected = 0;
int i = 0;
for (Individual individual : this.individuals) {
boolean skipThis = ! filter.filter(individual);
if (skipThis)
rejected += 1;
skip[i++] |= skipThis;
}
LOG.info("accepted {} rejected {}", skip.length - rejected, rejected);
}
int rejected = 0;
for (boolean s : skip)
if (s)
rejected += 1;
LOG.info("TOTALS: accepted {} rejected {}", skip.length - rejected, rejected);
}
@Override
public void setup() {
// call the subclass-specific file loading method
this.createIndividuals();
// call the shared filter chain method
this.applyFilterChain();
}
class PopulationIterator implements Iterator<Individual> {
int i = 0;
int n = individuals.size();
Iterator<Individual> iter = individuals.iterator();
public boolean hasNext() {
while (i < n && skip[i]) {
//LOG.debug("in iter, i = {}", i);
if (! iter.hasNext())
return false;
i += 1;
iter.next();
}
//LOG.debug("done skipping at {}", i);
return iter.hasNext();
}
public Individual next() {
if (this.hasNext()) {
Individual ret = iter.next();
i += 1;
return ret;
} else {
throw new NoSuchElementException();
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| false | true | protected void writeCsv(String outFileName, ResultSet results) {
LOG.debug("Writing population to CSV: {}", outFileName);
try {
CsvWriter writer = new CsvWriter(outFileName, ',', Charset.forName("UTF8"));
writer.writeRecord( new String[] {"label", "lat", "lon", "input", "output"} );
int i = 0;
// using internal list rather than filtered iterator
for (Individual indiv : this.individuals) {
if ( ! this.skip[i]) {
String[] entries = new String[] {
indiv.label, Double.toString(indiv.lat), Double.toString(indiv.lon),
Double.toString(indiv.input), Double.toString(results.results[i])
};
writer.writeRecord(entries);
}
i++;
}
writer.close(); // flush writes and close
} catch (Exception e) {
LOG.error("Error while writing to CSV file: {}", e.getMessage());
return;
}
LOG.debug("Done writing population to CSV at {}.", outFileName);
}
| protected void writeCsv(String outFileName, ResultSet results) {
LOG.debug("Writing population to CSV: {}", outFileName);
try {
CsvWriter writer = new CsvWriter(outFileName, ',', Charset.forName("UTF8"));
writer.writeRecord( new String[] {"label", "lat", "lon", "input", "output"} );
int i = 0;
int j = 0;
// using internal list rather than filtered iterator
for (Individual indiv : this.individuals) {
if ( ! this.skip[i]) {
String[] entries = new String[] {
indiv.label, Double.toString(indiv.lat), Double.toString(indiv.lon),
Double.toString(indiv.input), Double.toString(results.results[j])
};
writer.writeRecord(entries);
j++;
}
i++;
}
writer.close(); // flush writes and close
} catch (Exception e) {
LOG.error("Error while writing to CSV file: {}", e.getMessage());
return;
}
LOG.debug("Done writing population to CSV at {}.", outFileName);
}
|
diff --git a/tools/etfw/org.eclipse.ptp.etfw/src/org/eclipse/ptp/etfw/internal/RemoteBuildLaunchUtils.java b/tools/etfw/org.eclipse.ptp.etfw/src/org/eclipse/ptp/etfw/internal/RemoteBuildLaunchUtils.java
index efc4caff7..2c1bcb022 100644
--- a/tools/etfw/org.eclipse.ptp.etfw/src/org/eclipse/ptp/etfw/internal/RemoteBuildLaunchUtils.java
+++ b/tools/etfw/org.eclipse.ptp.etfw/src/org/eclipse/ptp/etfw/internal/RemoteBuildLaunchUtils.java
@@ -1,654 +1,655 @@
/****************************************************************************
* Tuning and Analysis Utilities
* http://www.cs.uoregon.edu/research/paracomp/tau
****************************************************************************
* Copyright (c) 1997-2006
* Department of Computer and Information Science, University of Oregon
* Advanced Computing Laboratory, Los Alamos National Laboratory
* Research Center Juelich, ZAM Germany
*
* 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:
* Wyatt Spear - initial API and implementation
****************************************************************************/
package org.eclipse.ptp.etfw.internal;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileInfo;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ptp.core.IPTPLaunchConfigurationConstants;
import org.eclipse.ptp.core.util.LaunchUtils;
import org.eclipse.ptp.ems.core.EnvManagerProjectProperties;
import org.eclipse.ptp.ems.core.EnvManagerRegistry;
import org.eclipse.ptp.ems.core.IEnvManager;
import org.eclipse.ptp.ems.core.IEnvManagerConfig;
import org.eclipse.ptp.etfw.Activator;
import org.eclipse.ptp.etfw.IBuildLaunchUtils;
import org.eclipse.ptp.etfw.IToolLaunchConfigurationConstants;
import org.eclipse.ptp.etfw.messages.Messages;
import org.eclipse.ptp.etfw.toolopts.ExternalToolProcess;
import org.eclipse.ptp.remote.core.IRemoteConnection;
import org.eclipse.ptp.remote.core.IRemoteConnectionManager;
import org.eclipse.ptp.remote.core.IRemoteFileManager;
import org.eclipse.ptp.remote.core.IRemoteProcess;
import org.eclipse.ptp.remote.core.IRemoteProcessBuilder;
import org.eclipse.ptp.remote.core.IRemoteServices;
import org.eclipse.ptp.remote.core.exception.RemoteConnectionException;
import org.eclipse.ptp.remote.ui.IRemoteUIFileManager;
import org.eclipse.ptp.remote.ui.IRemoteUIServices;
import org.eclipse.ptp.remote.ui.PTPRemoteUIPlugin;
import org.eclipse.swt.widgets.Shell;
public class RemoteBuildLaunchUtils implements IBuildLaunchUtils {
Shell selshell = null;
ILaunchConfiguration config;
IRemoteConnection conn = null;
IRemoteServices remoteServices = null;
IRemoteUIServices remoteUIServices = null;
IRemoteConnectionManager connMgr = null;
IRemoteUIFileManager fileManagerUI = null;
IRemoteFileManager fileManager = null;
IEnvManagerConfig envMgrConfig=null;
private IEnvManager envManager=null;
public RemoteBuildLaunchUtils(ILaunchConfiguration config) {
this.config = config;
remoteServices = PTPRemoteUIPlugin.getDefault().getRemoteServices(LaunchUtils.getRemoteServicesId(config), null);// ,getLaunchConfigurationDialog()
remoteUIServices = PTPRemoteUIPlugin.getDefault().getRemoteUIServices(remoteServices);
connMgr = remoteServices.getConnectionManager();
conn = connMgr.getConnection(LaunchUtils.getConnectionName(config));
fileManagerUI = remoteUIServices.getUIFileManager();
fileManager = remoteServices.getFileManager(conn);
envMgrConfig = getEnvManagerConfig(config);
if (envMgrConfig != null) {
envManager = EnvManagerRegistry.getEnvManager(null, conn);
// if (envManager != null) {
// //moduleSetup = envManager.getBashConcatenation(";", false, envMgrConfig, null);
// moduleSetup = envManager.createBashScript(null, false, config, commandToExecuteAfterward)
//
// }
}
// this.selshell=PlatformUI.getWorkbench().getDisplay().getActiveShell();
}
public String getWorkingDirectory() {
return conn.getWorkingDirectory();
}
/**
* Returns the directory containing the tool's executable file. Prompts the user for the location if it is not found. Returns
* the empty string if no selection is made
*
* @param toolfind
* The name of the executable being sought
* @param suggPath
* The suggested path upon which to focus the directory locator window
* @param queryText
* The text asking the user to search for the binary
* @param queryMessage
* The text providing more detail on the search task
* @param selshell
* The shell in which to launch the directory locator window
* @return
*/
public String findToolBinPath(String toolfind, String suggPath, String queryText, String queryMessage) {
String vtbinpath = checkToolEnvPath(toolfind);
if (vtbinpath == null || vtbinpath.equals("")) //$NON-NLS-1$
{
vtbinpath = askToolPath(suggPath, queryText, queryMessage);
if (vtbinpath == null) {
vtbinpath = ""; //$NON-NLS-1$
}
}
return vtbinpath;
}
/**
* Returns the directory containing the tool's executable file. Prompts the user for the location if it is not found. Returns
* the empty string if no selection is made
*
* @param toolfind
* The name of the executable being sought
* @param suggPath
* The suggested path upon which to focus the directory locator window
* @param toolName
* The name of the tool used when prompting the user for its location
* @param selshell
* The shell in which to launch the directory locator window
* @return
*/
public String findToolBinPath(String toolfind, String suggPath, String toolName) {
String vtbinpath = checkToolEnvPath(toolfind);
if (vtbinpath == null || vtbinpath.equals("")) //$NON-NLS-1$
{
vtbinpath = askToolPath(suggPath, toolName);
if (vtbinpath == null) {
vtbinpath = ""; //$NON-NLS-1$
}
}
return vtbinpath;
}
/**
* Given a tool's ID, returns the path to that tool's bin directory if already known and stored locally, otherwise returns the
* empty string
*
* @param toolID
* @return
*/
public String getToolPath(String toolID) {
IPreferenceStore pstore = Activator.getDefault().getPreferenceStore();
String toolBinID = IToolLaunchConfigurationConstants.TOOL_BIN_ID
+ "." + toolID + "." + LaunchUtils.getResourceManagerUniqueName(config); //$NON-NLS-1$//$NON-NLS-2$
String path = pstore.getString(toolBinID);
if (path != null) {
return path;
}
return ""; //$NON-NLS-1$
}
/**
* Iterates through an array of tools, populating the preference store with their binary directory locations
*
* @param tools
* The array of tools to be checked
* @param force
* If true existing values will be overridden.
*/
public void getAllToolPaths(ExternalToolProcess[] tools, boolean force) {
IPreferenceStore pstore = Activator.getDefault().getPreferenceStore();
// Shell ourshell = PlatformUI.getWorkbench().getDisplay().getActiveShell();
Iterator<Map.Entry<String, String>> eIt = null;
Map.Entry<String, String> me = null;
String entry = null;
for (int i = 0; i < tools.length; i++) {
eIt = tools[i].groupApp.entrySet().iterator();
while (eIt.hasNext()) {
me = eIt.next();
entry = me.getKey();
if (entry.equals("internal")) { //$NON-NLS-1$
continue;
}
String toolBinID = IToolLaunchConfigurationConstants.TOOL_BIN_ID
+ "." + entry + "." + LaunchUtils.getResourceManagerUniqueName(config); //$NON-NLS-1$ //$NON-NLS-2$
if (force || pstore.getString(toolBinID).equals("")) //$NON-NLS-1$
{
pstore.setValue(toolBinID, findToolBinPath(me.getValue(), null, entry));// findToolBinPath(tools[i].pathFinder,null,tools[i].queryText,tools[i].queryMessage)
}
}
}
}
public void verifyRequestToolPath(ExternalToolProcess tool, boolean force) {
IPreferenceStore pstore = Activator.getDefault().getPreferenceStore();
// Shell ourshell = PlatformUI.getWorkbench().getDisplay().getActiveShell();
Iterator<Map.Entry<String, String>> eIt = null;
Map.Entry<String, String> me = null;
String entry = null;
eIt = tool.groupApp.entrySet().iterator();
while (eIt.hasNext()) {
me = eIt.next();
entry = me.getKey();
if (entry.equals("internal")) { //$NON-NLS-1$
continue;
}
String toolBinID = IToolLaunchConfigurationConstants.TOOL_BIN_ID
+ "." + entry + "." + LaunchUtils.getResourceManagerUniqueName(config); //$NON-NLS-1$ //$NON-NLS-2$
if (force || pstore.getString(toolBinID).equals("")) //$NON-NLS-1$
{
pstore.setValue(toolBinID, findToolBinPath(me.getValue(), null, entry));// findToolBinPath(tools[i].pathFinder,null,tools[i].queryText,tools[i].queryMessage)
}
}
}
public void verifyEnvToolPath(ExternalToolProcess tool) {
IPreferenceStore pstore = Activator.getDefault().getPreferenceStore();
Iterator<Map.Entry<String, String>> eIt = null;
Map.Entry<String, String> me = null;
String entry = null;
String toolBinID = null;
String curTool = null;
eIt = tool.groupApp.entrySet().iterator();
while (eIt.hasNext()) {
me = eIt.next();
entry = me.getKey();
if (entry.equals("internal")) { //$NON-NLS-1$
continue;
}
toolBinID = IToolLaunchConfigurationConstants.TOOL_BIN_ID
+ "." + entry + "." + LaunchUtils.getResourceManagerUniqueName(config); //$NON-NLS-1$ //$NON-NLS-2$
curTool = pstore.getString(toolBinID);
IFileStore ttool = fileManager.getResource(curTool);
if (curTool == null || curTool.equals("") || !(ttool.fetchInfo().exists())) //$NON-NLS-1$
{
String gVal = me.getValue();
if (gVal != null && gVal.trim().length() > 0) {
curTool = checkToolEnvPath(gVal);
if (curTool != null) {
pstore.setValue(toolBinID, curTool);// findToolBinPath(tools[i].pathFinder,null,tools[i].queryText,tools[i].queryMessage)
}
}
}
}
}
/**
* Get the environment manager configuration associated with the project that was specified in the launch configuration. If no
* launchConfiguration was specified then this CommandJob does not need to use environment management so we can safely return
* null.
*
* @return environment manager configuration or null if no configuration can be found
*/
private IEnvManagerConfig getEnvManagerConfig(ILaunchConfiguration configuration) {
try {
String projectName = configuration.getAttribute(IPTPLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String) null);
if (projectName != null) {
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (project != null) {
final EnvManagerProjectProperties projectProperties = new EnvManagerProjectProperties(project);
if (projectProperties.isEnvMgmtEnabled()) {
return projectProperties;
}
}
}
} catch (CoreException e) {
// Ignore
}
return null;
}
/**
* This locates name of the parent of the directory containing the given tool.
*
* @param The
* name of the tool whose directory is being located
* @return The location of the tool's arch directory, or null if it is not found or if the architecture is windows
*
*/
public String checkToolEnvPath(String toolname) {
- if (org.eclipse.cdt.utils.Platform.getOS().toLowerCase().trim().indexOf("win") >= 0) {//$NON-NLS-1$
+ if (org.eclipse.cdt.utils.Platform.getOS().toLowerCase().trim().indexOf("win") >= 0&&!this.isRemote()) {//$NON-NLS-1$
return null;
}
String pPath = null;
try {
IRemoteProcessBuilder rpb = remoteServices.getProcessBuilder(conn);
if(envManager!=null){
String com="";
try {
com = envManager.createBashScript(null, false, envMgrConfig, "which "+toolname);
IFileStore envScript = fileManager.getResource(com);
IFileInfo envInfo=envScript.fetchInfo();
envInfo.setAttribute(EFS.ATTRIBUTE_OWNER_EXECUTE, true);
+ envInfo.setAttribute(EFS.ATTRIBUTE_EXECUTABLE, true);
envScript.putInfo(envInfo,EFS.SET_ATTRIBUTES,null);
} catch (RemoteConnectionException e) {
e.printStackTrace();
return null;
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rpb.command(com);
}
else{
rpb.command("which", toolname);//$NON-NLS-1$
}
// rpb.
IRemoteProcess p = rpb.start();
//Process p = new ProcessBuilder("which", toolname).start();//Runtime.getRuntime().exec("which "+toolname); //$NON-NLS-1$
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=null;//= reader.readLine();
while ((line=reader.readLine()) != null) {
//System.out.println(line);
IFileStore test =fileManager.getResource(line);
if(test.fetchInfo().exists())
{
pPath=line;
}
}
reader.close();
reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line=reader.readLine()) != null) {
//System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
if (pPath == null) {
return null;
}
IFileStore test = fileManager.getResource(pPath);
// File test = new File(pPath);
// IFileStore toolin = fileManager.getResource(toolname);
// File toolin = new File(toolname);
String name = test.fetchInfo().getName();
if (!name.equals(toolname)) {
return null;// TODO: Make sure this is the right behavior when the
}
// full path is provided
if (test.fetchInfo().exists()) {
return test.getParent().toURI().getPath();// pPath;//test.getParent().fetchInfo().getName();
// //.getParentFile().getPath();
} else {
return null;
}
}
/**
* Given a string as a starting point, this asks the user for the location of a tool's directory
* */
public String askToolPath(String archpath, String toolText, String toolMessage) {
// Shell
// ourshell=PlatformUI.getWorkbench().getDisplay().getActiveShell();
if (selshell == null) {
return null;
}
// DirectoryDialog dialog = new DirectoryDialog(selshell);
// dialog.setText(toolText);
// dialog.setMessage(toolMessage);
if (archpath != null) {
// File path = new File(archpath);
// IFileStore path = fileManager.getResource(archpath);////EFS.getLocalFileSystem().getStore(new Path(archpath));
// IFileInfo finf=path.fetchInfo();
// if (finf.exists()) {
// dialog.setFilterPath(!finf.isDirectory() ? archpath : path.getParent().toURI().getPath());
// }//TODO: We may actually want to use this initial directory checking
}
return fileManagerUI.browseDirectory(selshell, toolMessage, archpath, EFS.NONE);// dialog.open();
}
/**
* Given a tool's name, ask the user for the location of the tool
* */
public String askToolPath(String archpath, String toolName) {
return askToolPath(archpath, Messages.BuildLaunchUtils_Select + toolName + Messages.BuildLaunchUtils_BinDir,
Messages.BuildLaunchUtils_PleaseSelectDir + toolName + ""); //$NON-NLS-1$
}
/**
* Get the current timestamp
*
* @return A formatted representation of the current time
*/
public static String getNow() {
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
String DATE_FORMAT = "yyyy-MM-dd_HH:mm:ss"; //$NON-NLS-1$
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(cal.getTime());
}
/**
* Launches a command on the local system.
*
* @param tool
* The command to be run
* @param env
* A list of environment variables to associate with the tool
* @param directory
* The directory where the tool is invoked
*/
public boolean runTool(List<String> tool, Map<String, String> env, String directory) {
return runTool(tool, env, directory, null);
}
public IFileStore getFile(String path) {
return fileManager.getResource(path);
}
public boolean runTool(List<String> tool, Map<String, String> env, String directory, String output) {
int eval = -1;
try {
OutputStream fos = null;
if (output != null) {
IFileStore test = fileManager.getResource(output);
// File test = new File(output);
IFileStore parent = test.getParent();// fileManager.getResource
// File parent = test.getParentFile();
if (parent == null || !parent.fetchInfo().exists()) {
parent = fileManager.getResource(directory);
test = parent.getChild(output);
// output = directory + File.separator + output;
}
fos = test.openOutputStream(EFS.NONE, null);// test.openOutputStream(options, monitor)new FileOutputStream(test);
}
// IRemoteProcessBuilder pb = remoteServices.getProcessBuilder(conn, tool);//new IRemoteProcessBuilder(tool);
// pb.directory(fileManager.getResource(directory));
// if (env != null) {
// pb.environment().putAll(env);
// }
IRemoteProcess p = getProcess(tool, env, directory,false);// pb.start();// Runtime.getRuntime().exec(tool, env,
// directory);
StreamRunner outRun = new StreamRunner(p.getInputStream(), "out", fos); //$NON-NLS-1$
StreamRunner errRun = new StreamRunner(p.getErrorStream(), "err", null); //$NON-NLS-1$
outRun.start();
errRun.start();
outRun.join();
eval = p.waitFor();
if (fos != null) {
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return (eval == 0);// true;
}
public byte[] runToolGetOutput(List<String> tool, Map<String, String> env, String directory) {
return runToolGetOutput(tool,env,directory,false);
}
public byte[] runToolGetOutput(List<String> tool, Map<String, String> env, String directory,boolean showErr) {
int eval = -1;
byte[] out = null;
try {
ByteArrayOutputStream fos = new ByteArrayOutputStream();// null;
// if (output != null) {
// IFileStore test = fileManager.getResource(output);
// //File test = new File(output);
// IFileStore parent = test.getParent();//fileManager.getResource
// //File parent = test.getParentFile();
// if (parent == null || !parent.fetchInfo().exists()) {
// parent = fileManager.getResource(directory);
// test=parent.getChild(output);
// //output = directory + File.separator + output;
// }
// fos = test.openOutputStream(EFS.NONE, null);//test.openOutputStream(options, monitor)new FileOutputStream(test);
// }
IRemoteProcess p = getProcess(tool, env, directory,showErr);// pb.start();// Runtime.getRuntime().exec(tool, env,
// directory);
StreamRunner outRun = new StreamRunner(p.getInputStream(), "out", fos); //$NON-NLS-1$
StreamRunner errRun =null;
errRun = new StreamRunner(p.getErrorStream(), "err", null); //$NON-NLS-1$
outRun.start();
errRun.start();
outRun.join();
eval = p.waitFor();
if (fos != null) {
fos.flush();
out = fos.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (eval != 0) {
return null;
}
return out;
}
private IRemoteProcess getProcess(List<String> tool, Map<String, String> env, String directory,boolean mergeOutput) throws IOException {
IRemoteProcessBuilder pb;
if(envManager!=null){
String com="";
String concat="";
try {
concat="";
for(int i=0;i<tool.size();i++){
concat+=" "+tool.get(i);
}
com = envManager.createBashScript(null, false, envMgrConfig, concat);
IFileStore envScript = fileManager.getResource(com);
IFileInfo envInfo=envScript.fetchInfo();
envInfo.setAttribute(EFS.ATTRIBUTE_OWNER_EXECUTE, true);
envScript.putInfo(envInfo,EFS.SET_ATTRIBUTES,null);
} catch (RemoteConnectionException e) {
e.printStackTrace();
return null;
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pb = remoteServices.getProcessBuilder(conn, concat);
}
else{
pb = remoteServices.getProcessBuilder(conn, tool);// new IRemoteProcessBuilder(tool);
}
if (directory != null) {
pb.directory(fileManager.getResource(directory));
}
if (env != null) {
pb.environment().putAll(env);
}
pb.redirectErrorStream(mergeOutput);
return pb.start();
}
public void runVis(List<String> tool, Map<String, String> env, String directory) {
// int eval = -1;
try {
//
// IRemoteProcessBuilder pb = remoteServices.getProcessBuilder(conn, tool);//new IRemoteProcessBuilder(tool);
// pb.directory(fileManager.getResource(directory));
// if (env != null) {
// pb.environment().putAll(env);
// }
//
// //Process p =
// pb.start();
if(env==null)
env=new HashMap<String,String>();
if(env.get("DISPLAY")==null)
env.put("DISPLAY", ":0.0");
getProcess(tool, env, directory,false);
} catch (Exception e) {
e.printStackTrace();
// return false;
}
// return (eval == 0);// true;
}
static class StreamRunner extends Thread {
InputStream is;
OutputStream os;
String type;
StreamRunner(InputStream is, String type, OutputStream os) {
this.is = is;
this.os = os;
this.type = type;
}
@Override
public void run() {
try {
PrintWriter pw = null;
if (os != null) {
pw = new PrintWriter(os);
}
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (pw != null) {
pw.println(line);
} else {
System.out.println(line);
}
}
if (pw != null) {
pw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public boolean isRemote() {
return true;
}
}
| false | true | public String checkToolEnvPath(String toolname) {
if (org.eclipse.cdt.utils.Platform.getOS().toLowerCase().trim().indexOf("win") >= 0) {//$NON-NLS-1$
return null;
}
String pPath = null;
try {
IRemoteProcessBuilder rpb = remoteServices.getProcessBuilder(conn);
if(envManager!=null){
String com="";
try {
com = envManager.createBashScript(null, false, envMgrConfig, "which "+toolname);
IFileStore envScript = fileManager.getResource(com);
IFileInfo envInfo=envScript.fetchInfo();
envInfo.setAttribute(EFS.ATTRIBUTE_OWNER_EXECUTE, true);
envScript.putInfo(envInfo,EFS.SET_ATTRIBUTES,null);
} catch (RemoteConnectionException e) {
e.printStackTrace();
return null;
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rpb.command(com);
}
else{
rpb.command("which", toolname);//$NON-NLS-1$
}
// rpb.
IRemoteProcess p = rpb.start();
//Process p = new ProcessBuilder("which", toolname).start();//Runtime.getRuntime().exec("which "+toolname); //$NON-NLS-1$
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=null;//= reader.readLine();
while ((line=reader.readLine()) != null) {
//System.out.println(line);
IFileStore test =fileManager.getResource(line);
if(test.fetchInfo().exists())
{
pPath=line;
}
}
reader.close();
reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line=reader.readLine()) != null) {
//System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
if (pPath == null) {
return null;
}
IFileStore test = fileManager.getResource(pPath);
// File test = new File(pPath);
// IFileStore toolin = fileManager.getResource(toolname);
// File toolin = new File(toolname);
String name = test.fetchInfo().getName();
if (!name.equals(toolname)) {
return null;// TODO: Make sure this is the right behavior when the
}
// full path is provided
if (test.fetchInfo().exists()) {
return test.getParent().toURI().getPath();// pPath;//test.getParent().fetchInfo().getName();
// //.getParentFile().getPath();
} else {
return null;
}
}
| public String checkToolEnvPath(String toolname) {
if (org.eclipse.cdt.utils.Platform.getOS().toLowerCase().trim().indexOf("win") >= 0&&!this.isRemote()) {//$NON-NLS-1$
return null;
}
String pPath = null;
try {
IRemoteProcessBuilder rpb = remoteServices.getProcessBuilder(conn);
if(envManager!=null){
String com="";
try {
com = envManager.createBashScript(null, false, envMgrConfig, "which "+toolname);
IFileStore envScript = fileManager.getResource(com);
IFileInfo envInfo=envScript.fetchInfo();
envInfo.setAttribute(EFS.ATTRIBUTE_OWNER_EXECUTE, true);
envInfo.setAttribute(EFS.ATTRIBUTE_EXECUTABLE, true);
envScript.putInfo(envInfo,EFS.SET_ATTRIBUTES,null);
} catch (RemoteConnectionException e) {
e.printStackTrace();
return null;
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rpb.command(com);
}
else{
rpb.command("which", toolname);//$NON-NLS-1$
}
// rpb.
IRemoteProcess p = rpb.start();
//Process p = new ProcessBuilder("which", toolname).start();//Runtime.getRuntime().exec("which "+toolname); //$NON-NLS-1$
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=null;//= reader.readLine();
while ((line=reader.readLine()) != null) {
//System.out.println(line);
IFileStore test =fileManager.getResource(line);
if(test.fetchInfo().exists())
{
pPath=line;
}
}
reader.close();
reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line=reader.readLine()) != null) {
//System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
if (pPath == null) {
return null;
}
IFileStore test = fileManager.getResource(pPath);
// File test = new File(pPath);
// IFileStore toolin = fileManager.getResource(toolname);
// File toolin = new File(toolname);
String name = test.fetchInfo().getName();
if (!name.equals(toolname)) {
return null;// TODO: Make sure this is the right behavior when the
}
// full path is provided
if (test.fetchInfo().exists()) {
return test.getParent().toURI().getPath();// pPath;//test.getParent().fetchInfo().getName();
// //.getParentFile().getPath();
} else {
return null;
}
}
|
diff --git a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/VariableClasspathResolver.java b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/VariableClasspathResolver.java
index e5e2bad9d..64385d0bc 100644
--- a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/VariableClasspathResolver.java
+++ b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/VariableClasspathResolver.java
@@ -1,57 +1,57 @@
/*******************************************************************************
* 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.launching;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.variables.VariablesPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.IRuntimeClasspathEntryResolver;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
public class VariableClasspathResolver implements IRuntimeClasspathEntryResolver {
/* (non-Javadoc)
* @see org.eclipse.jdt.launching.IRuntimeClasspathEntryResolver#resolveRuntimeClasspathEntry(org.eclipse.jdt.launching.IRuntimeClasspathEntry, org.eclipse.debug.core.ILaunchConfiguration)
*/
public IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry(IRuntimeClasspathEntry entry, ILaunchConfiguration configuration) throws CoreException {
return resolveRuntimeClasspathEntry(entry);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.launching.IRuntimeClasspathEntryResolver#resolveRuntimeClasspathEntry(org.eclipse.jdt.launching.IRuntimeClasspathEntry, org.eclipse.jdt.core.IJavaProject)
*/
public IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry(IRuntimeClasspathEntry entry, IJavaProject project) throws CoreException {
return resolveRuntimeClasspathEntry(entry);
}
private IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry(IRuntimeClasspathEntry entry) throws CoreException{
String variableString = ((VariableClasspathEntry)entry).getVariableString();
String strpath = VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(variableString);
- IPath path = new Path(strpath);
+ IPath path = new Path(strpath).makeAbsolute();
IRuntimeClasspathEntry archiveEntry = JavaRuntime.newArchiveRuntimeClasspathEntry(path);
return new IRuntimeClasspathEntry[] { archiveEntry };
}
/* (non-Javadoc)
* @see org.eclipse.jdt.launching.IRuntimeClasspathEntryResolver#resolveVMInstall(org.eclipse.jdt.core.IClasspathEntry)
*/
public IVMInstall resolveVMInstall(IClasspathEntry entry) throws CoreException {
return null;
}
}
| true | true | private IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry(IRuntimeClasspathEntry entry) throws CoreException{
String variableString = ((VariableClasspathEntry)entry).getVariableString();
String strpath = VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(variableString);
IPath path = new Path(strpath);
IRuntimeClasspathEntry archiveEntry = JavaRuntime.newArchiveRuntimeClasspathEntry(path);
return new IRuntimeClasspathEntry[] { archiveEntry };
}
| private IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry(IRuntimeClasspathEntry entry) throws CoreException{
String variableString = ((VariableClasspathEntry)entry).getVariableString();
String strpath = VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(variableString);
IPath path = new Path(strpath).makeAbsolute();
IRuntimeClasspathEntry archiveEntry = JavaRuntime.newArchiveRuntimeClasspathEntry(path);
return new IRuntimeClasspathEntry[] { archiveEntry };
}
|
diff --git a/org.eclipse.riena.tests/src/org/eclipse/riena/ui/swt/CompletionComboTest.java b/org.eclipse.riena.tests/src/org/eclipse/riena/ui/swt/CompletionComboTest.java
index f7971fa6d..102c77907 100644
--- a/org.eclipse.riena.tests/src/org/eclipse/riena/ui/swt/CompletionComboTest.java
+++ b/org.eclipse.riena.tests/src/org/eclipse/riena/ui/swt/CompletionComboTest.java
@@ -1,153 +1,153 @@
/*******************************************************************************
* Copyright (c) 2007, 2011 compeople AG 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:
* compeople AG - initial API and implementation
*******************************************************************************/
package org.eclipse.riena.ui.swt;
import junit.framework.TestCase;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.riena.core.util.ReflectionUtils;
import org.eclipse.riena.internal.core.test.collect.UITestCase;
import org.eclipse.riena.ui.swt.CompletionCombo.AutoCompletionMode;
import org.eclipse.riena.ui.swt.utils.SwtUtilities;
import org.eclipse.riena.ui.swt.utils.UIControlsFactory;
/**
* Tests of the class {@link CompletionCombo}.
*/
@UITestCase
public class CompletionComboTest extends TestCase {
private Shell shell;
private CompletionCombo combo;
private Text text;
@Override
protected void setUp() throws Exception {
super.setUp();
shell = new Shell();
shell.setLayout(new RowLayout());
shell.setBounds(0, 0, 200, 200);
combo = UIControlsFactory.createCompletionCombo(shell, SWT.NONE);
text = UIControlsFactory.createText(shell, SWT.BORDER);
}
@Override
protected void tearDown() throws Exception {
SwtUtilities.dispose(shell);
}
// testing methods
//////////////////
public void testSetBackground() {
final Color red = combo.getDisplay().getSystemColor(SWT.COLOR_RED);
combo.setBackground(red);
assertEquals(red, combo.getBackground());
assertEquals(red, combo.getTextBackground());
assertEquals(red, combo.getListBackground());
}
public void testSetTextBackground() {
final Color red = combo.getDisplay().getSystemColor(SWT.COLOR_RED);
final Color green = combo.getDisplay().getSystemColor(SWT.COLOR_GREEN);
combo.setBackground(red);
combo.setTextBackground(green);
assertEquals(red, combo.getBackground());
assertEquals(green, combo.getTextBackground());
assertEquals(red, combo.getListBackground());
}
public void testSetListBackground() {
final Color red = combo.getDisplay().getSystemColor(SWT.COLOR_RED);
final Color green = combo.getDisplay().getSystemColor(SWT.COLOR_GREEN);
final Color blue = combo.getDisplay().getSystemColor(SWT.COLOR_GREEN);
combo.setBackground(red);
combo.setTextBackground(green);
combo.setListBackground(blue);
assertEquals(red, combo.getBackground());
assertEquals(green, combo.getTextBackground());
assertEquals(blue, combo.getListBackground());
}
/**
* As per bug 318301
*/
public void testGetChildren() {
final Control[] children = combo.getChildren();
assertEquals(2, children.length);
assertTrue(children[0] instanceof Text);
assertTrue(children[1] instanceof Button);
}
public void testArrowButtonEnabled() {
shell.setEnabled(false);
combo.setEnabled(false);
combo.setEnabled(true);
combo.setEditable(true);
shell.setEnabled(true);
assertTrue(combo.isEnabled());
final Text textControl = ReflectionUtils.invokeHidden(combo, "getTextControl");
assertTrue(textControl.isEnabled());
final Button buttonControl = ReflectionUtils.invokeHidden(combo, "getButtonControl");
assertTrue(buttonControl.isEnabled());
}
/**
* Tests the method {@code setFocus()}.
*/
public void testSetFocus() {
shell.open();
text.setFocus();
assertTrue(text.isFocusControl());
text.setFocus();
combo.setAutoCompletionMode(AutoCompletionMode.ALLOW_MISSMATCH);
combo.setFocus();
- assertTrue(combo.getTextControl().isFocusControl());
+ assertTrue(((Text) ReflectionUtils.invokeHidden(combo, "getTextControl")).isFocusControl());
text.setFocus();
combo.setAutoCompletionMode(AutoCompletionMode.FIRST_LETTER_MATCH);
combo.setFocus();
- assertTrue(combo.getTextControl().isFocusControl());
+ assertTrue(((Text) ReflectionUtils.invokeHidden(combo, "getTextControl")).isFocusControl());
text.setFocus();
combo.setAutoCompletionMode(AutoCompletionMode.NO_MISSMATCH);
combo.setFocus();
- assertTrue(combo.getTextControl().isFocusControl());
+ assertTrue(((Text) ReflectionUtils.invokeHidden(combo, "getTextControl")).isFocusControl());
text.setFocus();
combo.setEnabled(false);
combo.setFocus();
- assertFalse(combo.getTextControl().isFocusControl());
+ assertFalse(((Text) ReflectionUtils.invokeHidden(combo, "getTextControl")).isFocusControl());
text.setFocus();
combo.setEnabled(true);
combo.setVisible(false);
combo.setFocus();
- assertFalse(combo.getTextControl().isFocusControl());
+ assertFalse(((Text) ReflectionUtils.invokeHidden(combo, "getTextControl")).isFocusControl());
}
}
| false | true | public void testSetFocus() {
shell.open();
text.setFocus();
assertTrue(text.isFocusControl());
text.setFocus();
combo.setAutoCompletionMode(AutoCompletionMode.ALLOW_MISSMATCH);
combo.setFocus();
assertTrue(combo.getTextControl().isFocusControl());
text.setFocus();
combo.setAutoCompletionMode(AutoCompletionMode.FIRST_LETTER_MATCH);
combo.setFocus();
assertTrue(combo.getTextControl().isFocusControl());
text.setFocus();
combo.setAutoCompletionMode(AutoCompletionMode.NO_MISSMATCH);
combo.setFocus();
assertTrue(combo.getTextControl().isFocusControl());
text.setFocus();
combo.setEnabled(false);
combo.setFocus();
assertFalse(combo.getTextControl().isFocusControl());
text.setFocus();
combo.setEnabled(true);
combo.setVisible(false);
combo.setFocus();
assertFalse(combo.getTextControl().isFocusControl());
}
| public void testSetFocus() {
shell.open();
text.setFocus();
assertTrue(text.isFocusControl());
text.setFocus();
combo.setAutoCompletionMode(AutoCompletionMode.ALLOW_MISSMATCH);
combo.setFocus();
assertTrue(((Text) ReflectionUtils.invokeHidden(combo, "getTextControl")).isFocusControl());
text.setFocus();
combo.setAutoCompletionMode(AutoCompletionMode.FIRST_LETTER_MATCH);
combo.setFocus();
assertTrue(((Text) ReflectionUtils.invokeHidden(combo, "getTextControl")).isFocusControl());
text.setFocus();
combo.setAutoCompletionMode(AutoCompletionMode.NO_MISSMATCH);
combo.setFocus();
assertTrue(((Text) ReflectionUtils.invokeHidden(combo, "getTextControl")).isFocusControl());
text.setFocus();
combo.setEnabled(false);
combo.setFocus();
assertFalse(((Text) ReflectionUtils.invokeHidden(combo, "getTextControl")).isFocusControl());
text.setFocus();
combo.setEnabled(true);
combo.setVisible(false);
combo.setFocus();
assertFalse(((Text) ReflectionUtils.invokeHidden(combo, "getTextControl")).isFocusControl());
}
|
diff --git a/Lilian/src/main/java/org/lilian/data/real/fractal/random/RIFSEM.java b/Lilian/src/main/java/org/lilian/data/real/fractal/random/RIFSEM.java
index cbdcc9c..7f439ea 100644
--- a/Lilian/src/main/java/org/lilian/data/real/fractal/random/RIFSEM.java
+++ b/Lilian/src/main/java/org/lilian/data/real/fractal/random/RIFSEM.java
@@ -1,1061 +1,1065 @@
package org.lilian.data.real.fractal.random;
import static org.lilian.util.Functions.log2;
import static org.lilian.util.Functions.tic;
import static org.lilian.util.Functions.toc;
import static org.lilian.util.Series.series;
import static org.lilian.data.real.fractal.random.DiscreteRIFS.Codon;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.lilian.Global;
import org.lilian.data.real.Datasets;
import org.lilian.data.real.Density;
import org.lilian.data.real.KernelDensity;
import org.lilian.data.real.MVN;
import org.lilian.data.real.Point;
import org.lilian.data.real.Similitude;
import org.lilian.data.real.fractal.IFS;
import org.lilian.data.real.weighted.Weighted;
import org.lilian.data.real.weighted.WeightedLists;
import org.lilian.models.BasicFrequencyModel;
import org.lilian.search.Builder;
import org.lilian.search.Parameters;
import org.lilian.util.Functions;
import org.lilian.util.Series;
import org.lilian.util.distance.Distance;
import org.lilian.util.distance.EuclideanDistance;
import org.lilian.util.distance.HausdorffDistance;
import org.lilian.util.graphs.old.Stochastic;
/**
*
* TODO:
* - Use data as basis.
* @author Peter
*
*/
public class RIFSEM
{
private static double KERNEL_VAR = 0.5;
private static Distance<List<Point>> hausdorffDistance =
new HausdorffDistance<Point>(new EuclideanDistance());
private static boolean useSphericalMVN = false;
private static final int COVARIANCE_THRESHOLD = 5;
// * If a code has fewer than this number of points, it is not
// used in reconstructing the choice tree
private static final int TREE_POINTS_THRESHOLD = 10;
private List<List<Point>> data;
private List<List<Point>> dataSample;
// * The three main components of an EM iteration
private DiscreteRIFS<Similitude> model;
private List<SChoiceTree> trees;
// * A code tree for each dataset. This list holds the root nodes.
private List<Node> codeTrees;
private int compPerIFS, depth, sampleSize, numSources;
private double spanningPointsVariance, perturbVar;
private Builder<Similitude> builder;
private Builder<IFS<Similitude>> ifsBuilder;
/**
*
* @param initial Model consisting of IFSs with equal size.
* @param data
* @param depth
* @param sampleSize
* @param numSources How many points claim responsibility for a given code
*/
public RIFSEM(
DiscreteRIFS<Similitude> initial,
List<List<Point>> data, int depth, int sampleSize,
double spanningPointsVariance, double perturbVar, int numSources)
{
this.model = initial;
this.data = data;
this.depth = depth;
this.sampleSize = sampleSize;
this.spanningPointsVariance = spanningPointsVariance;
this.compPerIFS = model.models().get(0).size();
this.numSources = numSources;
// * Check that all component IFSs of model have the same size
for(IFS<Similitude> ifs : model.models())
if(ifs.size() != compPerIFS)
throw new IllegalArgumentException("All component IFSs of the initial model should have the same number of component transformations.");
dataSample = new ArrayList<List<Point>>(data.size());
codeTrees = new ArrayList<Node>();
for(int i : series(dataSample.size()))
codeTrees.add(new Node(null, null));
resample();
// * Add trees
trees = new ArrayList<SChoiceTree>(data.size());
for(int i : Series.series(dataSample.size()))
trees.add(new SChoiceTree(compPerIFS, model.size(), depth));
findCodes();
builder = Similitude.similitudeBuilder(model.dimension());
ifsBuilder = IFS.builder(compPerIFS, builder);
}
// public RIFSEM(DiscreteRIFS<Similitude> initial, List<List<Point>> data,
// List<ChoiceTree> dataTrees, int depth, int sampleSize, double spanningPointsVariance, double perturbVar)
// {
// this(initial, data, depth, sampleSize, spanningPointsVariance, perturbVar);
// this.trees = dataTrees;
// }
public void iteration()
{
resample();
tic();
findCodes();
Global.log().info("Finished finding codes. " + toc() + " seconds.");
tic();
findTrees();
Global.log().info("Finished finding trees. " + toc() + " seconds.");
for(SChoiceTree tree : trees)
System.out.println(tree);
tic();
findModel();
Global.log().info("Finished finding model. " + toc() + " seconds.");
}
public DiscreteRIFS<Similitude> model()
{
return model;
}
/**
* Finds a new Model given the current codes and sequences.
*/
public void findModel()
{
// * Look for matching codes in the code tree
Maps maps = findMaps();
// * Frequency model for all component IFSs
BasicFrequencyModel<Integer> freqs = new BasicFrequencyModel<Integer>();
for(SChoiceTree tree : trees)
tree.count(freqs);
// * Models and weights
List<IFS<Similitude>> modelComponents = new ArrayList<IFS<Similitude>>(model.size());
List<Double> modelWeights = new ArrayList<Double>(model.size());
// * Initialize empty
for (int i : Series.series(model.size()))
modelComponents.add(null);
for (int i : Series.series(model.size()))
modelWeights.add(-1.0);
// * Keep check of components which were unassigned
List<Integer> modelAssigned = new ArrayList<Integer>(model.size());
List<Integer> modelUnassigned = new ArrayList<Integer>(model.size());
for(int h : series(model.size()))
{
IFS<Similitude> component = model.models().get(h);
int numComponents = component.size();
// * Initialize empty trans and weights list
List<Similitude> trans = new ArrayList<Similitude>(numComponents);
for (int i : Series.series(numComponents))
trans.add(null);
List<Double> weights = new ArrayList<Double>(numComponents);
for (int i : Series.series(numComponents))
weights.add(1.0 / numComponents);
// * Keep check of components which were unassigned
List<Integer> assigned = new ArrayList<Integer>(numComponents);
List<Integer> unassigned = new ArrayList<Integer>(numComponents);
for (int i : series(numComponents))
{
Codon c = new Codon(h, i);
int n = maps.size(c);
if (n != 0) // codes found containing this comp
{
// * Find the map for the point pairs
Similitude map = findMap(maps.from(c), maps.to(c), component.get(i));
// * Find the weight for the frequency pairs
double weight = findScalar(maps.fromWeights(c),
maps.toWeights(c));
trans.set(i, map);
weights.set(i, weight);
assigned.add(i);
} else
{ // No codes found with this component
unassigned.add(i);
}
}
if(! unassigned.isEmpty())
Global.log().info("unassigned: " + unassigned);
if (assigned.isEmpty())
+ {
modelUnassigned.add(h);
- else
+ continue;
+ } else
+ {
modelAssigned.add(h);
+ }
// * For each unassigned IFS component, take a random assigned component and
// perturb it slightly.
for (int i : unassigned)
{
int j = assigned.get(Global.random.nextInt(assigned.size()));
Similitude source = trans.get(j);
double sourceWeight = weights.get(j);
Similitude perturbed0 = Parameters.perturb(source, builder, perturbVar);
Similitude perturbed1 = Parameters.perturb(source, builder, perturbVar);
trans.set(i, perturbed0);
trans.set(j, perturbed1);
weights.set(i, sourceWeight / 2.0);
weights.set(j, sourceWeight / 2.0);
}
component = new IFS<Similitude>(trans.get(0), weights.get(0));
for (int i : series(1, numComponents))
component.addMap(trans.get(i), weights.get(i));
double ifsPrior = freqs.probability(h);
modelComponents.set(h, component);
modelWeights.set(h, ifsPrior);
}
// * For each unassigned model component, take a random assigned component and
// perturb it slightly.
for (int h : modelUnassigned)
{
int j = modelAssigned.get(Global.random.nextInt(modelAssigned.size()));
IFS<Similitude> source = modelComponents.get(j);
double sourceWeight = modelWeights.get(j);
IFS<Similitude> perturbed0 = Parameters.perturb(source, ifsBuilder, perturbVar);
IFS<Similitude> perturbed1 = Parameters.perturb(source, ifsBuilder, perturbVar);
modelComponents.set(h, perturbed0);
modelComponents.set(j, perturbed1);
modelWeights.set(h, sourceWeight / 2.0);
modelWeights.set(j, sourceWeight / 2.0);
}
model = null;
for(int h : series(modelComponents.size()))
if(model == null)
model = new DiscreteRIFS<Similitude>(modelComponents.get(h), modelWeights.get(h));
else
model.addModel(modelComponents.get(h), modelWeights.get(h));
}
/**
* Resample the sampled datasets.
*
* @param sampleSize The number of points to sample per dataset.
*/
public void resample()
{
dataSample.clear();
for(List<Point> points : data)
dataSample.add(Datasets.sample(points, sampleSize));
}
/**
* Finds a new coding given the current model and sequences.
*/
public void findCodes()
{
codeTrees.clear();
for(int i : Series.series(dataSample.size()))
{
List<Point> points = dataSample.get(i);
SChoiceTree tree = trees.get(i);
Node root = new Node(null, null);
codeTrees.add(root);
for(Point point : points)
{
SearchStochastic.SearchResult result =
SearchStochastic.search(model, tree, point, new MVN(data.get(0).get(0).dimensionality()), numSources);
Weighted<List<Codon>> codes = result.codes();
for(int j : Series.series(codes.size()))
root.observe(codes.get(j), point, codes.weight(j));
}
}
// for(int j : series(20))
//
// System.out.println(codeTree.random().code());
}
/**
* Finds new ChoiceTrees given the current model and coding
*/
public void findTrees()
{
trees.clear();
for(int i : series(data.size()))
{
// * We start with a random tree, and add the choices we can figure
// out from the data.
SChoiceTree tree = new SChoiceTree(compPerIFS, model.size(), depth);
codeTrees.get(i).build(tree);
trees.add(tree);
// System.out.println(tree);
}
}
/**
*
* @return A list of maps so that Maps i in the list represents the
* maps for component IFS i.
*/
private Maps findMaps()
{
Maps maps = new Maps();
// * Collect all observed codes
Set<List<Codon>> allCodes = new LinkedHashSet<List<Codon>>();
for(Node root : codeTrees)
root.collectCodes(allCodes);
// * For each observed code ...
for (List<Codon> toCode : allCodes)
{
if(toCode.size() < 1)
continue;
// * find the pre-code (the code for the points that are mapped to this
// code by its first symbol.
List<Codon> fromCode = new ArrayList<Codon>(toCode);
Codon codon = fromCode.remove(0);
// * Collect the to and from set for each code
List<Point> to = new ArrayList<Point>(),
from = new ArrayList<Point>();
for(Node root : codeTrees)
{
to.addAll(root.points(toCode));
from.addAll(root.points(fromCode));
}
int m = Math.min(to.size(), from.size());
MVN toMVN = mvn(to), fromMVN = mvn(from);
if (fromMVN != null & toMVN != null)
{
if (m < COVARIANCE_THRESHOLD) // Not enough points to
// consider covariance
{
for (int i : series(from.size()))
maps.add(codon, fromMVN.mean(), toMVN.mean());
} else
{
// * Consider the covariance by taking not just the
// means,
// but points close to zero mapped to both
// distributions
// We generate as many points as are in the to node.
// (for depth one a handful would suffice, but for
// higher values the amount of points generated gives
// a sort of weight to this match in the codes among
// the other points)
List<Point> points =
new MVN(model.dimension(), spanningPointsVariance)
.generate(from.size());
List<Point> pf = fromMVN.map().map(points);
List<Point> pt = toMVN.map().map(points);
for (int i = 0; i < points.size(); i++)
maps.add(codon, pf.get(i), pt.get(i));
}
} else
{
// Global.log().info("Points for code " + code +
// " formed deficient MVN. No points added to pairs.");
}
// * Register the drop in frequency as the symbol t gets added
// to the code
maps.weight(codon, from.size(), to.size());
}
Global.log().info("Maps found.");
return maps;
}
private MVN mvn(List<Point> points)
{
try
{
return useSphericalMVN ? MVN.findSpherical(points) :
MVN.find(points);
} catch (RuntimeException e)
{
// * Could not find proper MVN model
return null;
}
}
/**
* A node in the code tree. Each code represents a path in this tree from
* root to leaf. At each node, we store each point whose path visits that
* node. (ie. the root node contains all points, and each node below the
* root contains all points whose code starts with a given symbol).
*
* The Node object also contains the search algorithm for matching codes.
*/
protected class Node implements Serializable
{
private static final long serialVersionUID = -6512700670917962320L;
// * An MVN fitted to the point stored in this node
MVN mvn = null;
// * The parent in the tree
Node parent;
// * The child nodes for each symbol (represented by an Integer)
Map<Codon, Node> children;
// * How deep this node is in the tree
int depth = 0;
// * This node's code
List<Codon> code;
// * Whether this node represents a leaf node
boolean isLeaf = false;
// * The points stored at this node
Weighted<Point> points = WeightedLists.empty();
/**
* Create a child node for the given symbol under this parent
*
* @param symbol
* @param parent
*/
public Node(Codon symbol, Node parent)
{
this.parent = parent;
code = new ArrayList<Codon>(
parent != null ? parent.code().size() + 1 : 1);
if (parent != null)
code.addAll(parent.code());
if (symbol != null)
code.add(symbol);
if (parent != null)
depth = parent.depth + 1;
children = new HashMap<Codon, Node>();
}
/**
* Add the symbols of this node and the subtree below it to the given
* frequency model.
*
* @param model
*/
public void count(BasicFrequencyModel<Codon> model)
{
if (!isRoot())
model.add(symbol());
for (Codon i : children.keySet())
children.get(i).count(model);
}
/**
* Add the symbols of this node and the subtree below it to the given
* frequency model.
*
* @param model
*/
public void countIFS(BasicFrequencyModel<Integer> model)
{
if (!isRoot())
model.add(symbol().ifs());
for (Codon i : children.keySet())
children.get(i).countIFS(model);
}
/**
* Returns whether this node is the root node of the tree.
*
* @return
*/
public boolean isRoot()
{
return parent == null;
}
/**
* How far from the root this tree is.
*
* @return
*/
public int depth()
{
return depth;
}
/**
* The code represented by this node
*/
public List<Codon> code()
{
return code;
}
/**
* The symbol for this node (ie. the last symbol in its code).
*
* @return
*/
public Codon symbol()
{
return code.get(code.size() - 1);
}
/**
* Store the given point at this node, and pass it on to the correct
* child.
*
* @param codeSuffix
* The suffix of the code after this node
* @param point
* The point to be observed.
*/
public void observe(List<Codon> codeSuffix, Point point)
{
observe(codeSuffix, point, 1.0);
}
public void observe(List<Codon> codeSuffix, Point point, double weight)
{
// if(parent == null)
// System.out.println(codeSuffix);
//
points.add(point, weight);
mvn = null; // signal that the mvn needs to be recomputed
if (codeSuffix.size() == 0)
{
isLeaf = true;
return;
}
Codon symbol = codeSuffix.get(0);
if (!children.containsKey(symbol))
children.put(symbol, new Node(symbol, this));
children.get(symbol).observe(
codeSuffix.subList(1, codeSuffix.size()), point);
}
/**
* The points stored at this node
*
* @return
*/
public List<Point> points()
{
return points;
}
/**
* Returns the points associated with the node at the given code-suffix
* (ie. the path from this node).
*
* @param code
* @return
*/
public List<Point> points(List<Codon> code)
{
if (code.isEmpty())
return points();
Codon head = code.get(0);
if(! children.containsKey(head))
return Collections.emptyList();
return children.get(head).points(code.subList(1, code.size()));
}
/**
* Add all codes at and below this node to the given collection
* @param codes
*/
public void collectCodes(Collection<List<Codon>> codes)
{
codes.add(code());
for(Node child : children.values())
child.collectCodes(codes);
}
/**
* The number of times this node was visited (ie. the number of points
* stored here)
*/
public double frequency()
{
return points.size();
}
/**
* @return Whether this node is a leaf node in the tree. A node is a
* leaf if it is at the set maximum depth for this iteration of
* the EM algorithm. It may be that is has no children yet but
* they will be created by the observation of a future code.
*/
public boolean isLeaf()
{
return isLeaf;
}
/**
* A multivariate normal distribution fitted to the points stored at
* this node
*
* Note: returns null if the points for this code form a deficient mvn
* model.
*
* @return
*/
public MVN mvn()
{
if (mvn == null)
try
{
mvn = useSphericalMVN ? MVN.findSpherical(points) :
MVN.find(points);
} catch (RuntimeException e)
{
// * Could not find proper MVN model
return null;
}
return mvn;
}
/**
* Print a lengthy (multiline) representation of this node to the given
* outputstream
*
* @param out
* @param indent
* The number of tabs to indent with
*/
public void print(PrintStream out, int indent)
{
String ind = "";
for (int i : series(indent))
ind += "\t";
String code = "";
for (Codon codon : code())
code += codon + " ";
out.println(ind + code + " f:" + frequency() + ", p: ...");
for (Codon symbol : children.keySet())
children.get(symbol).print(out, indent + 1);
}
/**
* Returns the node for the given code (suffix) (starting from this
* node).
*
* @param code
* The code suffix for which to find the node starting from
* the current node.
* @return the requested Node if it exists. null otherwise.
*/
public Node find(List<Codon> code)
{
if (code.size() == 0)
return this;
Codon symbol = code.get(0);
if (! children.containsKey(symbol))
return null;
return children.get(symbol).find(code.subList(1, code.size()));
}
public void build(SChoiceTree tree)
{
if(children == null || children.size() == 0)
return;
if(points().size() < TREE_POINTS_THRESHOLD)
return;
// * Find the best IFS for this node
// * We calculate the score of an IFS by fitting an MVN to the points
// of this node, mapping it by each component transformation, and
// taking the log probability of the points of the matching node.
int best = -1;
double bestScore = Double.NEGATIVE_INFINITY;
List<Double> probs = new ArrayList<Double>(model.size());
for(int i : series(model.size()))
probs.add(Double.NaN);
for(int i : series(model.size()))
{
IFS<Similitude> component = model.models().get(i);
double logIFSPrior = log2(model.probability(i));
double score = logIFSPrior;
// MVN mvn = mvn();
List<Point> from = points();
// System.out.println(code() + " " + points() + " " + mvn);
for(int j : series(component.size()))
{
// System.out.println(j);
// MVN mapped = mvn.transform(component.get(j));
List<Point> mapped = component.get(j).map(from);
Density density = new KernelDensity(mapped, KERNEL_VAR);
// * Retrieve all points from children with map component j
List<Point> to = new ArrayList<Point>();
for(int k : series(model.size()))
{
Codon codon = new Codon(k, j);
if(children.containsKey(codon))
to.addAll(children.get(codon).points());
}
if(to.isEmpty())
continue;
// score += hausdorffDistance.distance(mapped, to);
for(Point point : to)
score += log2(density.density(point));
}
probs.set(i, score);
if(score >= bestScore)
{
bestScore = score;
best = i;
}
}
// System.out.println(depth() + " " + best + " " + bestScore + " " + probs);
// * Submit to the choice tree
if(best != -1)
{
SChoiceTree.Node node = tree.get(mapCode(code()));
node.clear();
for(int i : Series.series(probs.size()))
{
if(! Double.isNaN(probs.get(i)))
node.set(i, probs.get(i));
}
}
// * Recurse
for(Node child : children.values())
child.build(tree);
}
public String toString()
{
String code = depth() + ") ";
for (Codon c : code())
code += c;
return code;
}
public Node random()
{
if(children.size() == 0)
return this;
List<Codon> keys = new ArrayList<Codon>(children.keySet());
Codon k = keys.get(Global.random.nextInt(keys.size()));
return children.get(k).random();
}
}
/**
* Helper class for storing paired points and paired frequencies for each
* component map of a given IFS
*/
protected class Maps
{
// * The inner list stores all 'from' points. We store one such list for
// each component
private Map<Codon, List<Point>> from = new HashMap<Codon, List<Point>>();
// * The inner list stores all 'to' points. We store one such list for
// each component
private Map<Codon, List<Point>> to = new HashMap<Codon, List<Point>>();
// * The same but for the weights (inner lists store frequencies)
private Map<Codon, List<Double>> fromWeights = new HashMap<Codon, List<Double>>();
private Map<Codon, List<Double>> toWeights = new HashMap<Codon, List<Double>>();
/**
* The number of point pairs stored for a given component
*
* @param i
* The component index
* @return The number of point pairs stored for component i
*/
public int size(Codon c)
{
ensure(c);
return from.get(c).size();
}
/**
* Add a point pair to a given component
*
* @param component
* The component that maps from the first to the second point
* @param from
* The from point
* @param to
* The to point
*/
public void add(Codon component, Point from, Point to)
{
ensure(component);
this.from.get(component).add(from);
this.to.get(component).add(to);
}
/**
* Add a frequency pair to a given component
*
* @param component
* The component that maps from the first to the second
* frequency
* @param from
* The from frequency
* @param to
* The to frequency
*/
public void weight(Codon component, double from, double to)
{
ensure(component);
this.fromWeights.get(component).add(from);
this.toWeights.get(component).add(to);
}
/**
* Ensure that lists exist for the given component (and below)
*/
private void ensure(Codon codon)
{
if(! from.containsKey(codon))
from.put(codon, new ArrayList<Point>());
if(! to.containsKey(codon))
to.put(codon, new ArrayList<Point>());
if(! fromWeights.containsKey(codon))
fromWeights.put(codon, new ArrayList<Double>());
if(! toWeights.containsKey(codon))
toWeights.put(codon, new ArrayList<Double>());
}
/**
* Returns a list of 'from' points which the given component should map
* into the points returned by {@link to()}
*
* @param component
* @return
*/
public List<Point> from(Codon codon)
{
if(from.containsKey(codon))
return from.get(codon);
return Collections.emptyList();
}
/**
* Returns a list of 'to' points which should be mapped by the given
* component into the points returned by {@link from()}
*
* @param component
* @return
*/
public List<Point> to(Codon codon)
{
if (to.containsKey(codon))
return to.get(codon);
return Collections.emptyList();
}
/**
* Returns a list of 'from' frequencies which the given component weight
* should 'scale' into the points returned by {@link to()}
*
* @param component
* @return
*/
public List<Double> fromWeights(Codon codon)
{
if (fromWeights.containsKey(codon))
return fromWeights.get(codon);
return Collections.emptyList();
}
/**
* Returns a list of 'to' points which should be 'scales' by the weight
* of the given component into the points returned by {@link from()}
*
* @param component
* @return
*/
public List<Double> toWeights(Codon codon)
{
if (toWeights.containsKey(codon))
return toWeights.get(codon);
return Collections.emptyList();
}
@Override
public String toString()
{
String out = "";
for (Codon codon : from.keySet())
{
out += codon + ":" + from(codon).size() + "_" + to(codon).size() + " ";
}
return out;
}
}
protected Similitude findMap(List<Point> from, List<Point> to, Similitude old)
{
return org.lilian.data.real.Maps.findMap(from, to);
}
public static double findScalar(List<Double> x, List<Double> y)
{
double sumXX = 0.0;
double sumYX = 0.0;
for (int i = 0; i < x.size(); i++)
{
sumXX += x.get(i) * x.get(i);
sumYX += y.get(i) * x.get(i);
}
return sumYX / sumXX;
}
public static List<Integer> ifsCode(List<Codon> code)
{
return new Wrapper(code, true);
}
public static List<Integer> mapCode(List<Codon> code)
{
return new Wrapper(code, false);
}
private static class Wrapper extends AbstractList<Integer>
{
List<Codon> master;
boolean ifs;
public Wrapper(List<Codon> master, boolean ifs)
{
this.master = master;
this.ifs = ifs;
}
@Override
public Integer get(int index)
{
return ifs ? master.get(index).ifs() : master.get(index).map();
}
@Override
public int size()
{
return master.size();
}
}
}
| false | true | public void findModel()
{
// * Look for matching codes in the code tree
Maps maps = findMaps();
// * Frequency model for all component IFSs
BasicFrequencyModel<Integer> freqs = new BasicFrequencyModel<Integer>();
for(SChoiceTree tree : trees)
tree.count(freqs);
// * Models and weights
List<IFS<Similitude>> modelComponents = new ArrayList<IFS<Similitude>>(model.size());
List<Double> modelWeights = new ArrayList<Double>(model.size());
// * Initialize empty
for (int i : Series.series(model.size()))
modelComponents.add(null);
for (int i : Series.series(model.size()))
modelWeights.add(-1.0);
// * Keep check of components which were unassigned
List<Integer> modelAssigned = new ArrayList<Integer>(model.size());
List<Integer> modelUnassigned = new ArrayList<Integer>(model.size());
for(int h : series(model.size()))
{
IFS<Similitude> component = model.models().get(h);
int numComponents = component.size();
// * Initialize empty trans and weights list
List<Similitude> trans = new ArrayList<Similitude>(numComponents);
for (int i : Series.series(numComponents))
trans.add(null);
List<Double> weights = new ArrayList<Double>(numComponents);
for (int i : Series.series(numComponents))
weights.add(1.0 / numComponents);
// * Keep check of components which were unassigned
List<Integer> assigned = new ArrayList<Integer>(numComponents);
List<Integer> unassigned = new ArrayList<Integer>(numComponents);
for (int i : series(numComponents))
{
Codon c = new Codon(h, i);
int n = maps.size(c);
if (n != 0) // codes found containing this comp
{
// * Find the map for the point pairs
Similitude map = findMap(maps.from(c), maps.to(c), component.get(i));
// * Find the weight for the frequency pairs
double weight = findScalar(maps.fromWeights(c),
maps.toWeights(c));
trans.set(i, map);
weights.set(i, weight);
assigned.add(i);
} else
{ // No codes found with this component
unassigned.add(i);
}
}
if(! unassigned.isEmpty())
Global.log().info("unassigned: " + unassigned);
if (assigned.isEmpty())
modelUnassigned.add(h);
else
modelAssigned.add(h);
// * For each unassigned IFS component, take a random assigned component and
// perturb it slightly.
for (int i : unassigned)
{
int j = assigned.get(Global.random.nextInt(assigned.size()));
Similitude source = trans.get(j);
double sourceWeight = weights.get(j);
Similitude perturbed0 = Parameters.perturb(source, builder, perturbVar);
Similitude perturbed1 = Parameters.perturb(source, builder, perturbVar);
trans.set(i, perturbed0);
trans.set(j, perturbed1);
weights.set(i, sourceWeight / 2.0);
weights.set(j, sourceWeight / 2.0);
}
component = new IFS<Similitude>(trans.get(0), weights.get(0));
for (int i : series(1, numComponents))
component.addMap(trans.get(i), weights.get(i));
double ifsPrior = freqs.probability(h);
modelComponents.set(h, component);
modelWeights.set(h, ifsPrior);
}
// * For each unassigned model component, take a random assigned component and
// perturb it slightly.
for (int h : modelUnassigned)
{
int j = modelAssigned.get(Global.random.nextInt(modelAssigned.size()));
IFS<Similitude> source = modelComponents.get(j);
double sourceWeight = modelWeights.get(j);
IFS<Similitude> perturbed0 = Parameters.perturb(source, ifsBuilder, perturbVar);
IFS<Similitude> perturbed1 = Parameters.perturb(source, ifsBuilder, perturbVar);
modelComponents.set(h, perturbed0);
modelComponents.set(j, perturbed1);
modelWeights.set(h, sourceWeight / 2.0);
modelWeights.set(j, sourceWeight / 2.0);
}
model = null;
for(int h : series(modelComponents.size()))
if(model == null)
model = new DiscreteRIFS<Similitude>(modelComponents.get(h), modelWeights.get(h));
else
model.addModel(modelComponents.get(h), modelWeights.get(h));
}
| public void findModel()
{
// * Look for matching codes in the code tree
Maps maps = findMaps();
// * Frequency model for all component IFSs
BasicFrequencyModel<Integer> freqs = new BasicFrequencyModel<Integer>();
for(SChoiceTree tree : trees)
tree.count(freqs);
// * Models and weights
List<IFS<Similitude>> modelComponents = new ArrayList<IFS<Similitude>>(model.size());
List<Double> modelWeights = new ArrayList<Double>(model.size());
// * Initialize empty
for (int i : Series.series(model.size()))
modelComponents.add(null);
for (int i : Series.series(model.size()))
modelWeights.add(-1.0);
// * Keep check of components which were unassigned
List<Integer> modelAssigned = new ArrayList<Integer>(model.size());
List<Integer> modelUnassigned = new ArrayList<Integer>(model.size());
for(int h : series(model.size()))
{
IFS<Similitude> component = model.models().get(h);
int numComponents = component.size();
// * Initialize empty trans and weights list
List<Similitude> trans = new ArrayList<Similitude>(numComponents);
for (int i : Series.series(numComponents))
trans.add(null);
List<Double> weights = new ArrayList<Double>(numComponents);
for (int i : Series.series(numComponents))
weights.add(1.0 / numComponents);
// * Keep check of components which were unassigned
List<Integer> assigned = new ArrayList<Integer>(numComponents);
List<Integer> unassigned = new ArrayList<Integer>(numComponents);
for (int i : series(numComponents))
{
Codon c = new Codon(h, i);
int n = maps.size(c);
if (n != 0) // codes found containing this comp
{
// * Find the map for the point pairs
Similitude map = findMap(maps.from(c), maps.to(c), component.get(i));
// * Find the weight for the frequency pairs
double weight = findScalar(maps.fromWeights(c),
maps.toWeights(c));
trans.set(i, map);
weights.set(i, weight);
assigned.add(i);
} else
{ // No codes found with this component
unassigned.add(i);
}
}
if(! unassigned.isEmpty())
Global.log().info("unassigned: " + unassigned);
if (assigned.isEmpty())
{
modelUnassigned.add(h);
continue;
} else
{
modelAssigned.add(h);
}
// * For each unassigned IFS component, take a random assigned component and
// perturb it slightly.
for (int i : unassigned)
{
int j = assigned.get(Global.random.nextInt(assigned.size()));
Similitude source = trans.get(j);
double sourceWeight = weights.get(j);
Similitude perturbed0 = Parameters.perturb(source, builder, perturbVar);
Similitude perturbed1 = Parameters.perturb(source, builder, perturbVar);
trans.set(i, perturbed0);
trans.set(j, perturbed1);
weights.set(i, sourceWeight / 2.0);
weights.set(j, sourceWeight / 2.0);
}
component = new IFS<Similitude>(trans.get(0), weights.get(0));
for (int i : series(1, numComponents))
component.addMap(trans.get(i), weights.get(i));
double ifsPrior = freqs.probability(h);
modelComponents.set(h, component);
modelWeights.set(h, ifsPrior);
}
// * For each unassigned model component, take a random assigned component and
// perturb it slightly.
for (int h : modelUnassigned)
{
int j = modelAssigned.get(Global.random.nextInt(modelAssigned.size()));
IFS<Similitude> source = modelComponents.get(j);
double sourceWeight = modelWeights.get(j);
IFS<Similitude> perturbed0 = Parameters.perturb(source, ifsBuilder, perturbVar);
IFS<Similitude> perturbed1 = Parameters.perturb(source, ifsBuilder, perturbVar);
modelComponents.set(h, perturbed0);
modelComponents.set(j, perturbed1);
modelWeights.set(h, sourceWeight / 2.0);
modelWeights.set(j, sourceWeight / 2.0);
}
model = null;
for(int h : series(modelComponents.size()))
if(model == null)
model = new DiscreteRIFS<Similitude>(modelComponents.get(h), modelWeights.get(h));
else
model.addModel(modelComponents.get(h), modelWeights.get(h));
}
|
diff --git a/document-classification/src/main/java/pl/edu/icm/coansys/classification/documents/pig/extractors/EXTRACT_MAP.java b/document-classification/src/main/java/pl/edu/icm/coansys/classification/documents/pig/extractors/EXTRACT_MAP.java
index 2ac6181d..1dfe4101 100644
--- a/document-classification/src/main/java/pl/edu/icm/coansys/classification/documents/pig/extractors/EXTRACT_MAP.java
+++ b/document-classification/src/main/java/pl/edu/icm/coansys/classification/documents/pig/extractors/EXTRACT_MAP.java
@@ -1,91 +1,91 @@
/*
* (C) 2010-2012 ICM UW. All rights reserved.
*/
package pl.edu.icm.coansys.classification.documents.pig.extractors;
import com.google.common.base.Joiner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.DefaultDataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import pl.edu.icm.coansys.classification.documents.auxil.StackTraceExtractor;
import pl.edu.icm.coansys.models.DocumentProtos.ClassifCode;
import pl.edu.icm.coansys.models.DocumentProtos.DocumentMetadata;
import pl.edu.icm.coansys.models.DocumentProtos.KeywordsList;
import pl.edu.icm.coansys.models.DocumentProtos.TextWithLanguage;
/**
*
* @author pdendek
*/
@SuppressWarnings("rawtypes")
public class EXTRACT_MAP extends EvalFunc<Map> {
@Override
public Map exec(Tuple input) throws IOException {
try {
DataByteArray protoMetadata = (DataByteArray) input.get(0);
DocumentMetadata metadata = DocumentMetadata.parseFrom(protoMetadata.get());
String titles;
String abstracts;
List<String> titleList = new ArrayList<String>();
for (TextWithLanguage title : metadata.getBasicMetadata().getTitleList()) {
titleList.add(title.getText());
}
titles = Joiner.on(" ").join(titleList);
List<String> abstractsList = new ArrayList<String>();
for (TextWithLanguage documentAbstract : metadata.getBasicMetadata().getTitleList()) {
abstractsList.add(documentAbstract.getText());
}
abstracts = Joiner.on(" ").join(abstractsList);
Map<String, Object> map = new HashMap<String, Object>();
map.put("key", metadata.getKey());
map.put("title", titles);
map.put("keywords", getConcatenated(metadata.getKeywordsList()));
- map.put("abstract", titles);
+ map.put("abstract", abstracts);
map.put("categories", getCategories(metadata.getBasicMetadata().getClassifCodeList()));
return map;
} catch (Exception e) {
// Throwing an exception will cause the task to fail.
throw new IOException("Caught exception processing input row:\n"
+ StackTraceExtractor.getStackTrace(e));
}
}
private static DataBag getCategories(List<ClassifCode> classifCodeList) {
DataBag db = new DefaultDataBag();
for (ClassifCode code : classifCodeList) {
for (String co_str : code.getValueList()) {
// System.out.print(" "+co_str);
db.add(TupleFactory.getInstance().newTuple(co_str));
}
}
return db;
}
private String getConcatenated(List<KeywordsList> list) {
if (list == null || list.isEmpty()) {
return null;
}
List<String> allKeywords = new ArrayList<String>();
if (allKeywords.isEmpty()) {
return null;
} else {
return Joiner.on(" ").join(allKeywords);
}
}
}
| true | true | public Map exec(Tuple input) throws IOException {
try {
DataByteArray protoMetadata = (DataByteArray) input.get(0);
DocumentMetadata metadata = DocumentMetadata.parseFrom(protoMetadata.get());
String titles;
String abstracts;
List<String> titleList = new ArrayList<String>();
for (TextWithLanguage title : metadata.getBasicMetadata().getTitleList()) {
titleList.add(title.getText());
}
titles = Joiner.on(" ").join(titleList);
List<String> abstractsList = new ArrayList<String>();
for (TextWithLanguage documentAbstract : metadata.getBasicMetadata().getTitleList()) {
abstractsList.add(documentAbstract.getText());
}
abstracts = Joiner.on(" ").join(abstractsList);
Map<String, Object> map = new HashMap<String, Object>();
map.put("key", metadata.getKey());
map.put("title", titles);
map.put("keywords", getConcatenated(metadata.getKeywordsList()));
map.put("abstract", titles);
map.put("categories", getCategories(metadata.getBasicMetadata().getClassifCodeList()));
return map;
} catch (Exception e) {
// Throwing an exception will cause the task to fail.
throw new IOException("Caught exception processing input row:\n"
+ StackTraceExtractor.getStackTrace(e));
}
}
| public Map exec(Tuple input) throws IOException {
try {
DataByteArray protoMetadata = (DataByteArray) input.get(0);
DocumentMetadata metadata = DocumentMetadata.parseFrom(protoMetadata.get());
String titles;
String abstracts;
List<String> titleList = new ArrayList<String>();
for (TextWithLanguage title : metadata.getBasicMetadata().getTitleList()) {
titleList.add(title.getText());
}
titles = Joiner.on(" ").join(titleList);
List<String> abstractsList = new ArrayList<String>();
for (TextWithLanguage documentAbstract : metadata.getBasicMetadata().getTitleList()) {
abstractsList.add(documentAbstract.getText());
}
abstracts = Joiner.on(" ").join(abstractsList);
Map<String, Object> map = new HashMap<String, Object>();
map.put("key", metadata.getKey());
map.put("title", titles);
map.put("keywords", getConcatenated(metadata.getKeywordsList()));
map.put("abstract", abstracts);
map.put("categories", getCategories(metadata.getBasicMetadata().getClassifCodeList()));
return map;
} catch (Exception e) {
// Throwing an exception will cause the task to fail.
throw new IOException("Caught exception processing input row:\n"
+ StackTraceExtractor.getStackTrace(e));
}
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/IWindow.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/IWindow.java
index 74a808087..6a67b77c4 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/IWindow.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/IWindow.java
@@ -1,472 +1,473 @@
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.Iterator;
import java.util.Vector;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.KeyboardListenerCollection;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.ScrollListener;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
/**
* "Sub window" component.
*
* TODO update position / scrollposition / size to client
*
* @author IT Mill Ltd
*/
public class IWindow extends PopupPanel implements Paintable, ScrollListener {
private static final int DEFAULT_HEIGHT = 300;
private static final int DEFAULT_WIDTH = 400;
private static final int MIN_HEIGHT = 60;
private static final int MIN_WIDTH = 80;
private static Vector windowOrder = new Vector();
public static final String CLASSNAME = "i-window";
/** pixels used by inner borders and paddings horizontally */
protected static final int BORDER_WIDTH_HORIZONTAL = 41;
/** pixels used by headers, footers, inner borders and paddings vertically */
protected static final int BORDER_WIDTH_VERTICAL = 58;
private static final int STACKING_OFFSET_PIXELS = 15;
private static final int Z_INDEX_BASE = 10000;
private Paintable layout;
private Element contents;
private Element header;
private Element footer;
private Element resizeBox;
private final ScrollPanel contentPanel = new ScrollPanel();
private boolean dragging;
private int startX;
private int startY;
private int origX;
private int origY;
private boolean resizing;
private int origW;
private int origH;
private Element closeBox;
protected ApplicationConnection client;
private String id;
ShortcutActionHandler shortcutHandler;
/** Last known width read from UIDL or updated to application connection */
private int uidlWidth = -1;
/** Last known height read from UIDL or updated to application connection */
private int uidlHeight = -1;
/** Last known positionx read from UIDL or updated to application connection */
private int uidlPositionX = -1;
/** Last known positiony read from UIDL or updated to application connection */
private int uidlPositionY = -1;
private boolean modal = false;
private Element headerText;
public IWindow() {
super();
int order = windowOrder.size();
setWindowOrder(order);
windowOrder.add(this);
setStyleName(CLASSNAME);
constructDOM();
setPopupPosition(order * STACKING_OFFSET_PIXELS, order
* STACKING_OFFSET_PIXELS);
contentPanel.addScrollListener(this);
}
private void bringToFront() {
int curIndex = windowOrder.indexOf(this);
if (curIndex + 1 < windowOrder.size()) {
windowOrder.remove(this);
windowOrder.add(this);
for (; curIndex < windowOrder.size(); curIndex++) {
((IWindow) windowOrder.get(curIndex)).setWindowOrder(curIndex);
}
}
}
/**
* Returns true if window is the topmost window
*
* @return
*/
private boolean isActive() {
return windowOrder.lastElement().equals(this);
}
public void setWindowOrder(int order) {
DOM.setStyleAttribute(getElement(), "zIndex", ""
+ (order + Z_INDEX_BASE));
}
protected void constructDOM() {
header = DOM.createDiv();
DOM.setElementProperty(header, "className", CLASSNAME + "-outerheader");
headerText = DOM.createDiv();
DOM.setElementProperty(headerText, "className", CLASSNAME + "-header");
contents = DOM.createDiv();
DOM.setElementProperty(contents, "className", CLASSNAME + "-contents");
footer = DOM.createDiv();
DOM.setElementProperty(footer, "className", CLASSNAME + "-footer");
resizeBox = DOM.createDiv();
DOM
.setElementProperty(resizeBox, "className", CLASSNAME
+ "-resizebox");
closeBox = DOM.createDiv();
DOM.setElementProperty(closeBox, "className", CLASSNAME + "-closebox");
DOM.appendChild(footer, resizeBox);
DOM.sinkEvents(header, Event.MOUSEEVENTS);
DOM.sinkEvents(resizeBox, Event.MOUSEEVENTS);
DOM.sinkEvents(closeBox, Event.ONCLICK);
DOM.sinkEvents(contents, Event.ONCLICK);
Element wrapper = DOM.createDiv();
DOM.setElementProperty(wrapper, "className", CLASSNAME + "-wrap");
Element wrapper2 = DOM.createDiv();
DOM.setElementProperty(wrapper2, "className", CLASSNAME + "-wrap2");
DOM.sinkEvents(wrapper, Event.ONKEYDOWN);
DOM.appendChild(wrapper2, closeBox);
DOM.appendChild(wrapper2, header);
DOM.appendChild(header, headerText);
DOM.appendChild(wrapper2, contents);
DOM.appendChild(wrapper2, footer);
DOM.appendChild(wrapper, wrapper2);
DOM.appendChild(getElement(), wrapper);
setWidget(contentPanel);
// set default size
setWidth(DEFAULT_WIDTH + "px");
setHeight(DEFAULT_HEIGHT + "px");
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
id = uidl.getId();
this.client = client;
if (uidl.hasAttribute("invisible")) {
this.hide();
return;
}
if (client.updateComponent(this, uidl, false)) {
return;
}
if (uidl.getBooleanAttribute("modal") != modal) {
setModal(!modal);
}
// Initialize the width from UIDL
if (uidl.hasVariable("width")) {
String width = uidl.getStringVariable("width");
setWidth(width);
}
if (uidl.hasVariable("height")) {
String height = uidl.getStringVariable("height");
setHeight(height);
}
// Initialize the position form UIDL
try {
int positionx = uidl.getIntVariable("positionx");
int positiony = uidl.getIntVariable("positiony");
if (positionx >= 0 && positiony >= 0) {
setPopupPosition(positionx, positiony);
}
} catch (IllegalArgumentException e) {
// Silently ignored as positionx and positiony are not required
// parameters
}
if (!isAttached()) {
show();
}
if (uidl.hasAttribute("caption")) {
setCaption(uidl.getStringAttribute("caption"));
}
UIDL childUidl = uidl.getChildUIDL(0);
if ("open".equals(childUidl.getTag())) {
- // TODO render different resources (theme:// etc?)
+ String parsedUri = client.translateToolkitUri(childUidl
+ .getStringAttribute("src"));
// TODO this should be a while-loop for multiple opens
if (!childUidl.hasAttribute("name")) {
Frame frame = new Frame();
DOM.setStyleAttribute(frame.getElement(), "width", "100%");
DOM.setStyleAttribute(frame.getElement(), "height", "100%");
DOM.setStyleAttribute(frame.getElement(), "border", "0px");
- frame.setUrl(childUidl.getStringAttribute("src"));
+ frame.setUrl(parsedUri);
contentPanel.setWidget(frame);
} else {
String target = childUidl.getStringAttribute("name");
- Window.open(childUidl.getStringAttribute("src"), target, "");
+ Window.open(parsedUri, target, "");
}
} else {
Paintable lo = (Paintable) client.getWidget(childUidl);
if (layout != null) {
if (layout != lo) {
// remove old
client.unregisterPaintable(layout);
contentPanel.remove((Widget) layout);
// add new
contentPanel.setWidget((Widget) lo);
layout = lo;
}
} else {
contentPanel.setWidget((Widget) lo);
}
lo.updateFromUIDL(childUidl, client);
}
// we may have actions and notifications
if (uidl.getChidlCount() > 1) {
int cnt = uidl.getChidlCount();
for (int i = 1; i < cnt; i++) {
childUidl = uidl.getChildUIDL(i);
if (childUidl.getTag().equals("actions")) {
if (shortcutHandler == null) {
shortcutHandler = new ShortcutActionHandler(id, client);
}
shortcutHandler.updateActionMap(childUidl);
} else if (childUidl.getTag().equals("notifications")) {
// TODO needed? move ->
for (Iterator it = childUidl.getChildIterator(); it
.hasNext();) {
UIDL notification = (UIDL) it.next();
String html = "";
if (notification.hasAttribute("caption")) {
html += "<H1>"
+ notification
.getStringAttribute("caption")
+ "</H1>";
}
if (notification.hasAttribute("message")) {
html += "<p>"
+ notification
.getStringAttribute("message")
+ "</p>";
}
String style = notification.hasAttribute("style") ? notification
.getStringAttribute("style")
: null;
int position = notification.getIntAttribute("position");
int delay = notification.getIntAttribute("delay");
new Notification(delay).show(html, position, style);
}
}
}
}
// setting scrollposition must happen after children is rendered
contentPanel.setScrollPosition(uidl.getIntVariable("scrolltop"));
contentPanel.setHorizontalScrollPosition(uidl
.getIntVariable("scrollleft"));
}
private void setModal(boolean modality) {
// TODO create transparent curtain to create visual clue that window is
// modal
modal = modality;
}
public void setPopupPosition(int left, int top) {
super.setPopupPosition(left, top);
if (left != uidlPositionX && client != null) {
client.updateVariable(id, "positionx", left, false);
uidlPositionX = left;
}
if (top != uidlPositionY && client != null) {
client.updateVariable(id, "positiony", top, false);
uidlPositionY = top;
}
}
public void setCaption(String c) {
DOM.setInnerText(headerText, c);
}
protected Element getContainerElement() {
return contents;
}
public void onBrowserEvent(Event event) {
int type = DOM.eventGetType(event);
if (type == Event.ONKEYDOWN && shortcutHandler != null) {
int modifiers = KeyboardListenerCollection
.getKeyboardModifiers(event);
shortcutHandler.handleKeyboardEvent((char) DOM
.eventGetKeyCode(event), modifiers);
return;
}
if (!isActive()) {
bringToFront();
}
Element target = DOM.eventGetTarget(event);
if (dragging || DOM.isOrHasChild(header, target)) {
onHeaderEvent(event);
DOM.eventCancelBubble(event, true);
} else if (resizing || DOM.compare(resizeBox, target)) {
onResizeEvent(event);
DOM.eventCancelBubble(event, true);
} else if (DOM.compare(target, closeBox) && type == Event.ONCLICK) {
onCloseClick();
DOM.eventCancelBubble(event, true);
}
}
private void onCloseClick() {
client.updateVariable(id, "close", true, true);
}
private void onResizeEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
resizing = true;
startX = DOM.eventGetScreenX(event);
startY = DOM.eventGetScreenY(event);
origW = DOM.getIntStyleAttribute(getElement(), "width")
- BORDER_WIDTH_HORIZONTAL;
origH = getWidget().getOffsetHeight();
DOM.eventPreventDefault(event);
DOM.addEventPreview(this);
break;
case Event.ONMOUSEUP:
resizing = false;
DOM.removeEventPreview(this);
setSize(event, true);
break;
case Event.ONMOUSEMOVE:
if (resizing) {
setSize(event, false);
DOM.eventPreventDefault(event);
}
break;
default:
DOM.eventPreventDefault(event);
break;
}
}
public void setSize(Event event, boolean updateVariables) {
int w = DOM.eventGetScreenX(event) - startX + origW;
if (w < MIN_WIDTH) {
w = MIN_WIDTH;
}
int h = DOM.eventGetScreenY(event) - startY + origH;
if (h < MIN_HEIGHT) {
h = MIN_HEIGHT;
}
setWidth(w + "px");
setHeight(h + "px");
if (updateVariables) {
// sending width back always as pixels, no need for unit
client.updateVariable(id, "width", w, false);
client.updateVariable(id, "height", h, false);
}
// Update child widget dimensions
Util.runDescendentsLayout(this);
}
public void setWidth(String width) {
DOM.setStyleAttribute(getElement(), "width", (Integer.parseInt(width
.substring(0, width.length() - 2)) + BORDER_WIDTH_HORIZONTAL)
+ "px");
}
private void onHeaderEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
dragging = true;
startX = DOM.eventGetScreenX(event);
startY = DOM.eventGetScreenY(event);
origX = DOM.getAbsoluteLeft(getElement());
origY = DOM.getAbsoluteTop(getElement());
DOM.eventPreventDefault(event);
DOM.addEventPreview(this);
break;
case Event.ONMOUSEUP:
dragging = false;
DOM.removeEventPreview(this);
break;
case Event.ONMOUSEMOVE:
if (dragging) {
int x = DOM.eventGetScreenX(event) - startX + origX;
int y = DOM.eventGetScreenY(event) - startY + origY;
setPopupPosition(x, y);
DOM.eventPreventDefault(event);
}
break;
default:
break;
}
}
public boolean onEventPreview(Event event) {
if (dragging) {
onHeaderEvent(event);
return false;
} else if (resizing) {
onResizeEvent(event);
return false;
} else if (modal) {
// return false when modal and outside window
Element target = DOM.eventGetTarget(event);
if (!DOM.isOrHasChild(getElement(), target)) {
return false;
}
}
return true;
}
public void onScroll(Widget widget, int scrollLeft, int scrollTop) {
client.updateVariable(id, "scrolltop", scrollTop, false);
client.updateVariable(id, "scrollleft", scrollLeft, false);
}
}
| false | true | public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
id = uidl.getId();
this.client = client;
if (uidl.hasAttribute("invisible")) {
this.hide();
return;
}
if (client.updateComponent(this, uidl, false)) {
return;
}
if (uidl.getBooleanAttribute("modal") != modal) {
setModal(!modal);
}
// Initialize the width from UIDL
if (uidl.hasVariable("width")) {
String width = uidl.getStringVariable("width");
setWidth(width);
}
if (uidl.hasVariable("height")) {
String height = uidl.getStringVariable("height");
setHeight(height);
}
// Initialize the position form UIDL
try {
int positionx = uidl.getIntVariable("positionx");
int positiony = uidl.getIntVariable("positiony");
if (positionx >= 0 && positiony >= 0) {
setPopupPosition(positionx, positiony);
}
} catch (IllegalArgumentException e) {
// Silently ignored as positionx and positiony are not required
// parameters
}
if (!isAttached()) {
show();
}
if (uidl.hasAttribute("caption")) {
setCaption(uidl.getStringAttribute("caption"));
}
UIDL childUidl = uidl.getChildUIDL(0);
if ("open".equals(childUidl.getTag())) {
// TODO render different resources (theme:// etc?)
// TODO this should be a while-loop for multiple opens
if (!childUidl.hasAttribute("name")) {
Frame frame = new Frame();
DOM.setStyleAttribute(frame.getElement(), "width", "100%");
DOM.setStyleAttribute(frame.getElement(), "height", "100%");
DOM.setStyleAttribute(frame.getElement(), "border", "0px");
frame.setUrl(childUidl.getStringAttribute("src"));
contentPanel.setWidget(frame);
} else {
String target = childUidl.getStringAttribute("name");
Window.open(childUidl.getStringAttribute("src"), target, "");
}
} else {
Paintable lo = (Paintable) client.getWidget(childUidl);
if (layout != null) {
if (layout != lo) {
// remove old
client.unregisterPaintable(layout);
contentPanel.remove((Widget) layout);
// add new
contentPanel.setWidget((Widget) lo);
layout = lo;
}
} else {
contentPanel.setWidget((Widget) lo);
}
lo.updateFromUIDL(childUidl, client);
}
// we may have actions and notifications
if (uidl.getChidlCount() > 1) {
int cnt = uidl.getChidlCount();
for (int i = 1; i < cnt; i++) {
childUidl = uidl.getChildUIDL(i);
if (childUidl.getTag().equals("actions")) {
if (shortcutHandler == null) {
shortcutHandler = new ShortcutActionHandler(id, client);
}
shortcutHandler.updateActionMap(childUidl);
} else if (childUidl.getTag().equals("notifications")) {
// TODO needed? move ->
for (Iterator it = childUidl.getChildIterator(); it
.hasNext();) {
UIDL notification = (UIDL) it.next();
String html = "";
if (notification.hasAttribute("caption")) {
html += "<H1>"
+ notification
.getStringAttribute("caption")
+ "</H1>";
}
if (notification.hasAttribute("message")) {
html += "<p>"
+ notification
.getStringAttribute("message")
+ "</p>";
}
String style = notification.hasAttribute("style") ? notification
.getStringAttribute("style")
: null;
int position = notification.getIntAttribute("position");
int delay = notification.getIntAttribute("delay");
new Notification(delay).show(html, position, style);
}
}
}
}
// setting scrollposition must happen after children is rendered
contentPanel.setScrollPosition(uidl.getIntVariable("scrolltop"));
contentPanel.setHorizontalScrollPosition(uidl
.getIntVariable("scrollleft"));
}
| public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
id = uidl.getId();
this.client = client;
if (uidl.hasAttribute("invisible")) {
this.hide();
return;
}
if (client.updateComponent(this, uidl, false)) {
return;
}
if (uidl.getBooleanAttribute("modal") != modal) {
setModal(!modal);
}
// Initialize the width from UIDL
if (uidl.hasVariable("width")) {
String width = uidl.getStringVariable("width");
setWidth(width);
}
if (uidl.hasVariable("height")) {
String height = uidl.getStringVariable("height");
setHeight(height);
}
// Initialize the position form UIDL
try {
int positionx = uidl.getIntVariable("positionx");
int positiony = uidl.getIntVariable("positiony");
if (positionx >= 0 && positiony >= 0) {
setPopupPosition(positionx, positiony);
}
} catch (IllegalArgumentException e) {
// Silently ignored as positionx and positiony are not required
// parameters
}
if (!isAttached()) {
show();
}
if (uidl.hasAttribute("caption")) {
setCaption(uidl.getStringAttribute("caption"));
}
UIDL childUidl = uidl.getChildUIDL(0);
if ("open".equals(childUidl.getTag())) {
String parsedUri = client.translateToolkitUri(childUidl
.getStringAttribute("src"));
// TODO this should be a while-loop for multiple opens
if (!childUidl.hasAttribute("name")) {
Frame frame = new Frame();
DOM.setStyleAttribute(frame.getElement(), "width", "100%");
DOM.setStyleAttribute(frame.getElement(), "height", "100%");
DOM.setStyleAttribute(frame.getElement(), "border", "0px");
frame.setUrl(parsedUri);
contentPanel.setWidget(frame);
} else {
String target = childUidl.getStringAttribute("name");
Window.open(parsedUri, target, "");
}
} else {
Paintable lo = (Paintable) client.getWidget(childUidl);
if (layout != null) {
if (layout != lo) {
// remove old
client.unregisterPaintable(layout);
contentPanel.remove((Widget) layout);
// add new
contentPanel.setWidget((Widget) lo);
layout = lo;
}
} else {
contentPanel.setWidget((Widget) lo);
}
lo.updateFromUIDL(childUidl, client);
}
// we may have actions and notifications
if (uidl.getChidlCount() > 1) {
int cnt = uidl.getChidlCount();
for (int i = 1; i < cnt; i++) {
childUidl = uidl.getChildUIDL(i);
if (childUidl.getTag().equals("actions")) {
if (shortcutHandler == null) {
shortcutHandler = new ShortcutActionHandler(id, client);
}
shortcutHandler.updateActionMap(childUidl);
} else if (childUidl.getTag().equals("notifications")) {
// TODO needed? move ->
for (Iterator it = childUidl.getChildIterator(); it
.hasNext();) {
UIDL notification = (UIDL) it.next();
String html = "";
if (notification.hasAttribute("caption")) {
html += "<H1>"
+ notification
.getStringAttribute("caption")
+ "</H1>";
}
if (notification.hasAttribute("message")) {
html += "<p>"
+ notification
.getStringAttribute("message")
+ "</p>";
}
String style = notification.hasAttribute("style") ? notification
.getStringAttribute("style")
: null;
int position = notification.getIntAttribute("position");
int delay = notification.getIntAttribute("delay");
new Notification(delay).show(html, position, style);
}
}
}
}
// setting scrollposition must happen after children is rendered
contentPanel.setScrollPosition(uidl.getIntVariable("scrolltop"));
contentPanel.setHorizontalScrollPosition(uidl
.getIntVariable("scrollleft"));
}
|
diff --git a/java/FRC-DriverStation-PC/src/org/anidev/frcds/pc/Utils.java b/java/FRC-DriverStation-PC/src/org/anidev/frcds/pc/Utils.java
index 8ea71ac..b7ae2f8 100644
--- a/java/FRC-DriverStation-PC/src/org/anidev/frcds/pc/Utils.java
+++ b/java/FRC-DriverStation-PC/src/org/anidev/frcds/pc/Utils.java
@@ -1,89 +1,89 @@
package org.anidev.frcds.pc;
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.prefs.Preferences;
import javax.imageio.ImageIO;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
public class Utils {
public static int calcAlpha(double alpha,int newColor,int oldColor) {
return (int)Math.round(alpha*newColor+(1-alpha)*oldColor);
}
public static Color calcAlpha(double alpha,Color newColor,Color oldColor) {
int calcR=calcAlpha(alpha,newColor.getRed(),oldColor.getRed());
int calcG=calcAlpha(alpha,newColor.getGreen(),oldColor.getGreen());
int calcB=calcAlpha(alpha,newColor.getBlue(),oldColor.getBlue());
return new Color(calcR,calcG,calcB);
}
public static AbstractButton getSelectedButton(ButtonGroup group) {
Enumeration<AbstractButton> buttons=group.getElements();
while(buttons.hasMoreElements()) {
AbstractButton button=buttons.nextElement();
if(button.isSelected()) {
return button;
}
}
return null;
}
public static ImageIcon getIcon(String name) {
try {
URL imageUrl=Utils.class.getResource("/resources/"+name);
Image image=ImageIO.read(imageUrl);
ImageIcon icon=new ImageIcon(image);
return icon;
} catch(IOException e) {
e.printStackTrace();
return null;
}
}
public static Preferences getPrefs() {
return Preferences.userNodeForPackage(PCDriverStation.class);
}
public static Object getNimbusPref(String key,JComponent c) {
UIDefaults uiValues=UIManager.getLookAndFeelDefaults();
Object overrides=c.getClientProperty("Nimbus.Overrides");
Object pref=null;
if(overrides!=null&&overrides instanceof UIDefaults) {
pref=((UIDefaults)overrides).get(key);
}
if(pref==null) {
pref=uiValues.get(key);
}
return pref;
}
public static void setLookAndFeel() {
String lafStr=System.getProperty("anidev.pcds.laf","<nimbus>");
switch(lafStr) {
case "<nimbus>":
lafStr="com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel";
break;
case "<system>":
lafStr=UIManager.getSystemLookAndFeelClassName();
break;
case "<cross>":
lafStr=UIManager.getCrossPlatformLookAndFeelClassName();
break;
}
try {
UIManager.setLookAndFeel(lafStr);
} catch(Exception e) {
- System.err.println("Error while setting Nimbus L&F.");
+ System.err.println("Error while setting "+lafStr+" L&F.");
e.printStackTrace();
}
}
}
| true | true | public static void setLookAndFeel() {
String lafStr=System.getProperty("anidev.pcds.laf","<nimbus>");
switch(lafStr) {
case "<nimbus>":
lafStr="com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel";
break;
case "<system>":
lafStr=UIManager.getSystemLookAndFeelClassName();
break;
case "<cross>":
lafStr=UIManager.getCrossPlatformLookAndFeelClassName();
break;
}
try {
UIManager.setLookAndFeel(lafStr);
} catch(Exception e) {
System.err.println("Error while setting Nimbus L&F.");
e.printStackTrace();
}
}
| public static void setLookAndFeel() {
String lafStr=System.getProperty("anidev.pcds.laf","<nimbus>");
switch(lafStr) {
case "<nimbus>":
lafStr="com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel";
break;
case "<system>":
lafStr=UIManager.getSystemLookAndFeelClassName();
break;
case "<cross>":
lafStr=UIManager.getCrossPlatformLookAndFeelClassName();
break;
}
try {
UIManager.setLookAndFeel(lafStr);
} catch(Exception e) {
System.err.println("Error while setting "+lafStr+" L&F.");
e.printStackTrace();
}
}
|
diff --git a/IntListIterationTiming.java b/IntListIterationTiming.java
index 7a84b04..dcbfd20 100644
--- a/IntListIterationTiming.java
+++ b/IntListIterationTiming.java
@@ -1,49 +1,49 @@
import java.util.Locale;
import java.util.Random;
/**
* Benchmark the difference between iteration on {@code ArrayList<Integer>} and regular java array.
* @author Roman Elizarov
*/
public class IntListIterationTiming {
private static final String[] CLASS_NAMES = new String[]{"IntList$ViaArrayList", "IntList$ViaJavaArray"};
private static int dummy; // to avoid HotSpot optimizing away iteration
private final IntList list;
@SuppressWarnings("unchecked")
private IntListIterationTiming(String className, int size) throws Exception {
list = (IntList)Class.forName(className).newInstance();
Random random = new Random(1);
for (int i = 0; i < size; i++)
list.add(random.nextInt());
}
private double time() {
int reps = 100000000 / list.size();
long start = System.nanoTime();
for (int rep = 0; rep < reps; rep++)
dummy += runIteration();
return (double)(System.nanoTime() - start) / reps / list.size();
}
private int runIteration() {
int sum = 0;
for (int i = 0, n = list.size(); i < n; i++)
sum += list.getInt(i);
return sum;
}
public static void main(String[] args) throws Exception {
for (int pass = 1; pass <= 3; pass++) { // 2 passes to let JIT compile everything, look at 3rd
- System.out.printf("----- PASS %d -----%d%n", pass);
+ System.out.printf("----- PASS %d -----%n", pass);
for (int size = 1000; size <= 10000000; size *= 10) {
for (String className : CLASS_NAMES) {
dummy = 0;
IntListIterationTiming timing = new IntListIterationTiming(className, size);
double time = timing.time();
System.out.printf(Locale.US, "%30s[%8d]: %.2f ns per item (%d)%n", className, size, time, dummy);
}
}
}
}
}
| true | true | public static void main(String[] args) throws Exception {
for (int pass = 1; pass <= 3; pass++) { // 2 passes to let JIT compile everything, look at 3rd
System.out.printf("----- PASS %d -----%d%n", pass);
for (int size = 1000; size <= 10000000; size *= 10) {
for (String className : CLASS_NAMES) {
dummy = 0;
IntListIterationTiming timing = new IntListIterationTiming(className, size);
double time = timing.time();
System.out.printf(Locale.US, "%30s[%8d]: %.2f ns per item (%d)%n", className, size, time, dummy);
}
}
}
}
| public static void main(String[] args) throws Exception {
for (int pass = 1; pass <= 3; pass++) { // 2 passes to let JIT compile everything, look at 3rd
System.out.printf("----- PASS %d -----%n", pass);
for (int size = 1000; size <= 10000000; size *= 10) {
for (String className : CLASS_NAMES) {
dummy = 0;
IntListIterationTiming timing = new IntListIterationTiming(className, size);
double time = timing.time();
System.out.printf(Locale.US, "%30s[%8d]: %.2f ns per item (%d)%n", className, size, time, dummy);
}
}
}
}
|
diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/AstridNewSyncMigrator.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/AstridNewSyncMigrator.java
index 71d3d8277..b76de3ad4 100644
--- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/AstridNewSyncMigrator.java
+++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/AstridNewSyncMigrator.java
@@ -1,419 +1,419 @@
package com.todoroo.astrid.actfm.sync;
import java.util.HashSet;
import java.util.Set;
import android.text.TextUtils;
import android.util.Log;
import com.todoroo.andlib.data.DatabaseDao;
import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.sql.Criterion;
import com.todoroo.andlib.sql.Functions;
import com.todoroo.andlib.sql.Query;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.actfm.sync.messages.NameMaps;
import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria;
import com.todoroo.astrid.dao.OutstandingEntryDao;
import com.todoroo.astrid.dao.TagDataDao;
import com.todoroo.astrid.dao.TagOutstandingDao;
import com.todoroo.astrid.dao.TaskAttachmentDao;
import com.todoroo.astrid.dao.TaskDao;
import com.todoroo.astrid.dao.TaskOutstandingDao;
import com.todoroo.astrid.dao.UpdateDao;
import com.todoroo.astrid.dao.UserActivityDao;
import com.todoroo.astrid.dao.UserDao;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.data.OutstandingEntry;
import com.todoroo.astrid.data.RemoteModel;
import com.todoroo.astrid.data.SyncFlags;
import com.todoroo.astrid.data.TagData;
import com.todoroo.astrid.data.TagOutstanding;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.data.TaskAttachment;
import com.todoroo.astrid.data.TaskOutstanding;
import com.todoroo.astrid.data.Update;
import com.todoroo.astrid.data.User;
import com.todoroo.astrid.data.UserActivity;
import com.todoroo.astrid.files.FileMetadata;
import com.todoroo.astrid.helper.UUIDHelper;
import com.todoroo.astrid.service.MetadataService;
import com.todoroo.astrid.service.TagDataService;
import com.todoroo.astrid.tags.TaskToTagMetadata;
@SuppressWarnings("nls")
public class AstridNewSyncMigrator {
@Autowired private MetadataService metadataService;
@Autowired private TagDataService tagDataService;
@Autowired private TagDataDao tagDataDao;
@Autowired private TaskDao taskDao;
@Autowired private UpdateDao updateDao;
@Autowired private UserActivityDao userActivityDao;
@Autowired private UserDao userDao;
@Autowired private TaskAttachmentDao taskAttachmentDao;
@Autowired private TaskOutstandingDao taskOutstandingDao;
@Autowired private TagOutstandingDao tagOutstandingDao;
private static final String LOG_TAG = "sync-migrate";
public static final String PREF_SYNC_MIGRATION = "p_sync_migration";
public AstridNewSyncMigrator() {
DependencyInjectionService.getInstance().inject(this);
}
@SuppressWarnings("deprecation")
public void performMigration() {
if (Preferences.getBoolean(PREF_SYNC_MIGRATION, false))
return;
// --------------
// First ensure that a TagData object exists for each tag metadata
// --------------
try {
Query noTagDataQuery = Query.select(Metadata.PROPERTIES).where(Criterion.and(
MetadataCriteria.withKey(TaskToTagMetadata.KEY),
Criterion.or(TaskToTagMetadata.TAG_UUID.isNull(), TaskToTagMetadata.TAG_UUID.eq(0)),
Criterion.not(TaskToTagMetadata.TAG_NAME.in(Query.select(TagData.NAME).from(TagData.TABLE))))).groupBy(TaskToTagMetadata.TAG_NAME);
TodorooCursor<Metadata> noTagData = metadataService.query(noTagDataQuery);
try {
Metadata tag = new Metadata();
for (noTagData.moveToFirst(); !noTagData.isAfterLast(); noTagData.moveToNext()) {
tag.readFromCursor(noTagData);
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "CREATING TAG DATA " + tag.getValue(TaskToTagMetadata.TAG_NAME));
TagData newTagData = new TagData();
newTagData.setValue(TagData.NAME, tag.getValue(TaskToTagMetadata.TAG_NAME));
tagDataService.save(newTagData);
}
} finally {
noTagData.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error creating tag data", e);
}
// --------------
// Delete all emergent tag data, we don't need it
// --------------
try {
TodorooCursor<TagData> emergentTags = tagDataDao.query(Query.select(TagData.ID, TagData.NAME).where(Functions.bitwiseAnd(TagData.FLAGS, TagData.FLAG_EMERGENT).gt(0)));
try {
TagData td = new TagData();
for (emergentTags.moveToFirst(); !emergentTags.isAfterLast(); emergentTags.moveToNext()) {
td.clear();
td.readFromCursor(emergentTags);
String name = td.getValue(TagData.NAME);
tagDataDao.delete(td.getId());
if (!TextUtils.isEmpty(name))
metadataService.deleteWhere(Criterion.and(MetadataCriteria.withKey(TaskToTagMetadata.KEY), TaskToTagMetadata.TAG_NAME.eq(name)));
}
} finally {
emergentTags.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error clearing emergent tags");
}
// --------------
// Then ensure that every remote model has a remote id, by generating one using the uuid generator for all those without one
// --------------
final Set<Long> tasksThatNeedTagSync = new HashSet<Long>();
try {
Query tagsQuery = Query.select(TagData.ID, TagData.UUID, TagData.MODIFICATION_DATE).where(Criterion.or(TagData.UUID.eq(RemoteModel.NO_UUID), TagData.UUID.isNull()));
assertUUIDsExist(tagsQuery, new TagData(), tagDataDao, tagOutstandingDao, new TagOutstanding(), NameMaps.syncableProperties(NameMaps.TABLE_ID_TAGS), new UUIDAssertionExtras<TagData>() {
private static final String LAST_TAG_FETCH_TIME = "actfm_lastTag"; //$NON-NLS-1$
- private final long lastFetchTime = Preferences.getLong(LAST_TAG_FETCH_TIME, 0);
+ private final long lastFetchTime = Preferences.getInt(LAST_TAG_FETCH_TIME, 0) * 1000L;
@Override
public void beforeSave(TagData instance) {/**/}
@Override
public boolean shouldCreateOutstandingEntries(TagData instance) {
return lastFetchTime == 0 || (instance.containsNonNullValue(TagData.MODIFICATION_DATE) && instance.getValue(TagData.MODIFICATION_DATE) > lastFetchTime);
}
});
Query tasksQuery = Query.select(Task.ID, Task.UUID, Task.RECURRENCE, Task.FLAGS, Task.MODIFICATION_DATE, Task.LAST_SYNC).where(Criterion.all);
assertUUIDsExist(tasksQuery, new Task(), taskDao, taskOutstandingDao, new TaskOutstanding(), NameMaps.syncableProperties(NameMaps.TABLE_ID_TASKS), new UUIDAssertionExtras<Task>() {
@Override
public void beforeSave(Task instance) {
if (instance.getFlag(Task.FLAGS, Task.FLAG_IS_READONLY)) {
instance.setFlag(Task.FLAGS, Task.FLAG_IS_READONLY, false);
instance.setValue(Task.IS_READONLY, 1);
}
if (instance.getFlag(Task.FLAGS, Task.FLAG_PUBLIC)) {
instance.setFlag(Task.FLAGS, Task.FLAG_PUBLIC, false);
instance.setValue(Task.IS_PUBLIC, 1);
}
String recurrence = instance.getValue(Task.RECURRENCE);
if (!TextUtils.isEmpty(recurrence)) {
boolean repeatAfterCompletion = instance.getFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION);
instance.setFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION, false);
recurrence = recurrence.replaceAll("BYDAY=;", "");
if (repeatAfterCompletion)
recurrence = recurrence + ";FROM=COMPLETION";
instance.setValue(Task.RECURRENCE, recurrence);
}
}
@Override
public boolean shouldCreateOutstandingEntries(Task instance) {
boolean result;
if (!instance.containsNonNullValue(Task.MODIFICATION_DATE) || instance.getValue(Task.LAST_SYNC) == 0)
result = true;
else
result = instance.getValue(Task.LAST_SYNC) < instance.getValue(Task.MODIFICATION_DATE);
if (result)
tasksThatNeedTagSync.add(instance.getId());
return result;
}
});
} catch (Exception e) {
Log.e(LOG_TAG, "Error asserting UUIDs", e);
}
// --------------
// Migrate unsynced task comments to UserActivity table
// --------------
try {
TodorooCursor<Update> updates = updateDao.query(Query.select(Update.PROPERTIES).where(
Criterion.and(Criterion.or(Update.UUID.eq(0), Update.UUID.isNull()), Criterion.or(Update.ACTION_CODE.eq(UserActivity.ACTION_TAG_COMMENT),
Update.ACTION_CODE.eq(UserActivity.ACTION_TASK_COMMENT)))));
try {
Update update = new Update();
UserActivity userActivity = new UserActivity();
for (updates.moveToFirst(); !updates.isAfterLast(); updates.moveToNext()) {
update.clear();
userActivity.clear();
update.readFromCursor(updates);
boolean setTarget = true;
if (!RemoteModel.isUuidEmpty(update.getValue(Update.TASK_UUID))) {
userActivity.setValue(UserActivity.TARGET_ID, update.getValue(Update.TASK_UUID));
} else if (update.getValue(Update.TASK_LOCAL) > 0) {
Task local = taskDao.fetch(update.getValue(Update.TASK_LOCAL), Task.UUID);
if (local != null && !RemoteModel.isUuidEmpty(local.getUuid()))
userActivity.setValue(UserActivity.TARGET_ID, local.getUuid());
else
setTarget = false;
} else {
setTarget = false;
}
if (setTarget) {
userActivity.setValue(UserActivity.USER_UUID, update.getValue(Update.USER_ID));
userActivity.setValue(UserActivity.ACTION, update.getValue(Update.ACTION_CODE));
userActivity.setValue(UserActivity.MESSAGE, update.getValue(Update.MESSAGE));
userActivity.setValue(UserActivity.CREATED_AT, update.getValue(Update.CREATION_DATE));
userActivityDao.createNew(userActivity);
}
}
} finally {
updates.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error migrating updates", e);
}
// --------------
// Drop any entries from the Users table that don't have a UUID
// --------------
try {
userDao.deleteWhere(Criterion.or(User.UUID.isNull(), User.UUID.eq(""), User.UUID.eq("0")));
} catch (Exception e) {
Log.e(LOG_TAG, "Error deleting incomplete user entries", e);
}
// --------------
// Migrate legacy FileMetadata models to new TaskAttachment models
// --------------
try {
TodorooCursor<Metadata> fmCursor = metadataService.query(Query.select(Metadata.PROPERTIES)
.where(MetadataCriteria.withKey(FileMetadata.METADATA_KEY)));
try {
System.err.println("FILES COUNT: " + fmCursor.getCount());
Metadata m = new Metadata();
for (fmCursor.moveToFirst(); !fmCursor.isAfterLast(); fmCursor.moveToNext()) {
m.clear();
m.readFromCursor(fmCursor);
TaskAttachment attachment = new TaskAttachment();
Task task = taskDao.fetch(m.getValue(Metadata.TASK), Task.UUID);
System.err.println("TASK UUID: " + task.getUuid());
if (task == null || !RemoteModel.isValidUuid(task.getUuid()))
continue;
Long oldRemoteId = m.getValue(FileMetadata.REMOTE_ID);
boolean synced = false;
if (oldRemoteId != null && oldRemoteId > 0) {
synced = true;
attachment.setValue(TaskAttachment.UUID, Long.toString(oldRemoteId));
}
System.err.println("ALREADY SYNCED: " + synced);
attachment.setValue(TaskAttachment.TASK_UUID, task.getUuid());
if (m.containsNonNullValue(FileMetadata.NAME))
attachment.setValue(TaskAttachment.NAME, m.getValue(FileMetadata.NAME));
if (m.containsNonNullValue(FileMetadata.URL))
attachment.setValue(TaskAttachment.URL, m.getValue(FileMetadata.URL));
if (m.containsNonNullValue(FileMetadata.FILE_PATH))
attachment.setValue(TaskAttachment.FILE_PATH, m.getValue(FileMetadata.FILE_PATH));
if (m.containsNonNullValue(FileMetadata.FILE_TYPE))
attachment.setValue(TaskAttachment.CONTENT_TYPE, m.getValue(FileMetadata.FILE_TYPE));
if (m.containsNonNullValue(FileMetadata.DELETION_DATE))
attachment.setValue(TaskAttachment.DELETED_AT, m.getValue(FileMetadata.DELETION_DATE));
if (synced) {
System.err.println("ATTACHMENT UUID: " + attachment.getValue(TaskAttachment.UUID));
attachment.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
}
taskAttachmentDao.createNew(attachment);
}
} finally {
fmCursor.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error migrating task attachment metadata", e);
}
// --------------
// Finally, ensure that all tag metadata entities have all important fields filled in
// --------------
try {
Query incompleteQuery = Query.select(Metadata.PROPERTIES).where(Criterion.and(
MetadataCriteria.withKey(TaskToTagMetadata.KEY),
Criterion.or(TaskToTagMetadata.TASK_UUID.eq(0), TaskToTagMetadata.TASK_UUID.isNull(),
TaskToTagMetadata.TAG_UUID.eq(0), TaskToTagMetadata.TAG_UUID.isNull())));
TodorooCursor<Metadata> incompleteMetadata = metadataService.query(incompleteQuery);
try {
Metadata m = new Metadata();
for (incompleteMetadata.moveToFirst(); !incompleteMetadata.isAfterLast(); incompleteMetadata.moveToNext()) {
m.clear(); // Need this since some properties may be null
m.readFromCursor(incompleteMetadata);
boolean changes = false;
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "Incomplete linking task " + m.getValue(Metadata.TASK) + " to " + m.getValue(TaskToTagMetadata.TAG_NAME));
if (!m.containsNonNullValue(TaskToTagMetadata.TASK_UUID) || RemoteModel.isUuidEmpty(m.getValue(TaskToTagMetadata.TASK_UUID))) {
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "No task uuid");
updateTaskUuid(m);
changes = true;
}
if (!m.containsNonNullValue(TaskToTagMetadata.TAG_UUID) || RemoteModel.isUuidEmpty(m.getValue(TaskToTagMetadata.TAG_UUID))) {
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "No tag uuid");
updateTagUuid(m);
changes = true;
}
if (changes)
metadataService.save(m);
}
} finally {
incompleteMetadata.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error validating task to tag metadata", e);
}
Preferences.setBoolean(PREF_SYNC_MIGRATION, true);
ActFmSyncMonitor monitor = ActFmSyncMonitor.getInstance();
synchronized (monitor) {
monitor.notifyAll();
}
}
private interface UUIDAssertionExtras<TYPE extends RemoteModel> {
void beforeSave(TYPE instance);
boolean shouldCreateOutstandingEntries(TYPE instance);
}
private <TYPE extends RemoteModel, OE extends OutstandingEntry<TYPE>> void assertUUIDsExist(Query query, TYPE instance, DatabaseDao<TYPE> dao, OutstandingEntryDao<OE> oeDao, OE oe, Property<?>[] propertiesForOutstanding, UUIDAssertionExtras<TYPE> extras) {
TodorooCursor<TYPE> cursor = dao.query(query);
try {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
instance.readPropertiesFromCursor(cursor);
boolean unsyncedModel = false;
if (!instance.containsNonNullValue(RemoteModel.UUID_PROPERTY) || RemoteModel.NO_UUID.equals(instance.getValue(RemoteModel.UUID_PROPERTY))) {
// No remote id exists, just create a UUID
unsyncedModel = true;
instance.setValue(RemoteModel.UUID_PROPERTY, UUIDHelper.newUUID());
}
if (extras != null)
extras.beforeSave(instance);
instance.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
dao.saveExisting(instance);
if (propertiesForOutstanding != null && (unsyncedModel || (extras != null && extras.shouldCreateOutstandingEntries(instance)))) {
createOutstandingEntries(instance.getId(), dao, oeDao, oe, propertiesForOutstanding);
}
}
} finally {
cursor.close();
}
}
private <TYPE extends RemoteModel, OE extends OutstandingEntry<TYPE>> void createOutstandingEntries(long id, DatabaseDao<TYPE> dao, OutstandingEntryDao<OE> oeDao, OE oe, Property<?>[] propertiesForOutstanding) {
TYPE instance = dao.fetch(id, propertiesForOutstanding);
long now = DateUtilities.now();
for (Property<?> property : propertiesForOutstanding) {
oe.clear();
oe.setValue(OutstandingEntry.ENTITY_ID_PROPERTY, id);
oe.setValue(OutstandingEntry.COLUMN_STRING_PROPERTY, property.name);
oe.setValue(OutstandingEntry.VALUE_STRING_PROPERTY, instance.getValue(property).toString());
oe.setValue(OutstandingEntry.CREATED_AT_PROPERTY, now);
oeDao.createNew(oe);
}
}
private void updateTaskUuid(Metadata m) {
long taskId = m.getValue(Metadata.TASK);
Task task = taskDao.fetch(taskId, Task.UUID);
if (task != null) {
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "Linking with task uuid " + task.getValue(Task.UUID));
m.setValue(TaskToTagMetadata.TASK_UUID, task.getValue(Task.UUID));
} else {
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "Task not found, deleting link");
m.setValue(Metadata.DELETION_DATE, DateUtilities.now());
}
}
private void updateTagUuid(Metadata m) {
String tag = m.getValue(TaskToTagMetadata.TAG_NAME);
TagData tagData = tagDataService.getTag(tag, TagData.UUID);
if (tagData != null) {
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "Linking with tag uuid " + tagData.getValue(TagData.UUID));
m.setValue(TaskToTagMetadata.TAG_UUID, tagData.getValue(TagData.UUID));
} else {
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "Tag not found, deleting link");
m.setValue(Metadata.DELETION_DATE, DateUtilities.now());
}
}
}
| true | true | public void performMigration() {
if (Preferences.getBoolean(PREF_SYNC_MIGRATION, false))
return;
// --------------
// First ensure that a TagData object exists for each tag metadata
// --------------
try {
Query noTagDataQuery = Query.select(Metadata.PROPERTIES).where(Criterion.and(
MetadataCriteria.withKey(TaskToTagMetadata.KEY),
Criterion.or(TaskToTagMetadata.TAG_UUID.isNull(), TaskToTagMetadata.TAG_UUID.eq(0)),
Criterion.not(TaskToTagMetadata.TAG_NAME.in(Query.select(TagData.NAME).from(TagData.TABLE))))).groupBy(TaskToTagMetadata.TAG_NAME);
TodorooCursor<Metadata> noTagData = metadataService.query(noTagDataQuery);
try {
Metadata tag = new Metadata();
for (noTagData.moveToFirst(); !noTagData.isAfterLast(); noTagData.moveToNext()) {
tag.readFromCursor(noTagData);
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "CREATING TAG DATA " + tag.getValue(TaskToTagMetadata.TAG_NAME));
TagData newTagData = new TagData();
newTagData.setValue(TagData.NAME, tag.getValue(TaskToTagMetadata.TAG_NAME));
tagDataService.save(newTagData);
}
} finally {
noTagData.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error creating tag data", e);
}
// --------------
// Delete all emergent tag data, we don't need it
// --------------
try {
TodorooCursor<TagData> emergentTags = tagDataDao.query(Query.select(TagData.ID, TagData.NAME).where(Functions.bitwiseAnd(TagData.FLAGS, TagData.FLAG_EMERGENT).gt(0)));
try {
TagData td = new TagData();
for (emergentTags.moveToFirst(); !emergentTags.isAfterLast(); emergentTags.moveToNext()) {
td.clear();
td.readFromCursor(emergentTags);
String name = td.getValue(TagData.NAME);
tagDataDao.delete(td.getId());
if (!TextUtils.isEmpty(name))
metadataService.deleteWhere(Criterion.and(MetadataCriteria.withKey(TaskToTagMetadata.KEY), TaskToTagMetadata.TAG_NAME.eq(name)));
}
} finally {
emergentTags.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error clearing emergent tags");
}
// --------------
// Then ensure that every remote model has a remote id, by generating one using the uuid generator for all those without one
// --------------
final Set<Long> tasksThatNeedTagSync = new HashSet<Long>();
try {
Query tagsQuery = Query.select(TagData.ID, TagData.UUID, TagData.MODIFICATION_DATE).where(Criterion.or(TagData.UUID.eq(RemoteModel.NO_UUID), TagData.UUID.isNull()));
assertUUIDsExist(tagsQuery, new TagData(), tagDataDao, tagOutstandingDao, new TagOutstanding(), NameMaps.syncableProperties(NameMaps.TABLE_ID_TAGS), new UUIDAssertionExtras<TagData>() {
private static final String LAST_TAG_FETCH_TIME = "actfm_lastTag"; //$NON-NLS-1$
private final long lastFetchTime = Preferences.getLong(LAST_TAG_FETCH_TIME, 0);
@Override
public void beforeSave(TagData instance) {/**/}
@Override
public boolean shouldCreateOutstandingEntries(TagData instance) {
return lastFetchTime == 0 || (instance.containsNonNullValue(TagData.MODIFICATION_DATE) && instance.getValue(TagData.MODIFICATION_DATE) > lastFetchTime);
}
});
Query tasksQuery = Query.select(Task.ID, Task.UUID, Task.RECURRENCE, Task.FLAGS, Task.MODIFICATION_DATE, Task.LAST_SYNC).where(Criterion.all);
assertUUIDsExist(tasksQuery, new Task(), taskDao, taskOutstandingDao, new TaskOutstanding(), NameMaps.syncableProperties(NameMaps.TABLE_ID_TASKS), new UUIDAssertionExtras<Task>() {
@Override
public void beforeSave(Task instance) {
if (instance.getFlag(Task.FLAGS, Task.FLAG_IS_READONLY)) {
instance.setFlag(Task.FLAGS, Task.FLAG_IS_READONLY, false);
instance.setValue(Task.IS_READONLY, 1);
}
if (instance.getFlag(Task.FLAGS, Task.FLAG_PUBLIC)) {
instance.setFlag(Task.FLAGS, Task.FLAG_PUBLIC, false);
instance.setValue(Task.IS_PUBLIC, 1);
}
String recurrence = instance.getValue(Task.RECURRENCE);
if (!TextUtils.isEmpty(recurrence)) {
boolean repeatAfterCompletion = instance.getFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION);
instance.setFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION, false);
recurrence = recurrence.replaceAll("BYDAY=;", "");
if (repeatAfterCompletion)
recurrence = recurrence + ";FROM=COMPLETION";
instance.setValue(Task.RECURRENCE, recurrence);
}
}
@Override
public boolean shouldCreateOutstandingEntries(Task instance) {
boolean result;
if (!instance.containsNonNullValue(Task.MODIFICATION_DATE) || instance.getValue(Task.LAST_SYNC) == 0)
result = true;
else
result = instance.getValue(Task.LAST_SYNC) < instance.getValue(Task.MODIFICATION_DATE);
if (result)
tasksThatNeedTagSync.add(instance.getId());
return result;
}
});
} catch (Exception e) {
Log.e(LOG_TAG, "Error asserting UUIDs", e);
}
// --------------
// Migrate unsynced task comments to UserActivity table
// --------------
try {
TodorooCursor<Update> updates = updateDao.query(Query.select(Update.PROPERTIES).where(
Criterion.and(Criterion.or(Update.UUID.eq(0), Update.UUID.isNull()), Criterion.or(Update.ACTION_CODE.eq(UserActivity.ACTION_TAG_COMMENT),
Update.ACTION_CODE.eq(UserActivity.ACTION_TASK_COMMENT)))));
try {
Update update = new Update();
UserActivity userActivity = new UserActivity();
for (updates.moveToFirst(); !updates.isAfterLast(); updates.moveToNext()) {
update.clear();
userActivity.clear();
update.readFromCursor(updates);
boolean setTarget = true;
if (!RemoteModel.isUuidEmpty(update.getValue(Update.TASK_UUID))) {
userActivity.setValue(UserActivity.TARGET_ID, update.getValue(Update.TASK_UUID));
} else if (update.getValue(Update.TASK_LOCAL) > 0) {
Task local = taskDao.fetch(update.getValue(Update.TASK_LOCAL), Task.UUID);
if (local != null && !RemoteModel.isUuidEmpty(local.getUuid()))
userActivity.setValue(UserActivity.TARGET_ID, local.getUuid());
else
setTarget = false;
} else {
setTarget = false;
}
if (setTarget) {
userActivity.setValue(UserActivity.USER_UUID, update.getValue(Update.USER_ID));
userActivity.setValue(UserActivity.ACTION, update.getValue(Update.ACTION_CODE));
userActivity.setValue(UserActivity.MESSAGE, update.getValue(Update.MESSAGE));
userActivity.setValue(UserActivity.CREATED_AT, update.getValue(Update.CREATION_DATE));
userActivityDao.createNew(userActivity);
}
}
} finally {
updates.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error migrating updates", e);
}
// --------------
// Drop any entries from the Users table that don't have a UUID
// --------------
try {
userDao.deleteWhere(Criterion.or(User.UUID.isNull(), User.UUID.eq(""), User.UUID.eq("0")));
} catch (Exception e) {
Log.e(LOG_TAG, "Error deleting incomplete user entries", e);
}
// --------------
// Migrate legacy FileMetadata models to new TaskAttachment models
// --------------
try {
TodorooCursor<Metadata> fmCursor = metadataService.query(Query.select(Metadata.PROPERTIES)
.where(MetadataCriteria.withKey(FileMetadata.METADATA_KEY)));
try {
System.err.println("FILES COUNT: " + fmCursor.getCount());
Metadata m = new Metadata();
for (fmCursor.moveToFirst(); !fmCursor.isAfterLast(); fmCursor.moveToNext()) {
m.clear();
m.readFromCursor(fmCursor);
TaskAttachment attachment = new TaskAttachment();
Task task = taskDao.fetch(m.getValue(Metadata.TASK), Task.UUID);
System.err.println("TASK UUID: " + task.getUuid());
if (task == null || !RemoteModel.isValidUuid(task.getUuid()))
continue;
Long oldRemoteId = m.getValue(FileMetadata.REMOTE_ID);
boolean synced = false;
if (oldRemoteId != null && oldRemoteId > 0) {
synced = true;
attachment.setValue(TaskAttachment.UUID, Long.toString(oldRemoteId));
}
System.err.println("ALREADY SYNCED: " + synced);
attachment.setValue(TaskAttachment.TASK_UUID, task.getUuid());
if (m.containsNonNullValue(FileMetadata.NAME))
attachment.setValue(TaskAttachment.NAME, m.getValue(FileMetadata.NAME));
if (m.containsNonNullValue(FileMetadata.URL))
attachment.setValue(TaskAttachment.URL, m.getValue(FileMetadata.URL));
if (m.containsNonNullValue(FileMetadata.FILE_PATH))
attachment.setValue(TaskAttachment.FILE_PATH, m.getValue(FileMetadata.FILE_PATH));
if (m.containsNonNullValue(FileMetadata.FILE_TYPE))
attachment.setValue(TaskAttachment.CONTENT_TYPE, m.getValue(FileMetadata.FILE_TYPE));
if (m.containsNonNullValue(FileMetadata.DELETION_DATE))
attachment.setValue(TaskAttachment.DELETED_AT, m.getValue(FileMetadata.DELETION_DATE));
if (synced) {
System.err.println("ATTACHMENT UUID: " + attachment.getValue(TaskAttachment.UUID));
attachment.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
}
taskAttachmentDao.createNew(attachment);
}
} finally {
fmCursor.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error migrating task attachment metadata", e);
}
// --------------
// Finally, ensure that all tag metadata entities have all important fields filled in
// --------------
try {
Query incompleteQuery = Query.select(Metadata.PROPERTIES).where(Criterion.and(
MetadataCriteria.withKey(TaskToTagMetadata.KEY),
Criterion.or(TaskToTagMetadata.TASK_UUID.eq(0), TaskToTagMetadata.TASK_UUID.isNull(),
TaskToTagMetadata.TAG_UUID.eq(0), TaskToTagMetadata.TAG_UUID.isNull())));
TodorooCursor<Metadata> incompleteMetadata = metadataService.query(incompleteQuery);
try {
Metadata m = new Metadata();
for (incompleteMetadata.moveToFirst(); !incompleteMetadata.isAfterLast(); incompleteMetadata.moveToNext()) {
m.clear(); // Need this since some properties may be null
m.readFromCursor(incompleteMetadata);
boolean changes = false;
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "Incomplete linking task " + m.getValue(Metadata.TASK) + " to " + m.getValue(TaskToTagMetadata.TAG_NAME));
if (!m.containsNonNullValue(TaskToTagMetadata.TASK_UUID) || RemoteModel.isUuidEmpty(m.getValue(TaskToTagMetadata.TASK_UUID))) {
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "No task uuid");
updateTaskUuid(m);
changes = true;
}
if (!m.containsNonNullValue(TaskToTagMetadata.TAG_UUID) || RemoteModel.isUuidEmpty(m.getValue(TaskToTagMetadata.TAG_UUID))) {
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "No tag uuid");
updateTagUuid(m);
changes = true;
}
if (changes)
metadataService.save(m);
}
} finally {
incompleteMetadata.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error validating task to tag metadata", e);
}
Preferences.setBoolean(PREF_SYNC_MIGRATION, true);
ActFmSyncMonitor monitor = ActFmSyncMonitor.getInstance();
synchronized (monitor) {
monitor.notifyAll();
}
}
| public void performMigration() {
if (Preferences.getBoolean(PREF_SYNC_MIGRATION, false))
return;
// --------------
// First ensure that a TagData object exists for each tag metadata
// --------------
try {
Query noTagDataQuery = Query.select(Metadata.PROPERTIES).where(Criterion.and(
MetadataCriteria.withKey(TaskToTagMetadata.KEY),
Criterion.or(TaskToTagMetadata.TAG_UUID.isNull(), TaskToTagMetadata.TAG_UUID.eq(0)),
Criterion.not(TaskToTagMetadata.TAG_NAME.in(Query.select(TagData.NAME).from(TagData.TABLE))))).groupBy(TaskToTagMetadata.TAG_NAME);
TodorooCursor<Metadata> noTagData = metadataService.query(noTagDataQuery);
try {
Metadata tag = new Metadata();
for (noTagData.moveToFirst(); !noTagData.isAfterLast(); noTagData.moveToNext()) {
tag.readFromCursor(noTagData);
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "CREATING TAG DATA " + tag.getValue(TaskToTagMetadata.TAG_NAME));
TagData newTagData = new TagData();
newTagData.setValue(TagData.NAME, tag.getValue(TaskToTagMetadata.TAG_NAME));
tagDataService.save(newTagData);
}
} finally {
noTagData.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error creating tag data", e);
}
// --------------
// Delete all emergent tag data, we don't need it
// --------------
try {
TodorooCursor<TagData> emergentTags = tagDataDao.query(Query.select(TagData.ID, TagData.NAME).where(Functions.bitwiseAnd(TagData.FLAGS, TagData.FLAG_EMERGENT).gt(0)));
try {
TagData td = new TagData();
for (emergentTags.moveToFirst(); !emergentTags.isAfterLast(); emergentTags.moveToNext()) {
td.clear();
td.readFromCursor(emergentTags);
String name = td.getValue(TagData.NAME);
tagDataDao.delete(td.getId());
if (!TextUtils.isEmpty(name))
metadataService.deleteWhere(Criterion.and(MetadataCriteria.withKey(TaskToTagMetadata.KEY), TaskToTagMetadata.TAG_NAME.eq(name)));
}
} finally {
emergentTags.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error clearing emergent tags");
}
// --------------
// Then ensure that every remote model has a remote id, by generating one using the uuid generator for all those without one
// --------------
final Set<Long> tasksThatNeedTagSync = new HashSet<Long>();
try {
Query tagsQuery = Query.select(TagData.ID, TagData.UUID, TagData.MODIFICATION_DATE).where(Criterion.or(TagData.UUID.eq(RemoteModel.NO_UUID), TagData.UUID.isNull()));
assertUUIDsExist(tagsQuery, new TagData(), tagDataDao, tagOutstandingDao, new TagOutstanding(), NameMaps.syncableProperties(NameMaps.TABLE_ID_TAGS), new UUIDAssertionExtras<TagData>() {
private static final String LAST_TAG_FETCH_TIME = "actfm_lastTag"; //$NON-NLS-1$
private final long lastFetchTime = Preferences.getInt(LAST_TAG_FETCH_TIME, 0) * 1000L;
@Override
public void beforeSave(TagData instance) {/**/}
@Override
public boolean shouldCreateOutstandingEntries(TagData instance) {
return lastFetchTime == 0 || (instance.containsNonNullValue(TagData.MODIFICATION_DATE) && instance.getValue(TagData.MODIFICATION_DATE) > lastFetchTime);
}
});
Query tasksQuery = Query.select(Task.ID, Task.UUID, Task.RECURRENCE, Task.FLAGS, Task.MODIFICATION_DATE, Task.LAST_SYNC).where(Criterion.all);
assertUUIDsExist(tasksQuery, new Task(), taskDao, taskOutstandingDao, new TaskOutstanding(), NameMaps.syncableProperties(NameMaps.TABLE_ID_TASKS), new UUIDAssertionExtras<Task>() {
@Override
public void beforeSave(Task instance) {
if (instance.getFlag(Task.FLAGS, Task.FLAG_IS_READONLY)) {
instance.setFlag(Task.FLAGS, Task.FLAG_IS_READONLY, false);
instance.setValue(Task.IS_READONLY, 1);
}
if (instance.getFlag(Task.FLAGS, Task.FLAG_PUBLIC)) {
instance.setFlag(Task.FLAGS, Task.FLAG_PUBLIC, false);
instance.setValue(Task.IS_PUBLIC, 1);
}
String recurrence = instance.getValue(Task.RECURRENCE);
if (!TextUtils.isEmpty(recurrence)) {
boolean repeatAfterCompletion = instance.getFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION);
instance.setFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION, false);
recurrence = recurrence.replaceAll("BYDAY=;", "");
if (repeatAfterCompletion)
recurrence = recurrence + ";FROM=COMPLETION";
instance.setValue(Task.RECURRENCE, recurrence);
}
}
@Override
public boolean shouldCreateOutstandingEntries(Task instance) {
boolean result;
if (!instance.containsNonNullValue(Task.MODIFICATION_DATE) || instance.getValue(Task.LAST_SYNC) == 0)
result = true;
else
result = instance.getValue(Task.LAST_SYNC) < instance.getValue(Task.MODIFICATION_DATE);
if (result)
tasksThatNeedTagSync.add(instance.getId());
return result;
}
});
} catch (Exception e) {
Log.e(LOG_TAG, "Error asserting UUIDs", e);
}
// --------------
// Migrate unsynced task comments to UserActivity table
// --------------
try {
TodorooCursor<Update> updates = updateDao.query(Query.select(Update.PROPERTIES).where(
Criterion.and(Criterion.or(Update.UUID.eq(0), Update.UUID.isNull()), Criterion.or(Update.ACTION_CODE.eq(UserActivity.ACTION_TAG_COMMENT),
Update.ACTION_CODE.eq(UserActivity.ACTION_TASK_COMMENT)))));
try {
Update update = new Update();
UserActivity userActivity = new UserActivity();
for (updates.moveToFirst(); !updates.isAfterLast(); updates.moveToNext()) {
update.clear();
userActivity.clear();
update.readFromCursor(updates);
boolean setTarget = true;
if (!RemoteModel.isUuidEmpty(update.getValue(Update.TASK_UUID))) {
userActivity.setValue(UserActivity.TARGET_ID, update.getValue(Update.TASK_UUID));
} else if (update.getValue(Update.TASK_LOCAL) > 0) {
Task local = taskDao.fetch(update.getValue(Update.TASK_LOCAL), Task.UUID);
if (local != null && !RemoteModel.isUuidEmpty(local.getUuid()))
userActivity.setValue(UserActivity.TARGET_ID, local.getUuid());
else
setTarget = false;
} else {
setTarget = false;
}
if (setTarget) {
userActivity.setValue(UserActivity.USER_UUID, update.getValue(Update.USER_ID));
userActivity.setValue(UserActivity.ACTION, update.getValue(Update.ACTION_CODE));
userActivity.setValue(UserActivity.MESSAGE, update.getValue(Update.MESSAGE));
userActivity.setValue(UserActivity.CREATED_AT, update.getValue(Update.CREATION_DATE));
userActivityDao.createNew(userActivity);
}
}
} finally {
updates.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error migrating updates", e);
}
// --------------
// Drop any entries from the Users table that don't have a UUID
// --------------
try {
userDao.deleteWhere(Criterion.or(User.UUID.isNull(), User.UUID.eq(""), User.UUID.eq("0")));
} catch (Exception e) {
Log.e(LOG_TAG, "Error deleting incomplete user entries", e);
}
// --------------
// Migrate legacy FileMetadata models to new TaskAttachment models
// --------------
try {
TodorooCursor<Metadata> fmCursor = metadataService.query(Query.select(Metadata.PROPERTIES)
.where(MetadataCriteria.withKey(FileMetadata.METADATA_KEY)));
try {
System.err.println("FILES COUNT: " + fmCursor.getCount());
Metadata m = new Metadata();
for (fmCursor.moveToFirst(); !fmCursor.isAfterLast(); fmCursor.moveToNext()) {
m.clear();
m.readFromCursor(fmCursor);
TaskAttachment attachment = new TaskAttachment();
Task task = taskDao.fetch(m.getValue(Metadata.TASK), Task.UUID);
System.err.println("TASK UUID: " + task.getUuid());
if (task == null || !RemoteModel.isValidUuid(task.getUuid()))
continue;
Long oldRemoteId = m.getValue(FileMetadata.REMOTE_ID);
boolean synced = false;
if (oldRemoteId != null && oldRemoteId > 0) {
synced = true;
attachment.setValue(TaskAttachment.UUID, Long.toString(oldRemoteId));
}
System.err.println("ALREADY SYNCED: " + synced);
attachment.setValue(TaskAttachment.TASK_UUID, task.getUuid());
if (m.containsNonNullValue(FileMetadata.NAME))
attachment.setValue(TaskAttachment.NAME, m.getValue(FileMetadata.NAME));
if (m.containsNonNullValue(FileMetadata.URL))
attachment.setValue(TaskAttachment.URL, m.getValue(FileMetadata.URL));
if (m.containsNonNullValue(FileMetadata.FILE_PATH))
attachment.setValue(TaskAttachment.FILE_PATH, m.getValue(FileMetadata.FILE_PATH));
if (m.containsNonNullValue(FileMetadata.FILE_TYPE))
attachment.setValue(TaskAttachment.CONTENT_TYPE, m.getValue(FileMetadata.FILE_TYPE));
if (m.containsNonNullValue(FileMetadata.DELETION_DATE))
attachment.setValue(TaskAttachment.DELETED_AT, m.getValue(FileMetadata.DELETION_DATE));
if (synced) {
System.err.println("ATTACHMENT UUID: " + attachment.getValue(TaskAttachment.UUID));
attachment.putTransitory(SyncFlags.ACTFM_SUPPRESS_OUTSTANDING_ENTRIES, true);
}
taskAttachmentDao.createNew(attachment);
}
} finally {
fmCursor.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error migrating task attachment metadata", e);
}
// --------------
// Finally, ensure that all tag metadata entities have all important fields filled in
// --------------
try {
Query incompleteQuery = Query.select(Metadata.PROPERTIES).where(Criterion.and(
MetadataCriteria.withKey(TaskToTagMetadata.KEY),
Criterion.or(TaskToTagMetadata.TASK_UUID.eq(0), TaskToTagMetadata.TASK_UUID.isNull(),
TaskToTagMetadata.TAG_UUID.eq(0), TaskToTagMetadata.TAG_UUID.isNull())));
TodorooCursor<Metadata> incompleteMetadata = metadataService.query(incompleteQuery);
try {
Metadata m = new Metadata();
for (incompleteMetadata.moveToFirst(); !incompleteMetadata.isAfterLast(); incompleteMetadata.moveToNext()) {
m.clear(); // Need this since some properties may be null
m.readFromCursor(incompleteMetadata);
boolean changes = false;
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "Incomplete linking task " + m.getValue(Metadata.TASK) + " to " + m.getValue(TaskToTagMetadata.TAG_NAME));
if (!m.containsNonNullValue(TaskToTagMetadata.TASK_UUID) || RemoteModel.isUuidEmpty(m.getValue(TaskToTagMetadata.TASK_UUID))) {
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "No task uuid");
updateTaskUuid(m);
changes = true;
}
if (!m.containsNonNullValue(TaskToTagMetadata.TAG_UUID) || RemoteModel.isUuidEmpty(m.getValue(TaskToTagMetadata.TAG_UUID))) {
if (ActFmInvoker.SYNC_DEBUG)
Log.w(LOG_TAG, "No tag uuid");
updateTagUuid(m);
changes = true;
}
if (changes)
metadataService.save(m);
}
} finally {
incompleteMetadata.close();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error validating task to tag metadata", e);
}
Preferences.setBoolean(PREF_SYNC_MIGRATION, true);
ActFmSyncMonitor monitor = ActFmSyncMonitor.getInstance();
synchronized (monitor) {
monitor.notifyAll();
}
}
|
diff --git a/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageInRegistryFinder.java b/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageInRegistryFinder.java
index 2c6044161..1a181f179 100644
--- a/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageInRegistryFinder.java
+++ b/org.emftext.sdk/src/org/emftext/sdk/finders/GenPackageInRegistryFinder.java
@@ -1,162 +1,162 @@
/*******************************************************************************
* Copyright (c) 2006-2010
* Software Technology Group, Dresden University of Technology
*
* 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:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.sdk.finders;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
import org.eclipse.emf.codegen.ecore.genmodel.GenPackage;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.emftext.sdk.EMFTextSDKPlugin;
import org.emftext.sdk.concretesyntax.GenPackageDependentElement;
/**
* A finder that looks up generator packages in the EMF package
* registry. This implementation queries the registry once at its first usage
* and loads and caches all valid generator packages.
*/
public class GenPackageInRegistryFinder implements IGenPackageFinder {
private static final Map<String, GenPackageInRegistry> cache = new HashMap<String, GenPackageInRegistry>();
private static boolean isInitialized = false;
private static void init() {
synchronized (GenPackageInRegistryFinder.class) {
if (!isInitialized) {
//search all registered generator models
final Map<String, URI> packageNsURIToGenModelLocationMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap();
for (String nextNS : packageNsURIToGenModelLocationMap.keySet()) {
URI genModelURI = packageNsURIToGenModelLocationMap.get(nextNS);
try {
final ResourceSet rs = new ResourceSetImpl();
Resource genModelResource = rs.getResource(genModelURI, true);
if (genModelResource == null) {
continue;
}
final EList<EObject> contents = genModelResource.getContents();
if (contents == null || contents.size() == 0) {
continue;
}
GenModel genModel = (GenModel) contents.get(0);
for (GenPackage genPackage : genModel.getGenPackages()) {
if (genPackage != null && !genPackage.eIsProxy()) {
String nsURI = genPackage.getNSURI();
final GenPackageInRegistry result = new GenPackageInRegistry(genPackage);
cache.put(nsURI, result);
registerSubGenPackages(genPackage);
}
}
} catch (Exception e) {
String uriString = genModelURI.toString();
// ignore FileNotFoundException caused by the org.eclipse.m2m.qvt.oml plug-in
// this plug-in does not contain the generator models it registers
// this is a workaround for Eclipse Bug 288208
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=288208
//
// do also ignore FileNotFoundException caused by some ATL plug-ins
// this is a workaround for Eclipse Bug 315376
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=315376
//
// do also ignore FileNotFoundException caused by some xText plug-ins
// this is a workaround for Eclipse Bug 315986
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=315986
//
// do also ignore FileNotFoundException caused by CDO
// this is a workaround for Eclipse Bug 317821
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=317821
//
- // do also ignore FileNotFoundException cased by MOFScript
+ // do also ignore FileNotFoundException caused by MOFScript
// This is a workaround for Eclipse Bug 322642
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=322642
//
// do also ignore FileNotFoundException caused by some pure::variants plug-ins
if (!uriString.startsWith("platform:/plugin/com.ps.consul.eclipse.ecore/src/pvmeta.genmodel") &&
!uriString.startsWith("platform:/plugin/com.ps.consul.eclipse.ecore/src/pvmodel.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.emf.cdo/model/resource.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.emf.mwe2.language/model/Mwe2.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.m2m.qvt.oml") &&
!uriString.startsWith("platform:/plugin/org.eclipse.m2m.atl.profiler.exportmodel/model/exportmodel.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.m2m.atl.profiler.model/model/ATL-Profiler.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.mofscript.model/src/model/mofscriptmodel.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.xtext/model/xtext.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.xtext.builder/model/BuilderState.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.xtext.xbase/org/eclipse/xtext/xbase/Xbase.genmodel")
) {
EMFTextSDKPlugin.logWarning("Exception while looking up generator model (" + nextNS + ") at " + uriString + " in the registry.", e);
}
}
}
isInitialized = true;
}
}
}
private static void registerSubGenPackages(GenPackage parentPackage) {
for(GenPackage genPackage : parentPackage.getSubGenPackages()) {
if (genPackage != null && !genPackage.eIsProxy()) {
String nsURI = genPackage.getNSURI();
final GenPackageInRegistry result = new GenPackageInRegistry(genPackage);
cache.put(nsURI, result);
registerSubGenPackages(genPackage);
}
}
}
/**
* An implementation of the IResolvedGenPackage that is used to
* return generator package found in the EMF registry.
*/
private static class GenPackageInRegistry implements IResolvedGenPackage {
private GenPackage genPackage;
public GenPackageInRegistry(GenPackage genPackage) {
Assert.isNotNull(genPackage);
this.genPackage = genPackage;
}
public boolean hasChanged() {
return false;
}
public GenPackage getResult() {
return genPackage;
}
}
public Collection<IResolvedGenPackage> findGenPackages(String nsURI, String locationHint, GenPackageDependentElement container, Resource resource, boolean resolveFuzzy) {
init();
Collection<IResolvedGenPackage> result = new LinkedHashSet<IResolvedGenPackage>();
for (String nextNsURI : cache.keySet()) {
if (nextNsURI == null) {
continue;
}
if (nextNsURI.equals(nsURI) || resolveFuzzy) {
result.add(cache.get(nextNsURI));
}
}
return result;
}
}
| true | true | private static void init() {
synchronized (GenPackageInRegistryFinder.class) {
if (!isInitialized) {
//search all registered generator models
final Map<String, URI> packageNsURIToGenModelLocationMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap();
for (String nextNS : packageNsURIToGenModelLocationMap.keySet()) {
URI genModelURI = packageNsURIToGenModelLocationMap.get(nextNS);
try {
final ResourceSet rs = new ResourceSetImpl();
Resource genModelResource = rs.getResource(genModelURI, true);
if (genModelResource == null) {
continue;
}
final EList<EObject> contents = genModelResource.getContents();
if (contents == null || contents.size() == 0) {
continue;
}
GenModel genModel = (GenModel) contents.get(0);
for (GenPackage genPackage : genModel.getGenPackages()) {
if (genPackage != null && !genPackage.eIsProxy()) {
String nsURI = genPackage.getNSURI();
final GenPackageInRegistry result = new GenPackageInRegistry(genPackage);
cache.put(nsURI, result);
registerSubGenPackages(genPackage);
}
}
} catch (Exception e) {
String uriString = genModelURI.toString();
// ignore FileNotFoundException caused by the org.eclipse.m2m.qvt.oml plug-in
// this plug-in does not contain the generator models it registers
// this is a workaround for Eclipse Bug 288208
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=288208
//
// do also ignore FileNotFoundException caused by some ATL plug-ins
// this is a workaround for Eclipse Bug 315376
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=315376
//
// do also ignore FileNotFoundException caused by some xText plug-ins
// this is a workaround for Eclipse Bug 315986
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=315986
//
// do also ignore FileNotFoundException caused by CDO
// this is a workaround for Eclipse Bug 317821
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=317821
//
// do also ignore FileNotFoundException cased by MOFScript
// This is a workaround for Eclipse Bug 322642
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=322642
//
// do also ignore FileNotFoundException caused by some pure::variants plug-ins
if (!uriString.startsWith("platform:/plugin/com.ps.consul.eclipse.ecore/src/pvmeta.genmodel") &&
!uriString.startsWith("platform:/plugin/com.ps.consul.eclipse.ecore/src/pvmodel.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.emf.cdo/model/resource.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.emf.mwe2.language/model/Mwe2.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.m2m.qvt.oml") &&
!uriString.startsWith("platform:/plugin/org.eclipse.m2m.atl.profiler.exportmodel/model/exportmodel.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.m2m.atl.profiler.model/model/ATL-Profiler.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.mofscript.model/src/model/mofscriptmodel.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.xtext/model/xtext.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.xtext.builder/model/BuilderState.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.xtext.xbase/org/eclipse/xtext/xbase/Xbase.genmodel")
) {
EMFTextSDKPlugin.logWarning("Exception while looking up generator model (" + nextNS + ") at " + uriString + " in the registry.", e);
}
}
}
isInitialized = true;
}
}
}
| private static void init() {
synchronized (GenPackageInRegistryFinder.class) {
if (!isInitialized) {
//search all registered generator models
final Map<String, URI> packageNsURIToGenModelLocationMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap();
for (String nextNS : packageNsURIToGenModelLocationMap.keySet()) {
URI genModelURI = packageNsURIToGenModelLocationMap.get(nextNS);
try {
final ResourceSet rs = new ResourceSetImpl();
Resource genModelResource = rs.getResource(genModelURI, true);
if (genModelResource == null) {
continue;
}
final EList<EObject> contents = genModelResource.getContents();
if (contents == null || contents.size() == 0) {
continue;
}
GenModel genModel = (GenModel) contents.get(0);
for (GenPackage genPackage : genModel.getGenPackages()) {
if (genPackage != null && !genPackage.eIsProxy()) {
String nsURI = genPackage.getNSURI();
final GenPackageInRegistry result = new GenPackageInRegistry(genPackage);
cache.put(nsURI, result);
registerSubGenPackages(genPackage);
}
}
} catch (Exception e) {
String uriString = genModelURI.toString();
// ignore FileNotFoundException caused by the org.eclipse.m2m.qvt.oml plug-in
// this plug-in does not contain the generator models it registers
// this is a workaround for Eclipse Bug 288208
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=288208
//
// do also ignore FileNotFoundException caused by some ATL plug-ins
// this is a workaround for Eclipse Bug 315376
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=315376
//
// do also ignore FileNotFoundException caused by some xText plug-ins
// this is a workaround for Eclipse Bug 315986
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=315986
//
// do also ignore FileNotFoundException caused by CDO
// this is a workaround for Eclipse Bug 317821
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=317821
//
// do also ignore FileNotFoundException caused by MOFScript
// This is a workaround for Eclipse Bug 322642
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=322642
//
// do also ignore FileNotFoundException caused by some pure::variants plug-ins
if (!uriString.startsWith("platform:/plugin/com.ps.consul.eclipse.ecore/src/pvmeta.genmodel") &&
!uriString.startsWith("platform:/plugin/com.ps.consul.eclipse.ecore/src/pvmodel.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.emf.cdo/model/resource.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.emf.mwe2.language/model/Mwe2.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.m2m.qvt.oml") &&
!uriString.startsWith("platform:/plugin/org.eclipse.m2m.atl.profiler.exportmodel/model/exportmodel.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.m2m.atl.profiler.model/model/ATL-Profiler.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.mofscript.model/src/model/mofscriptmodel.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.xtext/model/xtext.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.xtext.builder/model/BuilderState.genmodel") &&
!uriString.startsWith("platform:/plugin/org.eclipse.xtext.xbase/org/eclipse/xtext/xbase/Xbase.genmodel")
) {
EMFTextSDKPlugin.logWarning("Exception while looking up generator model (" + nextNS + ") at " + uriString + " in the registry.", e);
}
}
}
isInitialized = true;
}
}
}
|
diff --git a/CustomSpawners/src/com/github/thebiologist13/commands/entities/EntityVelocityCommand.java b/CustomSpawners/src/com/github/thebiologist13/commands/entities/EntityVelocityCommand.java
index c806cb3..887cd44 100644
--- a/CustomSpawners/src/com/github/thebiologist13/commands/entities/EntityVelocityCommand.java
+++ b/CustomSpawners/src/com/github/thebiologist13/commands/entities/EntityVelocityCommand.java
@@ -1,132 +1,132 @@
package com.github.thebiologist13.commands.entities;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import com.github.thebiologist13.CustomSpawners;
import com.github.thebiologist13.SpawnableEntity;
import com.github.thebiologist13.commands.SpawnerCommand;
public class EntityVelocityCommand extends SpawnerCommand {
private CustomSpawners plugin = null;
private Logger log = null;
public EntityVelocityCommand(CustomSpawners plugin) {
this.plugin = plugin;
this.log = plugin.log;
}
@Override
public void run(CommandSender arg0, Command arg1, String arg2, String[] arg3) {
//Command Syntax = /customspawners setvelocity [id] <x,y,z>
//Array Index with selection 0 1
//Without selection 0 1 2
//Player
Player p = null;
//Entity
SpawnableEntity s = null;
//Vector components
double x = 0;
double y = 0;
double z = 0;
//Permissions
String perm = "customspawners.entities.setvelocity";
final String COMMAND_FORMAT = ChatColor.RED + "Invalid values for velocity. Please use the following format: " +
ChatColor.GOLD + "/entities setvelocity <x value>,<y value>,<z value>.";
if(!(arg0 instanceof Player)) {
log.info(NO_CONSOLE);
return;
}
p = (Player) arg0;
if(p.hasPermission(perm)) {
if(CustomSpawners.entitySelection.containsKey(p) && arg3.length == 2) {
s = plugin.getEntityById(CustomSpawners.entitySelection.get(p));
int firstCommaIndex = arg3[1].indexOf(",");
int secondCommaIndex = arg3[1].indexOf(",", firstCommaIndex + 1);
String xVal = arg3[1].substring(0, firstCommaIndex);
String yVal = arg3[1].substring(firstCommaIndex + 1, secondCommaIndex);
String zVal = arg3[1].substring(secondCommaIndex + 1, arg3[1].length());
if(!plugin.isDouble(xVal) || !plugin.isDouble(yVal) || !plugin.isDouble(zVal)) {
p.sendMessage(COMMAND_FORMAT);
return;
}
x = Double.parseDouble(xVal);
y = Double.parseDouble(yVal);
z = Double.parseDouble(zVal);
} else if(arg3.length == 2) {
p.sendMessage(NEEDS_SELECTION);
return;
} else if(arg3.length == 3) {
int id = 0;
//Check that the ID entered is a number
if(!plugin.isInteger(arg3[1])) {
p.sendMessage(ID_NOT_NUMBER);
return;
}
id = Integer.parseInt(arg3[1]);
//Check if the ID entered is the ID of a entity
if(!plugin.isValidEntity(id)) {
p.sendMessage(NO_ID);
return;
}
s = plugin.getEntityById(id);
int firstCommaIndex = arg3[2].indexOf(",");
int secondCommaIndex = arg3[2].indexOf(",", firstCommaIndex + 1);
String xVal = arg3[2].substring(0, firstCommaIndex);
String yVal = arg3[2].substring(firstCommaIndex + 1, secondCommaIndex);
String zVal = arg3[2].substring(secondCommaIndex + 1, arg3[2].length());
if(!plugin.isDouble(xVal) ||!plugin.isDouble(yVal) || !plugin.isDouble(zVal)) {
p.sendMessage(COMMAND_FORMAT);
return;
}
- x = Integer.parseInt(xVal);
- y = Integer.parseInt(yVal);
- z = Integer.parseInt(zVal);
+ x = Double.parseDouble(xVal);
+ y = Double.parseDouble(yVal);
+ z = Double.parseDouble(zVal);
} else {
p.sendMessage(GENERAL_ERROR);
return;
}
//Carry out command
s.setVelocity(new Vector(x,y,z));
//Success
p.sendMessage(ChatColor.GREEN + "Successfully set the velocity of spawnable entity with ID "
+ ChatColor.GOLD + s.getId() + ChatColor.GREEN + " to " + ChatColor.GOLD
+ "(" + x + "," + y + "," + z + ")" + ChatColor.GREEN + "!");
} else {
p.sendMessage(NO_PERMISSION);
return;
}
}
}
| true | true | public void run(CommandSender arg0, Command arg1, String arg2, String[] arg3) {
//Command Syntax = /customspawners setvelocity [id] <x,y,z>
//Array Index with selection 0 1
//Without selection 0 1 2
//Player
Player p = null;
//Entity
SpawnableEntity s = null;
//Vector components
double x = 0;
double y = 0;
double z = 0;
//Permissions
String perm = "customspawners.entities.setvelocity";
final String COMMAND_FORMAT = ChatColor.RED + "Invalid values for velocity. Please use the following format: " +
ChatColor.GOLD + "/entities setvelocity <x value>,<y value>,<z value>.";
if(!(arg0 instanceof Player)) {
log.info(NO_CONSOLE);
return;
}
p = (Player) arg0;
if(p.hasPermission(perm)) {
if(CustomSpawners.entitySelection.containsKey(p) && arg3.length == 2) {
s = plugin.getEntityById(CustomSpawners.entitySelection.get(p));
int firstCommaIndex = arg3[1].indexOf(",");
int secondCommaIndex = arg3[1].indexOf(",", firstCommaIndex + 1);
String xVal = arg3[1].substring(0, firstCommaIndex);
String yVal = arg3[1].substring(firstCommaIndex + 1, secondCommaIndex);
String zVal = arg3[1].substring(secondCommaIndex + 1, arg3[1].length());
if(!plugin.isDouble(xVal) || !plugin.isDouble(yVal) || !plugin.isDouble(zVal)) {
p.sendMessage(COMMAND_FORMAT);
return;
}
x = Double.parseDouble(xVal);
y = Double.parseDouble(yVal);
z = Double.parseDouble(zVal);
} else if(arg3.length == 2) {
p.sendMessage(NEEDS_SELECTION);
return;
} else if(arg3.length == 3) {
int id = 0;
//Check that the ID entered is a number
if(!plugin.isInteger(arg3[1])) {
p.sendMessage(ID_NOT_NUMBER);
return;
}
id = Integer.parseInt(arg3[1]);
//Check if the ID entered is the ID of a entity
if(!plugin.isValidEntity(id)) {
p.sendMessage(NO_ID);
return;
}
s = plugin.getEntityById(id);
int firstCommaIndex = arg3[2].indexOf(",");
int secondCommaIndex = arg3[2].indexOf(",", firstCommaIndex + 1);
String xVal = arg3[2].substring(0, firstCommaIndex);
String yVal = arg3[2].substring(firstCommaIndex + 1, secondCommaIndex);
String zVal = arg3[2].substring(secondCommaIndex + 1, arg3[2].length());
if(!plugin.isDouble(xVal) ||!plugin.isDouble(yVal) || !plugin.isDouble(zVal)) {
p.sendMessage(COMMAND_FORMAT);
return;
}
x = Integer.parseInt(xVal);
y = Integer.parseInt(yVal);
z = Integer.parseInt(zVal);
} else {
p.sendMessage(GENERAL_ERROR);
return;
}
//Carry out command
s.setVelocity(new Vector(x,y,z));
//Success
p.sendMessage(ChatColor.GREEN + "Successfully set the velocity of spawnable entity with ID "
+ ChatColor.GOLD + s.getId() + ChatColor.GREEN + " to " + ChatColor.GOLD
+ "(" + x + "," + y + "," + z + ")" + ChatColor.GREEN + "!");
} else {
p.sendMessage(NO_PERMISSION);
return;
}
}
| public void run(CommandSender arg0, Command arg1, String arg2, String[] arg3) {
//Command Syntax = /customspawners setvelocity [id] <x,y,z>
//Array Index with selection 0 1
//Without selection 0 1 2
//Player
Player p = null;
//Entity
SpawnableEntity s = null;
//Vector components
double x = 0;
double y = 0;
double z = 0;
//Permissions
String perm = "customspawners.entities.setvelocity";
final String COMMAND_FORMAT = ChatColor.RED + "Invalid values for velocity. Please use the following format: " +
ChatColor.GOLD + "/entities setvelocity <x value>,<y value>,<z value>.";
if(!(arg0 instanceof Player)) {
log.info(NO_CONSOLE);
return;
}
p = (Player) arg0;
if(p.hasPermission(perm)) {
if(CustomSpawners.entitySelection.containsKey(p) && arg3.length == 2) {
s = plugin.getEntityById(CustomSpawners.entitySelection.get(p));
int firstCommaIndex = arg3[1].indexOf(",");
int secondCommaIndex = arg3[1].indexOf(",", firstCommaIndex + 1);
String xVal = arg3[1].substring(0, firstCommaIndex);
String yVal = arg3[1].substring(firstCommaIndex + 1, secondCommaIndex);
String zVal = arg3[1].substring(secondCommaIndex + 1, arg3[1].length());
if(!plugin.isDouble(xVal) || !plugin.isDouble(yVal) || !plugin.isDouble(zVal)) {
p.sendMessage(COMMAND_FORMAT);
return;
}
x = Double.parseDouble(xVal);
y = Double.parseDouble(yVal);
z = Double.parseDouble(zVal);
} else if(arg3.length == 2) {
p.sendMessage(NEEDS_SELECTION);
return;
} else if(arg3.length == 3) {
int id = 0;
//Check that the ID entered is a number
if(!plugin.isInteger(arg3[1])) {
p.sendMessage(ID_NOT_NUMBER);
return;
}
id = Integer.parseInt(arg3[1]);
//Check if the ID entered is the ID of a entity
if(!plugin.isValidEntity(id)) {
p.sendMessage(NO_ID);
return;
}
s = plugin.getEntityById(id);
int firstCommaIndex = arg3[2].indexOf(",");
int secondCommaIndex = arg3[2].indexOf(",", firstCommaIndex + 1);
String xVal = arg3[2].substring(0, firstCommaIndex);
String yVal = arg3[2].substring(firstCommaIndex + 1, secondCommaIndex);
String zVal = arg3[2].substring(secondCommaIndex + 1, arg3[2].length());
if(!plugin.isDouble(xVal) ||!plugin.isDouble(yVal) || !plugin.isDouble(zVal)) {
p.sendMessage(COMMAND_FORMAT);
return;
}
x = Double.parseDouble(xVal);
y = Double.parseDouble(yVal);
z = Double.parseDouble(zVal);
} else {
p.sendMessage(GENERAL_ERROR);
return;
}
//Carry out command
s.setVelocity(new Vector(x,y,z));
//Success
p.sendMessage(ChatColor.GREEN + "Successfully set the velocity of spawnable entity with ID "
+ ChatColor.GOLD + s.getId() + ChatColor.GREEN + " to " + ChatColor.GOLD
+ "(" + x + "," + y + "," + z + ")" + ChatColor.GREEN + "!");
} else {
p.sendMessage(NO_PERMISSION);
return;
}
}
|
diff --git a/src/AdmVentas.java b/src/AdmVentas.java
index e5d0926..eee7906 100644
--- a/src/AdmVentas.java
+++ b/src/AdmVentas.java
@@ -1,86 +1,86 @@
import java.util.ArrayList;
public class AdmVentas {
private ArrayList<Ventas> doc;
public AdmVentas() {
doc = new ArrayList<Ventas>();
}
public void validarDatosIncompletos(String numero, String fecha_emision, String fecha_vencimiento, String empresa, String fecha_pago, String estado, String concepto, double subtotal, double igv, double total, String moneda) throws BusinessException {
String msg = "";
if (numero == null || numero.isEmpty())
msg = "El numero de documento no puede ser vacio o nulo";
if (fecha_emision == null || fecha_emision.isEmpty())
msg += "\nFecha de Emision no pueder ser vacio o nulo";
if (fecha_vencimiento == null || fecha_vencimiento.isEmpty())
msg += "\nFecha de vencimiento no pueder ser vacio o nulo";
if (! msg.isEmpty())
throw new BusinessException(msg);
}
public Ventas Fn_buscar(String numero) {
for(Ventas doc : fn_getDoc())
if (doc.getNumero().trim().equals(numero))
return doc;
return null;
}
public void validarDuplicidad(String numero) throws BusinessException {
if (Fn_buscar(numero) != null){
String msg = "Documento "+numero+ " ya existe.";
throw new BusinessException(msg);
}
}
private void validarExistenciaPersona(String numero)
throws BusinessException {
if (Fn_buscar(numero) == null){
String msg = "Numero de documento "+ numero + " no existe.";
throw new BusinessException(msg);
}
}
public void registrarDocumento(String numero, String fecha_emision, String fecha_vencimiento, String empresa, String fecha_pago, String estado, String concepto, double subtotal, double igv, double total, String moneda) throws BusinessException {
// Validar datos incompletos
validarDatosIncompletos(numero,fecha_emision,fecha_vencimiento,empresa,fecha_pago,estado,concepto,subtotal,igv,total,moneda);
// Validar que exista documento
validarDuplicidad(numero);
fn_getDoc().add(new Ventas(numero,fecha_emision,fecha_vencimiento,empresa,fecha_pago,estado,concepto,subtotal,igv,total,moneda));
}
public void eliminarDocumento(String numero) throws BusinessException {
validarExistenciaPersona(numero);
fn_getDoc().remove(Fn_buscar(numero));
}
public void editarDocumento(String numero, String fecha_emision, String fecha_vencimiento, String empresa, String fecha_pago, String estado, String concepto, double subtotal, double igv, double total, String moneda) throws BusinessException {
Ventas oven= Fn_buscar(numero);
oven.setFecha_vencimiento(fecha_vencimiento);
oven.setFecha_vencimiento(fecha_vencimiento);
oven.setEmpresa(empresa);
oven.setFecha_pago(fecha_pago);
- oven.
+ /* oven.
oven.setS_pais(S_pais);
oven.setS_nombres(S_nombres);
oven.setS_apellidos(S_apellidos);
oven.setS_pasaporte(S_pasaporte);
oven.setS_sexo(S_sexo);
oven.setD_fechacumpleanos(D_fechacumpleanos);
- oven.setS_comentario(S_comentario);
+ oven.setS_comentario(S_comentario);*/
}
public ArrayList<Ventas> fn_getDoc() {
return doc;
}
}
| false | true | public void editarDocumento(String numero, String fecha_emision, String fecha_vencimiento, String empresa, String fecha_pago, String estado, String concepto, double subtotal, double igv, double total, String moneda) throws BusinessException {
Ventas oven= Fn_buscar(numero);
oven.setFecha_vencimiento(fecha_vencimiento);
oven.setFecha_vencimiento(fecha_vencimiento);
oven.setEmpresa(empresa);
oven.setFecha_pago(fecha_pago);
oven.
oven.setS_pais(S_pais);
oven.setS_nombres(S_nombres);
oven.setS_apellidos(S_apellidos);
oven.setS_pasaporte(S_pasaporte);
oven.setS_sexo(S_sexo);
oven.setD_fechacumpleanos(D_fechacumpleanos);
oven.setS_comentario(S_comentario);
}
| public void editarDocumento(String numero, String fecha_emision, String fecha_vencimiento, String empresa, String fecha_pago, String estado, String concepto, double subtotal, double igv, double total, String moneda) throws BusinessException {
Ventas oven= Fn_buscar(numero);
oven.setFecha_vencimiento(fecha_vencimiento);
oven.setFecha_vencimiento(fecha_vencimiento);
oven.setEmpresa(empresa);
oven.setFecha_pago(fecha_pago);
/* oven.
oven.setS_pais(S_pais);
oven.setS_nombres(S_nombres);
oven.setS_apellidos(S_apellidos);
oven.setS_pasaporte(S_pasaporte);
oven.setS_sexo(S_sexo);
oven.setD_fechacumpleanos(D_fechacumpleanos);
oven.setS_comentario(S_comentario);*/
}
|
diff --git a/src/com/diycomputerscience/minesweeper/view/UI.java b/src/com/diycomputerscience/minesweeper/view/UI.java
index 1c1dadb..3575fab 100644
--- a/src/com/diycomputerscience/minesweeper/view/UI.java
+++ b/src/com/diycomputerscience/minesweeper/view/UI.java
@@ -1,234 +1,234 @@
package com.diycomputerscience.minesweeper.view;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.InputStream;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.plaf.ColorUIResource;
import com.diycomputerscience.minesweeper.Board;
import com.diycomputerscience.minesweeper.FilePersistenceStrategy;
import com.diycomputerscience.minesweeper.PersistenceException;
import com.diycomputerscience.minesweeper.PersistenceStrategy;
import com.diycomputerscience.minesweeper.RandomMineInitializationStrategy;
import com.diycomputerscience.minesweeper.Square;
import com.diycomputerscience.minesweeper.UncoveredMineException;
public class UI extends JFrame {
private Board board;
private OptionPane optionPane;
private PersistenceStrategy peristenceStrategy;
private JPanel panel;
public UI(Board board, OptionPane optionPane, PersistenceStrategy persistenceStrategy) {
// set this.board to the injected Board
this.board = board;
this.optionPane = optionPane;
this.peristenceStrategy = persistenceStrategy;
// Set the title to "Minesweeper"
this.setTitle("title");
this.panel = new JPanel();
// Set the name of the panel to "MainPanel"
panel.setName("MainPanel");
// Set the layout of panel to GridLayout. Be sure to give it correct dimensions
panel.setLayout(new GridLayout(Board.MAX_ROWS, Board.MAX_COLS));
// add squares to the panel
this.layoutSquares(panel);
// add panel to the content pane
this.getContentPane().add(this.panel);
// set the menu bar
this.setJMenuBar(buildMenuBar());
// validate components
//this.validate();
}
public void load(Board board) {
this.board = board;
this.getContentPane().removeAll();
this.invalidate();
this.panel = new JPanel();
// Set the name of the panel to "MainPanel"
panel.setName("MainPanel");
// Set the layout of panel to GridLayout. Be sure to give it correct dimensions
panel.setLayout(new GridLayout(Board.MAX_ROWS, Board.MAX_COLS));
// add squares to the panel
this.layoutSquares(panel);
// add panel to the content pane
this.getContentPane().add(this.panel);
this.validate();
}
private void layoutSquares(JPanel panel) {
final Square squares[][] = this.board.getSquares();
for(int row=0; row<Board.MAX_ROWS; row++) {
for(int col=0; col<Board.MAX_COLS; col++) {
final JButton squareUI = new JButton();
squareUI.setName(row+","+col);
final int theRow = row;
final int theCol = col;
squareUI.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
// invoke the appropriate logic to affect this action (left or right mouse click)
if(SwingUtilities.isLeftMouseButton(me)) {
try {
UI.this.board.getSquares()[theRow][theCol].uncover();
} catch(UncoveredMineException ume) {
squareUI.setBackground(Color.RED);
String gameOverTitle = "Game Over Title";
String gameOverMsg = "Game Over Message";
int answer = optionPane.userConfirmation(UI.this, gameOverMsg, gameOverTitle, JOptionPane.YES_NO_OPTION);
if(answer == JOptionPane.YES_OPTION) {
Board board = new Board(new RandomMineInitializationStrategy());
load(board);
} else {
UI.this.dispose();
}
}
} else if(SwingUtilities.isRightMouseButton(me)) {
UI.this.board.getSquares()[theRow][theCol].mark();
}
// display the new state of the square
updateSquareUIDisplay(squareUI, UI.this.board.getSquares()[theRow][theCol]);
}
});
updateSquareUIDisplay(squareUI, UI.this.board.getSquares()[row][col]);
panel.add(squareUI);
}
}
}
private void updateSquareUIDisplay(JButton squareUI, Square square) {
if(square.getState().equals(Square.SquareState.UNCOVERED)) {
if(square.isMine()) {
squareUI.setBackground(ColorUIResource.RED);
} else {
squareUI.setText(String.valueOf(square.getCount()));
}
} else if(square.getState().equals(Square.SquareState.MARKED)) {
squareUI.setText("");
squareUI.setBackground(ColorUIResource.MAGENTA);
} else if(square.getState().equals(Square.SquareState.COVERED)) {
squareUI.setText("");
squareUI.setBackground(new ColorUIResource(238, 238, 238));
}
}
private JMenuBar buildMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("Menu File");
file.setName("file");
JMenuItem fileSave = new JMenuItem("Menu Item Save");
fileSave.setName("file-save");
fileSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
UI.this.peristenceStrategy.save(UI.this.board);
} catch(PersistenceException pe) {
System.out.println("Could not save the game" + pe);
}
}
});
JMenuItem fileLoad = new JMenuItem("Menu Item Load");
fileLoad.setName("file-load");
fileLoad.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
UI.this.load(UI.this.board = UI.this.peristenceStrategy.load());
} catch(PersistenceException pe) {
//TODO: error dialogue
//TODO: This button should be enabled only if a previously saved state exists
System.out.println("Could not load game from previously saved state");
}
}
});
JMenuItem close = new JMenuItem("Menu Item Close");
close.setName("file-close");
close.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
file.add(fileSave);
file.add(fileLoad);
file.add(close);
menuBar.add(file);
JMenu help = new JMenu("Menu Help");
help.setName("help");
JMenuItem helpAbout = new JMenuItem("Menu Item About");
help.add(helpAbout);
- help.setName("help-about");
+ helpAbout.setName("help-about");
menuBar.add(help);
return menuBar;
}
public static UI build(Board board, OptionPane optionPane, PersistenceStrategy persistenceStrategy) {
UI ui = new UI(board, optionPane, persistenceStrategy);
ui.setSize(300, 400);
ui.setVisible(true);
ui.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
return ui;
}
public static void main(String[] args) {
InputStream configIS = null;
try {
configIS = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties");
final Properties configProperties = new Properties();
configProperties.load(configIS);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
build(new Board(new RandomMineInitializationStrategy()),
new SwingOptionPane(),
new FilePersistenceStrategy(configProperties.getProperty("persistence.filename")));
}
});
} catch(IOException ioe) {
System.out.println("Quitting: Could not load filename for persistence... " + ioe);
}
}
}
| true | true | private JMenuBar buildMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("Menu File");
file.setName("file");
JMenuItem fileSave = new JMenuItem("Menu Item Save");
fileSave.setName("file-save");
fileSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
UI.this.peristenceStrategy.save(UI.this.board);
} catch(PersistenceException pe) {
System.out.println("Could not save the game" + pe);
}
}
});
JMenuItem fileLoad = new JMenuItem("Menu Item Load");
fileLoad.setName("file-load");
fileLoad.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
UI.this.load(UI.this.board = UI.this.peristenceStrategy.load());
} catch(PersistenceException pe) {
//TODO: error dialogue
//TODO: This button should be enabled only if a previously saved state exists
System.out.println("Could not load game from previously saved state");
}
}
});
JMenuItem close = new JMenuItem("Menu Item Close");
close.setName("file-close");
close.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
file.add(fileSave);
file.add(fileLoad);
file.add(close);
menuBar.add(file);
JMenu help = new JMenu("Menu Help");
help.setName("help");
JMenuItem helpAbout = new JMenuItem("Menu Item About");
help.add(helpAbout);
help.setName("help-about");
menuBar.add(help);
return menuBar;
}
| private JMenuBar buildMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("Menu File");
file.setName("file");
JMenuItem fileSave = new JMenuItem("Menu Item Save");
fileSave.setName("file-save");
fileSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
UI.this.peristenceStrategy.save(UI.this.board);
} catch(PersistenceException pe) {
System.out.println("Could not save the game" + pe);
}
}
});
JMenuItem fileLoad = new JMenuItem("Menu Item Load");
fileLoad.setName("file-load");
fileLoad.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
UI.this.load(UI.this.board = UI.this.peristenceStrategy.load());
} catch(PersistenceException pe) {
//TODO: error dialogue
//TODO: This button should be enabled only if a previously saved state exists
System.out.println("Could not load game from previously saved state");
}
}
});
JMenuItem close = new JMenuItem("Menu Item Close");
close.setName("file-close");
close.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
file.add(fileSave);
file.add(fileLoad);
file.add(close);
menuBar.add(file);
JMenu help = new JMenu("Menu Help");
help.setName("help");
JMenuItem helpAbout = new JMenuItem("Menu Item About");
help.add(helpAbout);
helpAbout.setName("help-about");
menuBar.add(help);
return menuBar;
}
|
diff --git a/src/com/android/launcher2/AppsCustomizeTabHost.java b/src/com/android/launcher2/AppsCustomizeTabHost.java
index af0f205d..0199d01c 100644
--- a/src/com/android/launcher2/AppsCustomizeTabHost.java
+++ b/src/com/android/launcher2/AppsCustomizeTabHost.java
@@ -1,477 +1,477 @@
/*
* 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.launcher2;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import com.android.launcher.R;
import java.util.ArrayList;
public class AppsCustomizeTabHost extends TabHost implements LauncherTransitionable,
TabHost.OnTabChangeListener {
static final String LOG_TAG = "AppsCustomizeTabHost";
private static final String APPS_TAB_TAG = "APPS";
private static final String WIDGETS_TAB_TAG = "WIDGETS";
private final LayoutInflater mLayoutInflater;
private ViewGroup mTabs;
private ViewGroup mTabsContainer;
private AppsCustomizePagedView mAppsCustomizePane;
private boolean mSuppressContentCallback = false;
private FrameLayout mAnimationBuffer;
private LinearLayout mContent;
private boolean mInTransition;
private boolean mTransitioningToWorkspace;
private boolean mResetAfterTransition;
private Runnable mRelayoutAndMakeVisible;
public AppsCustomizeTabHost(Context context, AttributeSet attrs) {
super(context, attrs);
mLayoutInflater = LayoutInflater.from(context);
mRelayoutAndMakeVisible = new Runnable() {
public void run() {
mTabs.requestLayout();
mTabsContainer.setAlpha(1f);
}
};
}
/**
* Convenience methods to select specific tabs. We want to set the content type immediately
* in these cases, but we note that we still call setCurrentTabByTag() so that the tab view
* reflects the new content (but doesn't do the animation and logic associated with changing
* tabs manually).
*/
private void setContentTypeImmediate(AppsCustomizePagedView.ContentType type) {
onTabChangedStart();
onTabChangedEnd(type);
}
void selectAppsTab() {
setContentTypeImmediate(AppsCustomizePagedView.ContentType.Applications);
setCurrentTabByTag(APPS_TAB_TAG);
}
void selectWidgetsTab() {
setContentTypeImmediate(AppsCustomizePagedView.ContentType.Widgets);
setCurrentTabByTag(WIDGETS_TAB_TAG);
}
/**
* Setup the tab host and create all necessary tabs.
*/
@Override
protected void onFinishInflate() {
// Setup the tab host
setup();
final ViewGroup tabsContainer = (ViewGroup) findViewById(R.id.tabs_container);
final TabWidget tabs = (TabWidget) findViewById(com.android.internal.R.id.tabs);
final AppsCustomizePagedView appsCustomizePane = (AppsCustomizePagedView)
findViewById(R.id.apps_customize_pane_content);
mTabs = tabs;
mTabsContainer = tabsContainer;
mAppsCustomizePane = appsCustomizePane;
mAnimationBuffer = (FrameLayout) findViewById(R.id.animation_buffer);
mContent = (LinearLayout) findViewById(R.id.apps_customize_content);
if (tabs == null || mAppsCustomizePane == null) throw new Resources.NotFoundException();
// Configure the tabs content factory to return the same paged view (that we change the
// content filter on)
TabContentFactory contentFactory = new TabContentFactory() {
public View createTabContent(String tag) {
return appsCustomizePane;
}
};
// Create the tabs
TextView tabView;
String label;
label = mContext.getString(R.string.all_apps_button_label);
tabView = (TextView) mLayoutInflater.inflate(R.layout.tab_widget_indicator, tabs, false);
tabView.setText(label);
tabView.setContentDescription(label);
addTab(newTabSpec(APPS_TAB_TAG).setIndicator(tabView).setContent(contentFactory));
label = mContext.getString(R.string.widgets_tab_label);
tabView = (TextView) mLayoutInflater.inflate(R.layout.tab_widget_indicator, tabs, false);
tabView.setText(label);
tabView.setContentDescription(label);
addTab(newTabSpec(WIDGETS_TAB_TAG).setIndicator(tabView).setContent(contentFactory));
setOnTabChangedListener(this);
// Setup the key listener to jump between the last tab view and the market icon
AppsCustomizeTabKeyEventListener keyListener = new AppsCustomizeTabKeyEventListener();
View lastTab = tabs.getChildTabViewAt(tabs.getTabCount() - 1);
lastTab.setOnKeyListener(keyListener);
View shopButton = findViewById(R.id.market_button);
shopButton.setOnKeyListener(keyListener);
// Hide the tab bar until we measure
mTabsContainer.setAlpha(0f);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
boolean remeasureTabWidth = (mTabs.getLayoutParams().width <= 0);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Set the width of the tab list to the content width
if (remeasureTabWidth) {
int contentWidth = mAppsCustomizePane.getPageContentWidth();
if (contentWidth > 0 && mTabs.getLayoutParams().width != contentWidth) {
// Set the width and show the tab bar
mTabs.getLayoutParams().width = contentWidth;
post(mRelayoutAndMakeVisible);
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public boolean onInterceptTouchEvent(MotionEvent ev) {
// If we are mid transition then intercept touch events here so we can ignore them
if (mInTransition) {
return true;
}
return super.onInterceptTouchEvent(ev);
};
@Override
public boolean onTouchEvent(MotionEvent event) {
// Allow touch events to fall through if we are transitioning to the workspace
if (mInTransition) {
if (mTransitioningToWorkspace) {
return super.onTouchEvent(event);
}
}
// Intercept all touch events up to the bottom of the AppsCustomizePane so they do not fall
// through to the workspace and trigger showWorkspace()
if (event.getY() < mAppsCustomizePane.getBottom()) {
return true;
}
return super.onTouchEvent(event);
}
private void onTabChangedStart() {
mAppsCustomizePane.hideScrollingIndicator(false);
}
private void reloadCurrentPage() {
if (!LauncherApplication.isScreenLarge()) {
mAppsCustomizePane.flashScrollingIndicator(true);
}
mAppsCustomizePane.loadAssociatedPages(mAppsCustomizePane.getCurrentPage());
mAppsCustomizePane.requestFocus();
}
private void onTabChangedEnd(AppsCustomizePagedView.ContentType type) {
mAppsCustomizePane.setContentType(type);
}
@Override
public void onTabChanged(String tabId) {
final AppsCustomizePagedView.ContentType type = getContentTypeForTabTag(tabId);
if (mSuppressContentCallback) {
mSuppressContentCallback = false;
return;
}
// Animate the changing of the tab content by fading pages in and out
final Resources res = getResources();
final int duration = res.getInteger(R.integer.config_tabTransitionDuration);
// We post a runnable here because there is a delay while the first page is loading and
// the feedback from having changed the tab almost feels better than having it stick
post(new Runnable() {
@Override
public void run() {
if (mAppsCustomizePane.getMeasuredWidth() <= 0 ||
mAppsCustomizePane.getMeasuredHeight() <= 0) {
reloadCurrentPage();
return;
}
// Take the visible pages and re-parent them temporarily to mAnimatorBuffer
// and then cross fade to the new pages
int[] visiblePageRange = new int[2];
mAppsCustomizePane.getVisiblePages(visiblePageRange);
if (visiblePageRange[0] == -1 && visiblePageRange[1] == -1) {
// If we can't get the visible page ranges, then just skip the animation
reloadCurrentPage();
return;
}
ArrayList<View> visiblePages = new ArrayList<View>();
for (int i = visiblePageRange[0]; i <= visiblePageRange[1]; i++) {
visiblePages.add(mAppsCustomizePane.getPageAt(i));
}
// We want the pages to be rendered in exactly the same way as they were when
// their parent was mAppsCustomizePane -- so set the scroll on mAnimationBuffer
// to be exactly the same as mAppsCustomizePane, and below, set the left/top
// parameters to be correct for each of the pages
mAnimationBuffer.scrollTo(mAppsCustomizePane.getScrollX(), 0);
// mAppsCustomizePane renders its children in reverse order, so
// add the pages to mAnimationBuffer in reverse order to match that behavior
for (int i = visiblePages.size() - 1; i >= 0; i--) {
View child = visiblePages.get(i);
if (child instanceof PagedViewCellLayout) {
((PagedViewCellLayout) child).resetChildrenOnKeyListeners();
} else if (child instanceof PagedViewGridLayout) {
((PagedViewGridLayout) child).resetChildrenOnKeyListeners();
}
PagedViewWidget.setDeletePreviewsWhenDetachedFromWindow(false);
mAppsCustomizePane.removeView(child);
PagedViewWidget.setDeletePreviewsWhenDetachedFromWindow(true);
mAnimationBuffer.setAlpha(1f);
mAnimationBuffer.setVisibility(View.VISIBLE);
- LayoutParams p = new FrameLayout.LayoutParams(child.getWidth(),
- child.getHeight());
+ LayoutParams p = new FrameLayout.LayoutParams(child.getMeasuredWidth(),
+ child.getMeasuredHeight());
p.setMargins((int) child.getLeft(), (int) child.getTop(), 0, 0);
mAnimationBuffer.addView(child, p);
}
// Toggle the new content
onTabChangedStart();
onTabChangedEnd(type);
// Animate the transition
ObjectAnimator outAnim = ObjectAnimator.ofFloat(mAnimationBuffer, "alpha", 0f);
outAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mAnimationBuffer.setVisibility(View.GONE);
mAnimationBuffer.removeAllViews();
}
@Override
public void onAnimationCancel(Animator animation) {
mAnimationBuffer.setVisibility(View.GONE);
mAnimationBuffer.removeAllViews();
}
});
ObjectAnimator inAnim = ObjectAnimator.ofFloat(mAppsCustomizePane, "alpha", 1f);
inAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
reloadCurrentPage();
}
});
AnimatorSet animSet = new AnimatorSet();
animSet.playTogether(outAnim, inAnim);
animSet.setDuration(duration);
animSet.start();
}
});
}
public void setCurrentTabFromContent(AppsCustomizePagedView.ContentType type) {
mSuppressContentCallback = true;
setCurrentTabByTag(getTabTagForContentType(type));
}
/**
* Returns the content type for the specified tab tag.
*/
public AppsCustomizePagedView.ContentType getContentTypeForTabTag(String tag) {
if (tag.equals(APPS_TAB_TAG)) {
return AppsCustomizePagedView.ContentType.Applications;
} else if (tag.equals(WIDGETS_TAB_TAG)) {
return AppsCustomizePagedView.ContentType.Widgets;
}
return AppsCustomizePagedView.ContentType.Applications;
}
/**
* Returns the tab tag for a given content type.
*/
public String getTabTagForContentType(AppsCustomizePagedView.ContentType type) {
if (type == AppsCustomizePagedView.ContentType.Applications) {
return APPS_TAB_TAG;
} else if (type == AppsCustomizePagedView.ContentType.Widgets) {
return WIDGETS_TAB_TAG;
}
return APPS_TAB_TAG;
}
/**
* Disable focus on anything under this view in the hierarchy if we are not visible.
*/
@Override
public int getDescendantFocusability() {
if (getVisibility() != View.VISIBLE) {
return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
}
return super.getDescendantFocusability();
}
void reset() {
if (mInTransition) {
// Defer to after the transition to reset
mResetAfterTransition = true;
} else {
// Reset immediately
mAppsCustomizePane.reset();
}
}
private void enableAndBuildHardwareLayer() {
// isHardwareAccelerated() checks if we're attached to a window and if that
// window is HW accelerated-- we were sometimes not attached to a window
// and buildLayer was throwing an IllegalStateException
if (isHardwareAccelerated()) {
// Turn on hardware layers for performance
setLayerType(LAYER_TYPE_HARDWARE, null);
// force building the layer, so you don't get a blip early in an animation
// when the layer is created layer
buildLayer();
// Let the GC system know that now is a good time to do any garbage
// collection; makes it less likely we'll get a GC during the all apps
// to workspace animation
System.gc();
}
}
@Override
public View getContent() {
return mContent;
}
/* LauncherTransitionable overrides */
@Override
public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
mAppsCustomizePane.onLauncherTransitionStart(l, animated, toWorkspace);
mInTransition = true;
mTransitioningToWorkspace = toWorkspace;
if (toWorkspace) {
// Going from All Apps -> Workspace
setVisibilityOfSiblingsWithLowerZOrder(VISIBLE);
// Stop the scrolling indicator - we don't want All Apps to be invalidating itself
// during the transition, especially since it has a hardware layer set on it
mAppsCustomizePane.cancelScrollingIndicatorAnimations();
} else {
// Going from Workspace -> All Apps
mContent.setVisibility(VISIBLE);
// Make sure the current page is loaded (we start loading the side pages after the
// transition to prevent slowing down the animation)
mAppsCustomizePane.loadAssociatedPages(mAppsCustomizePane.getCurrentPage(), true);
if (!LauncherApplication.isScreenLarge()) {
mAppsCustomizePane.showScrollingIndicator(true);
}
}
if (mResetAfterTransition) {
mAppsCustomizePane.reset();
mResetAfterTransition = false;
}
if (animated) {
enableAndBuildHardwareLayer();
}
}
@Override
public void onLauncherTransitionStep(Launcher l, float t) {
// Do nothing
}
@Override
public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
mAppsCustomizePane.onLauncherTransitionEnd(l, animated, toWorkspace);
mInTransition = false;
if (animated) {
setLayerType(LAYER_TYPE_NONE, null);
}
if (!toWorkspace) {
// Going from Workspace -> All Apps
setVisibilityOfSiblingsWithLowerZOrder(INVISIBLE);
// Dismiss the workspace cling and show the all apps cling (if not already shown)
l.dismissWorkspaceCling(null);
mAppsCustomizePane.showAllAppsCling();
// Make sure adjacent pages are loaded (we wait until after the transition to
// prevent slowing down the animation)
mAppsCustomizePane.loadAssociatedPages(mAppsCustomizePane.getCurrentPage());
if (!LauncherApplication.isScreenLarge()) {
mAppsCustomizePane.hideScrollingIndicator(false);
}
}
}
private void setVisibilityOfSiblingsWithLowerZOrder(int visibility) {
ViewGroup parent = (ViewGroup) getParent();
final int count = parent.getChildCount();
if (!isChildrenDrawingOrderEnabled()) {
for (int i = 0; i < count; i++) {
final View child = parent.getChildAt(i);
if (child == this) {
break;
} else {
if (child.getVisibility() == GONE) {
continue;
}
child.setVisibility(visibility);
}
}
} else {
throw new RuntimeException("Failed; can't get z-order of views");
}
}
public void onWindowVisible() {
if (getVisibility() == VISIBLE) {
mContent.setVisibility(VISIBLE);
// We unload the widget previews when the UI is hidden, so need to reload pages
// Load the current page synchronously, and the neighboring pages asynchronously
mAppsCustomizePane.loadAssociatedPages(mAppsCustomizePane.getCurrentPage(), true);
mAppsCustomizePane.loadAssociatedPages(mAppsCustomizePane.getCurrentPage());
}
}
public void onTrimMemory() {
mContent.setVisibility(GONE);
// Clear the widget pages of all their subviews - this will trigger the widget previews
// to delete their bitmaps
mAppsCustomizePane.clearAllWidgetPages();
}
boolean isTransitioning() {
return mInTransition;
}
}
| true | true | public void onTabChanged(String tabId) {
final AppsCustomizePagedView.ContentType type = getContentTypeForTabTag(tabId);
if (mSuppressContentCallback) {
mSuppressContentCallback = false;
return;
}
// Animate the changing of the tab content by fading pages in and out
final Resources res = getResources();
final int duration = res.getInteger(R.integer.config_tabTransitionDuration);
// We post a runnable here because there is a delay while the first page is loading and
// the feedback from having changed the tab almost feels better than having it stick
post(new Runnable() {
@Override
public void run() {
if (mAppsCustomizePane.getMeasuredWidth() <= 0 ||
mAppsCustomizePane.getMeasuredHeight() <= 0) {
reloadCurrentPage();
return;
}
// Take the visible pages and re-parent them temporarily to mAnimatorBuffer
// and then cross fade to the new pages
int[] visiblePageRange = new int[2];
mAppsCustomizePane.getVisiblePages(visiblePageRange);
if (visiblePageRange[0] == -1 && visiblePageRange[1] == -1) {
// If we can't get the visible page ranges, then just skip the animation
reloadCurrentPage();
return;
}
ArrayList<View> visiblePages = new ArrayList<View>();
for (int i = visiblePageRange[0]; i <= visiblePageRange[1]; i++) {
visiblePages.add(mAppsCustomizePane.getPageAt(i));
}
// We want the pages to be rendered in exactly the same way as they were when
// their parent was mAppsCustomizePane -- so set the scroll on mAnimationBuffer
// to be exactly the same as mAppsCustomizePane, and below, set the left/top
// parameters to be correct for each of the pages
mAnimationBuffer.scrollTo(mAppsCustomizePane.getScrollX(), 0);
// mAppsCustomizePane renders its children in reverse order, so
// add the pages to mAnimationBuffer in reverse order to match that behavior
for (int i = visiblePages.size() - 1; i >= 0; i--) {
View child = visiblePages.get(i);
if (child instanceof PagedViewCellLayout) {
((PagedViewCellLayout) child).resetChildrenOnKeyListeners();
} else if (child instanceof PagedViewGridLayout) {
((PagedViewGridLayout) child).resetChildrenOnKeyListeners();
}
PagedViewWidget.setDeletePreviewsWhenDetachedFromWindow(false);
mAppsCustomizePane.removeView(child);
PagedViewWidget.setDeletePreviewsWhenDetachedFromWindow(true);
mAnimationBuffer.setAlpha(1f);
mAnimationBuffer.setVisibility(View.VISIBLE);
LayoutParams p = new FrameLayout.LayoutParams(child.getWidth(),
child.getHeight());
p.setMargins((int) child.getLeft(), (int) child.getTop(), 0, 0);
mAnimationBuffer.addView(child, p);
}
// Toggle the new content
onTabChangedStart();
onTabChangedEnd(type);
// Animate the transition
ObjectAnimator outAnim = ObjectAnimator.ofFloat(mAnimationBuffer, "alpha", 0f);
outAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mAnimationBuffer.setVisibility(View.GONE);
mAnimationBuffer.removeAllViews();
}
@Override
public void onAnimationCancel(Animator animation) {
mAnimationBuffer.setVisibility(View.GONE);
mAnimationBuffer.removeAllViews();
}
});
ObjectAnimator inAnim = ObjectAnimator.ofFloat(mAppsCustomizePane, "alpha", 1f);
inAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
reloadCurrentPage();
}
});
AnimatorSet animSet = new AnimatorSet();
animSet.playTogether(outAnim, inAnim);
animSet.setDuration(duration);
animSet.start();
}
});
}
| public void onTabChanged(String tabId) {
final AppsCustomizePagedView.ContentType type = getContentTypeForTabTag(tabId);
if (mSuppressContentCallback) {
mSuppressContentCallback = false;
return;
}
// Animate the changing of the tab content by fading pages in and out
final Resources res = getResources();
final int duration = res.getInteger(R.integer.config_tabTransitionDuration);
// We post a runnable here because there is a delay while the first page is loading and
// the feedback from having changed the tab almost feels better than having it stick
post(new Runnable() {
@Override
public void run() {
if (mAppsCustomizePane.getMeasuredWidth() <= 0 ||
mAppsCustomizePane.getMeasuredHeight() <= 0) {
reloadCurrentPage();
return;
}
// Take the visible pages and re-parent them temporarily to mAnimatorBuffer
// and then cross fade to the new pages
int[] visiblePageRange = new int[2];
mAppsCustomizePane.getVisiblePages(visiblePageRange);
if (visiblePageRange[0] == -1 && visiblePageRange[1] == -1) {
// If we can't get the visible page ranges, then just skip the animation
reloadCurrentPage();
return;
}
ArrayList<View> visiblePages = new ArrayList<View>();
for (int i = visiblePageRange[0]; i <= visiblePageRange[1]; i++) {
visiblePages.add(mAppsCustomizePane.getPageAt(i));
}
// We want the pages to be rendered in exactly the same way as they were when
// their parent was mAppsCustomizePane -- so set the scroll on mAnimationBuffer
// to be exactly the same as mAppsCustomizePane, and below, set the left/top
// parameters to be correct for each of the pages
mAnimationBuffer.scrollTo(mAppsCustomizePane.getScrollX(), 0);
// mAppsCustomizePane renders its children in reverse order, so
// add the pages to mAnimationBuffer in reverse order to match that behavior
for (int i = visiblePages.size() - 1; i >= 0; i--) {
View child = visiblePages.get(i);
if (child instanceof PagedViewCellLayout) {
((PagedViewCellLayout) child).resetChildrenOnKeyListeners();
} else if (child instanceof PagedViewGridLayout) {
((PagedViewGridLayout) child).resetChildrenOnKeyListeners();
}
PagedViewWidget.setDeletePreviewsWhenDetachedFromWindow(false);
mAppsCustomizePane.removeView(child);
PagedViewWidget.setDeletePreviewsWhenDetachedFromWindow(true);
mAnimationBuffer.setAlpha(1f);
mAnimationBuffer.setVisibility(View.VISIBLE);
LayoutParams p = new FrameLayout.LayoutParams(child.getMeasuredWidth(),
child.getMeasuredHeight());
p.setMargins((int) child.getLeft(), (int) child.getTop(), 0, 0);
mAnimationBuffer.addView(child, p);
}
// Toggle the new content
onTabChangedStart();
onTabChangedEnd(type);
// Animate the transition
ObjectAnimator outAnim = ObjectAnimator.ofFloat(mAnimationBuffer, "alpha", 0f);
outAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mAnimationBuffer.setVisibility(View.GONE);
mAnimationBuffer.removeAllViews();
}
@Override
public void onAnimationCancel(Animator animation) {
mAnimationBuffer.setVisibility(View.GONE);
mAnimationBuffer.removeAllViews();
}
});
ObjectAnimator inAnim = ObjectAnimator.ofFloat(mAppsCustomizePane, "alpha", 1f);
inAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
reloadCurrentPage();
}
});
AnimatorSet animSet = new AnimatorSet();
animSet.playTogether(outAnim, inAnim);
animSet.setDuration(duration);
animSet.start();
}
});
}
|
diff --git a/src/Extensions/org/objectweb/proactive/extensions/pamr/client/ProActiveMessageHandler.java b/src/Extensions/org/objectweb/proactive/extensions/pamr/client/ProActiveMessageHandler.java
index e094b4b1b..54025ab81 100644
--- a/src/Extensions/org/objectweb/proactive/extensions/pamr/client/ProActiveMessageHandler.java
+++ b/src/Extensions/org/objectweb/proactive/extensions/pamr/client/ProActiveMessageHandler.java
@@ -1,167 +1,169 @@
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ActiveEon Team
* http://www.activeeon.com/
* Contributor(s):
*
* ################################################################
* $$ACTIVEEON_INITIAL_DEV$$
*/
package org.objectweb.proactive.extensions.pamr.client;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.apache.log4j.Logger;
import org.objectweb.proactive.core.body.future.MethodCallResult;
import org.objectweb.proactive.core.body.request.Request;
import org.objectweb.proactive.core.remoteobject.SynchronousReplyImpl;
import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl;
import org.objectweb.proactive.core.util.converter.remote.ProActiveMarshaller;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.objectweb.proactive.extensions.pamr.PAMRConfig;
import org.objectweb.proactive.extensions.pamr.exceptions.PAMRException;
import org.objectweb.proactive.extensions.pamr.protocol.message.DataRequestMessage;
import org.objectweb.proactive.extensions.pamr.remoteobject.message.PAMRMessage;
import org.objectweb.proactive.utils.NamedThreadFactory;
/** Executes a ProActive {@link Request} received and send the response.
*
* @since ProActive 4.1.0
*/
public class ProActiveMessageHandler implements MessageHandler {
public static final Logger logger = ProActiveLogger.getLogger(PAMRConfig.Loggers.PAMR_CLIENT);
/** {@link Request} are handled by a threadpool */
final private ExecutorService tpe;
/** Local agent */
private Agent agent;
public ProActiveMessageHandler(Agent agent) {
this.agent = agent;
/* DO NOT USE A FIXED THREAD POOL
*
* Each time a message arrives, it is handled by a task submitted to
* this executor service. Each task can a perform remote calls. If
* the number of workers is fixed it can lead to deadlock.
*
* Reentrant calls is the most obvious case of deadlock. But the same
* issue can occur with remote calls.
*/
ThreadFactory tf = new NamedThreadFactory("ProActive PAMR message handler");
tpe = Executors.newCachedThreadPool(tf);
}
public void pushMessage(DataRequestMessage message) {
if (logger.isTraceEnabled()) {
logger.trace("pushing message " + message + " into the executor queue");
}
ProActiveMessageProcessor pmp = new ProActiveMessageProcessor(message, agent);
tpe.submit(pmp);
}
/** Process one ProActive {@link Request} */
private class ProActiveMessageProcessor implements Runnable {
/** the request*/
private final DataRequestMessage _toProcess;
/** the local agent*/
private final Agent agent;
/** serialization*/
private final ProActiveMarshaller marshaller;
public ProActiveMessageProcessor(DataRequestMessage msg, Agent agent) {
this._toProcess = msg;
this.agent = agent;
// get the runtime URL
// if the local Agent has received a DataRequestMessage,
// means that a ProActiveRuntime exists on this machine
String runtimeUrl = ProActiveRuntimeImpl.getProActiveRuntime().getURL();
this.marshaller = new ProActiveMarshaller(runtimeUrl);
}
public void run() {
ClassLoader savedClassLoader = Thread.currentThread().getContextClassLoader();
try {
// Handle the message
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
PAMRMessage message;
try {
message = (PAMRMessage) this.marshaller.unmarshallObject(_toProcess.getData());
} catch (Throwable t) {
- new PAMRException("Failed to unmarshall incoming message", t);
- SynchronousReplyImpl sr = new SynchronousReplyImpl(new MethodCallResult(null, t));
+ PAMRException e = new PAMRException("Failed to unmarshall incoming message on " +
+ this.agent.getAgentID() + "for " + this._toProcess, t);
+ SynchronousReplyImpl sr = new SynchronousReplyImpl(new MethodCallResult(null, e));
agent.sendReply(_toProcess, this.marshaller.marshallObject(sr));
return;
}
if (logger.isTraceEnabled()) {
logger.trace("Processing message: " + message);
}
Object result = message.processMessage(); // Cannot throw an exception
byte[] resultBytes;
try {
resultBytes = this.marshaller.marshallObject(result);
} catch (Throwable t) {
- new PAMRException("Failed to marshall the result bytes", t);
- SynchronousReplyImpl sr = new SynchronousReplyImpl(new MethodCallResult(null, t));
+ PAMRException e = new PAMRException("Failed to marshall the result bytes on " +
+ this.agent.getAgentID() + " for " + _toProcess, t);
+ SynchronousReplyImpl sr = new SynchronousReplyImpl(new MethodCallResult(null, e));
agent.sendReply(_toProcess, this.marshaller.marshallObject(sr));
return;
}
try {
agent.sendReply(_toProcess, resultBytes);
} catch (Throwable t) {
logger.info("Failed to send the PAMR reply to " + this._toProcess +
". The router should discover the disconnection and unlock the caller", t);
return;
}
} catch (PAMRException e) {
logger.info("Failed to send the PAMR error reply to " + this._toProcess +
". The router should discover the disconnection and unlock the caller", e);
} catch (IOException e) {
logger.info("Failed to send the PAMR error reply to " + this._toProcess +
". The router should discover the disconnection and unlock the caller", e);
} finally {
Thread.currentThread().setContextClassLoader(savedClassLoader);
}
}
}
}
| false | true | public void run() {
ClassLoader savedClassLoader = Thread.currentThread().getContextClassLoader();
try {
// Handle the message
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
PAMRMessage message;
try {
message = (PAMRMessage) this.marshaller.unmarshallObject(_toProcess.getData());
} catch (Throwable t) {
new PAMRException("Failed to unmarshall incoming message", t);
SynchronousReplyImpl sr = new SynchronousReplyImpl(new MethodCallResult(null, t));
agent.sendReply(_toProcess, this.marshaller.marshallObject(sr));
return;
}
if (logger.isTraceEnabled()) {
logger.trace("Processing message: " + message);
}
Object result = message.processMessage(); // Cannot throw an exception
byte[] resultBytes;
try {
resultBytes = this.marshaller.marshallObject(result);
} catch (Throwable t) {
new PAMRException("Failed to marshall the result bytes", t);
SynchronousReplyImpl sr = new SynchronousReplyImpl(new MethodCallResult(null, t));
agent.sendReply(_toProcess, this.marshaller.marshallObject(sr));
return;
}
try {
agent.sendReply(_toProcess, resultBytes);
} catch (Throwable t) {
logger.info("Failed to send the PAMR reply to " + this._toProcess +
". The router should discover the disconnection and unlock the caller", t);
return;
}
} catch (PAMRException e) {
logger.info("Failed to send the PAMR error reply to " + this._toProcess +
". The router should discover the disconnection and unlock the caller", e);
} catch (IOException e) {
logger.info("Failed to send the PAMR error reply to " + this._toProcess +
". The router should discover the disconnection and unlock the caller", e);
} finally {
Thread.currentThread().setContextClassLoader(savedClassLoader);
}
}
| public void run() {
ClassLoader savedClassLoader = Thread.currentThread().getContextClassLoader();
try {
// Handle the message
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
PAMRMessage message;
try {
message = (PAMRMessage) this.marshaller.unmarshallObject(_toProcess.getData());
} catch (Throwable t) {
PAMRException e = new PAMRException("Failed to unmarshall incoming message on " +
this.agent.getAgentID() + "for " + this._toProcess, t);
SynchronousReplyImpl sr = new SynchronousReplyImpl(new MethodCallResult(null, e));
agent.sendReply(_toProcess, this.marshaller.marshallObject(sr));
return;
}
if (logger.isTraceEnabled()) {
logger.trace("Processing message: " + message);
}
Object result = message.processMessage(); // Cannot throw an exception
byte[] resultBytes;
try {
resultBytes = this.marshaller.marshallObject(result);
} catch (Throwable t) {
PAMRException e = new PAMRException("Failed to marshall the result bytes on " +
this.agent.getAgentID() + " for " + _toProcess, t);
SynchronousReplyImpl sr = new SynchronousReplyImpl(new MethodCallResult(null, e));
agent.sendReply(_toProcess, this.marshaller.marshallObject(sr));
return;
}
try {
agent.sendReply(_toProcess, resultBytes);
} catch (Throwable t) {
logger.info("Failed to send the PAMR reply to " + this._toProcess +
". The router should discover the disconnection and unlock the caller", t);
return;
}
} catch (PAMRException e) {
logger.info("Failed to send the PAMR error reply to " + this._toProcess +
". The router should discover the disconnection and unlock the caller", e);
} catch (IOException e) {
logger.info("Failed to send the PAMR error reply to " + this._toProcess +
". The router should discover the disconnection and unlock the caller", e);
} finally {
Thread.currentThread().setContextClassLoader(savedClassLoader);
}
}
|
diff --git a/ScenePlayer/src/org/puredata/android/scenes/RecordingSelection.java b/ScenePlayer/src/org/puredata/android/scenes/RecordingSelection.java
index 2fc0f38..cf0aa88 100644
--- a/ScenePlayer/src/org/puredata/android/scenes/RecordingSelection.java
+++ b/ScenePlayer/src/org/puredata/android/scenes/RecordingSelection.java
@@ -1,81 +1,81 @@
/**
*
* @author Peter Brinkmann ([email protected])
*
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*
*/
package org.puredata.android.scenes;
import java.io.File;
import java.io.IOException;
import org.puredata.android.scenes.SceneDataBase.RecordingColumn;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
public class RecordingSelection extends Activity implements OnItemClickListener, OnItemLongClickListener {
private static final String TAG = "Recording Selection";
private ListView recordingView;
private SceneDataBase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new SceneDataBase(this);
initGui();
}
private void initGui() {
setContentView(R.layout.recording_selection);
recordingView = (ListView) findViewById(R.id.recording_selection);
recordingView.setOnItemClickListener(this);
recordingView.setOnItemLongClickListener(this);
}
@Override
protected void onResume() {
super.onResume();
updateList();
}
private void updateList() {
RecordingListCursorAdapter adapter = new RecordingListCursorAdapter(RecordingSelection.this, db.getAllRecordings());
recordingView.setAdapter(adapter);
}
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Cursor cursor = db.getRecording(id);
String path = SceneDataBase.getString(cursor, RecordingColumn.RECORDING_PATH);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File file = new File(path);
- intent.setDataAndType(Uri.fromFile(file), "audio/*");
+ intent.setDataAndType(Uri.fromFile(file), "audio/x-wav");
startActivity(intent);
}
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View v, int position, long id) {
try {
db.deleteRecording(id);
} catch (IOException e) {
Log.e(TAG, e.toString());
}
updateList();
return true;
}
}
| true | true | public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Cursor cursor = db.getRecording(id);
String path = SceneDataBase.getString(cursor, RecordingColumn.RECORDING_PATH);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File file = new File(path);
intent.setDataAndType(Uri.fromFile(file), "audio/*");
startActivity(intent);
}
| public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Cursor cursor = db.getRecording(id);
String path = SceneDataBase.getString(cursor, RecordingColumn.RECORDING_PATH);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File file = new File(path);
intent.setDataAndType(Uri.fromFile(file), "audio/x-wav");
startActivity(intent);
}
|
diff --git a/extra/src/org/droidparts/util/intent/IntentHelper.java b/extra/src/org/droidparts/util/intent/IntentHelper.java
index 31f5197d..2752ab35 100644
--- a/extra/src/org/droidparts/util/intent/IntentHelper.java
+++ b/extra/src/org/droidparts/util/intent/IntentHelper.java
@@ -1,66 +1,68 @@
/**
* Copyright 2012 Alex Yanchenko
*
* 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.droidparts.util.intent;
import java.util.ArrayList;
import java.util.List;
import org.droidparts.util.L;
import org.droidparts.util.ui.AbstractDialogFactory;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
public class IntentHelper {
private Context ctx;
public IntentHelper(Context ctx) {
this.ctx = ctx;
}
public void startChooserOrWarn(Intent intent) {
startChooserOrWarn(intent, null);
}
public void startChooserOrWarn(Intent intent, String title) {
Intent choooserIntent = Intent.createChooser(intent, title);
startOrWarn(choooserIntent);
}
public void startOrWarn(Intent intent) {
try {
ctx.startActivity(intent);
} catch (ActivityNotFoundException e) {
L.e(e);
new AbstractDialogFactory(ctx).showErrorToast();
}
}
public ActivityInfo[] getIntentHandlers(Intent intent) {
List<ResolveInfo> list = ctx.getPackageManager().queryIntentActivities(
intent, 0);
ArrayList<ActivityInfo> activities = new ArrayList<ActivityInfo>();
- for (ResolveInfo ri : list) {
- activities.add(ri.activityInfo);
+ if (list != null) {
+ for (ResolveInfo ri : list) {
+ activities.add(ri.activityInfo);
+ }
}
return activities.toArray(new ActivityInfo[activities.size()]);
}
}
| true | true | public ActivityInfo[] getIntentHandlers(Intent intent) {
List<ResolveInfo> list = ctx.getPackageManager().queryIntentActivities(
intent, 0);
ArrayList<ActivityInfo> activities = new ArrayList<ActivityInfo>();
for (ResolveInfo ri : list) {
activities.add(ri.activityInfo);
}
return activities.toArray(new ActivityInfo[activities.size()]);
}
| public ActivityInfo[] getIntentHandlers(Intent intent) {
List<ResolveInfo> list = ctx.getPackageManager().queryIntentActivities(
intent, 0);
ArrayList<ActivityInfo> activities = new ArrayList<ActivityInfo>();
if (list != null) {
for (ResolveInfo ri : list) {
activities.add(ri.activityInfo);
}
}
return activities.toArray(new ActivityInfo[activities.size()]);
}
|
diff --git a/src/client/mgmt/ManagementClient.java b/src/client/mgmt/ManagementClient.java
index 51f02ee..2e255e3 100644
--- a/src/client/mgmt/ManagementClient.java
+++ b/src/client/mgmt/ManagementClient.java
@@ -1,312 +1,312 @@
package client.mgmt;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import server.billing.AuctionCharging;
import server.billing.Bill;
import server.analytics.AnalyticsServer;
import server.analytics.AnalyticsServerRMI;
import server.analytics.Event;
import server.billing.BillingServerRMI;
import server.billing.BillingServerSecure;
import server.billing.PriceStep;
import tools.PropertiesParser;
public class ManagementClient extends UnicastRemoteObject implements ManagementClientInterface
{
private static final long serialVersionUID = -5040308854282471229L;
private String analyticsBindingName = "";
private String billingBindingName = "";
private BillingServerRMI bs = null;
private BillingServerSecure bss = null;
private AnalyticsServerRMI as = null;
private PropertiesParser ps = null;
private Registry reg = null;
private BufferedReader keys = null;
private String PROMPT = "> ";
private int id = 0;
private ArrayList<String> buffer = null;
private boolean auto;
public ManagementClient(String analyticsBindingName, String billingBindingName) throws RemoteException{
keys = new BufferedReader(new InputStreamReader(System.in));
this.analyticsBindingName = analyticsBindingName;
this.billingBindingName = billingBindingName;
try {
ps = new PropertiesParser("registry.properties");
int portNr = Integer.parseInt(ps.getProperty("registry.port"));
String host = ps.getProperty("registry.host");
reg = LocateRegistry.getRegistry(host, portNr);
bs = (BillingServerRMI) reg.lookup(billingBindingName);
as = (AnalyticsServerRMI) reg.lookup(analyticsBindingName);
} catch (FileNotFoundException e) {
System.err.println("properties file not found!");
} catch (NumberFormatException e) {
System.err.println("Port non-numeric!");
} catch (RemoteException e) {
System.err.println("Registry couldn't be found!");
} catch (NotBoundException e) {
System.err.println("Object couldn't be found");
e.printStackTrace();
}
id = 1;
buffer = new ArrayList<String>();
auto = true;
}
public void listen() {
try {
String command = "";
String[] commandParts;
while ((command = keys.readLine()) != "\n") {
command = command.trim(); // remove leading and trailing whitespaces
commandParts = command.split("\\s+");
if (commandParts[0].equals("!login")) {
if (bss != null) {
System.err.println("You are already logged in! Logout first!");
} else {
if (commandParts.length != 3) {
System.err.println("Invalid command! Must be !login <username> <password>");
} else {
bss = (BillingServerSecure) bs.login(commandParts[1], commandParts[2]);
if (bss == null) {
System.err.println("Login failed!");
} else {
System.out.println(commandParts[1] + " successfully logged in");
PROMPT = commandParts[1] + "> ";
}
}
}
} else if (commandParts[0].equals("!steps")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
System.out.printf("%-9s %-9s %-9s %-9s%n", "Min_Price", "Max_Price", "Fee_Fixed", "Fee_Variable");
for (PriceStep p : bss.getPriceSteps().getPriceSteps()) {
System.out.printf("%-9.0f %-9.0f %-9.1f %-9.1f%n", p.getStartPrice(), p.getEndPrice(), p.getFixedPrice(), p.getVariablePricePercent());
}
}
} else if (commandParts[0].equals("!addStep")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
if (commandParts.length != 5) {
System.err.println("Invalid command! Must be !addStep <startPrice> <endPrice> <fixedPrice> <variablePricePercent>");
} else {
try {
double startPrice = Double.parseDouble(commandParts[1]);
double endPrice = Double.parseDouble(commandParts[2]);
double fixedPrice = Double.parseDouble(commandParts[3]);
double variablePricePercent = Double.parseDouble(commandParts[4]);
bss.createPriceStep(startPrice, endPrice, fixedPrice, variablePricePercent);
} catch (NumberFormatException e) {
System.err.println("Error! Non-numeric argument, where numeric argument expected!");
} catch (RemoteException e) {
System.err.println("Couldn't create price step! Please check if price steps are overlapping!");
}
}
}
} else if (commandParts[0].equals("!removeStep")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
if (commandParts.length != 3) {
System.err.println("Invalid command! Must be !removeStep <startPrice> <endPrice>");
} else {
try {
double startPrice = Double.parseDouble(commandParts[1]);
double endPrice = Double.parseDouble(commandParts[2]);
bss.deletePriceStep(startPrice, endPrice);
} catch (NumberFormatException e) {
System.err.println("Error! Non-numeric argument, where numeric argument expected!");
} catch (RemoteException e) {
System.err.println("Couldn't delete price step! Please make sure the given price step exists!");
}
}
}
} else if (commandParts[0].equals("!bill")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
if (commandParts.length != 2) {
System.err.println("Invalid command! Must be !bill <username>");
} else {
try {
Bill bill = bss.getBill(commandParts[1]);
System.out.printf("%-12s %-12s %-12s %-12s %-12s%n", "auction_ID", "strike_price", "fee_fixed", "fee_variable", "fee_total");
for (AuctionCharging ac : bill.getAuctionChargings()) {
System.out.printf("%-12d %-12.0f %-12.0f %-12.1f %-12.1f%n", ac.getAuctionId(), ac.getStrikePrice(), ac.getFixedFee(),
ac.getVariableFee(), ac.getVariableFee() + ac.getFixedFee());
}
} catch (RemoteException e) {
System.err.println("Couldn't bill user! Please make sure the given user exists!");
}
}
}
} else if (commandParts[0].equals("!billAuction")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
if (commandParts.length != 4) {
System.err.println("Invalid command! Must be !bill <username>");
} else {
try {
bss.billAuction(commandParts[1], Long.parseLong(commandParts[2]), Double.parseDouble(commandParts[3]));
} catch (RemoteException e) {
System.err.println("Couldn't bill user! Please make sure the given user exists!");
e.printStackTrace();
}
}
}
} else if (commandParts[0].equals("!logout")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
bss = null;
}
} else if (commandParts[0].equals("!subscribe")) {
if (commandParts.length != 2) {
System.err.println("Invalid command! Must be !subscribe <filter>");
} else {
try {
- as.subscribe(this, commandParts[1]);
+ System.out.println(as.subscribe(this, commandParts[1]));
} catch (RemoteException e) {
System.err.println("Couldn't subscribe!");
e.printStackTrace();
}
}
} else if (commandParts[0].equals("!unsubscribe")) {
if (commandParts.length != 2) {
System.err.println("Invalid command! Must be !unsubscribe <id>");
} else {
try {
- as.unsubscribe(this, Integer.parseInt(commandParts[1]));
+ System.out.println(as.unsubscribe(this, Integer.parseInt(commandParts[1])));
} catch (RemoteException e) {
System.err.println("Couldn't unsubscribe!");
e.printStackTrace();
} catch (NumberFormatException e1) {
System.err.println("ID must be a Integer!");
e1.printStackTrace();
}
}
} else if (commandParts[0].equals("!auto")) {
auto();
}else if (commandParts[0].equals("!hide")) {
hide();
}else if (commandParts[0].equals("!print")) {
printBuffer();
}else {
System.err.println("Unknown command!");
}
System.out.print(PROMPT);
}
} catch (IOException e) {
System.err.println("Console I/O Error!");
e.printStackTrace();
}
}
public String subscribe(String filter) {
String answer = "";
try {
answer = as.subscribe(this, filter);
} catch(Exception ex) {
ex.printStackTrace();
}
if(answer.equals("")) {
answer = "Failed";
}
return answer;
}
public String unsubscribe(int id) {
String answer = "";
try {
answer = as.unsubscribe(this, id);
} catch(Exception ex) {
ex.printStackTrace();
}
if(answer.equals("")) {
answer = "Failed";
}
return answer;
}
@Override
public void processEvent(Event e) throws RemoteException {
if(auto) {
System.out.println(e.toString());
} else {
buffer.add(e.toString());
}
}
public void printBuffer() {
if(!buffer.isEmpty()) {
for(String s:buffer) {
System.out.println(s);
}
buffer.clear();
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean getAuto() {
return auto;
}
public void setAuto(boolean a) {
auto = a;
}
public void hide(){
auto = false;
}
public void auto(){
auto = true;
}
public ArrayList<String> getBuffer() {
return buffer;
}
public void setBuffer(ArrayList<String> buffer) {
this.buffer = buffer;
}
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Invalid arguments!");
System.err.println("USAGE: java ManagementClient <AnalyticsBindingname> <BillingBindingName>");
} else {
ManagementClient mc = null;
try{
mc = new ManagementClient(args[0], args[1]);
}catch(RemoteException e){
e.printStackTrace();
}
mc.listen();
}
}
}
| false | true | public void listen() {
try {
String command = "";
String[] commandParts;
while ((command = keys.readLine()) != "\n") {
command = command.trim(); // remove leading and trailing whitespaces
commandParts = command.split("\\s+");
if (commandParts[0].equals("!login")) {
if (bss != null) {
System.err.println("You are already logged in! Logout first!");
} else {
if (commandParts.length != 3) {
System.err.println("Invalid command! Must be !login <username> <password>");
} else {
bss = (BillingServerSecure) bs.login(commandParts[1], commandParts[2]);
if (bss == null) {
System.err.println("Login failed!");
} else {
System.out.println(commandParts[1] + " successfully logged in");
PROMPT = commandParts[1] + "> ";
}
}
}
} else if (commandParts[0].equals("!steps")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
System.out.printf("%-9s %-9s %-9s %-9s%n", "Min_Price", "Max_Price", "Fee_Fixed", "Fee_Variable");
for (PriceStep p : bss.getPriceSteps().getPriceSteps()) {
System.out.printf("%-9.0f %-9.0f %-9.1f %-9.1f%n", p.getStartPrice(), p.getEndPrice(), p.getFixedPrice(), p.getVariablePricePercent());
}
}
} else if (commandParts[0].equals("!addStep")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
if (commandParts.length != 5) {
System.err.println("Invalid command! Must be !addStep <startPrice> <endPrice> <fixedPrice> <variablePricePercent>");
} else {
try {
double startPrice = Double.parseDouble(commandParts[1]);
double endPrice = Double.parseDouble(commandParts[2]);
double fixedPrice = Double.parseDouble(commandParts[3]);
double variablePricePercent = Double.parseDouble(commandParts[4]);
bss.createPriceStep(startPrice, endPrice, fixedPrice, variablePricePercent);
} catch (NumberFormatException e) {
System.err.println("Error! Non-numeric argument, where numeric argument expected!");
} catch (RemoteException e) {
System.err.println("Couldn't create price step! Please check if price steps are overlapping!");
}
}
}
} else if (commandParts[0].equals("!removeStep")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
if (commandParts.length != 3) {
System.err.println("Invalid command! Must be !removeStep <startPrice> <endPrice>");
} else {
try {
double startPrice = Double.parseDouble(commandParts[1]);
double endPrice = Double.parseDouble(commandParts[2]);
bss.deletePriceStep(startPrice, endPrice);
} catch (NumberFormatException e) {
System.err.println("Error! Non-numeric argument, where numeric argument expected!");
} catch (RemoteException e) {
System.err.println("Couldn't delete price step! Please make sure the given price step exists!");
}
}
}
} else if (commandParts[0].equals("!bill")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
if (commandParts.length != 2) {
System.err.println("Invalid command! Must be !bill <username>");
} else {
try {
Bill bill = bss.getBill(commandParts[1]);
System.out.printf("%-12s %-12s %-12s %-12s %-12s%n", "auction_ID", "strike_price", "fee_fixed", "fee_variable", "fee_total");
for (AuctionCharging ac : bill.getAuctionChargings()) {
System.out.printf("%-12d %-12.0f %-12.0f %-12.1f %-12.1f%n", ac.getAuctionId(), ac.getStrikePrice(), ac.getFixedFee(),
ac.getVariableFee(), ac.getVariableFee() + ac.getFixedFee());
}
} catch (RemoteException e) {
System.err.println("Couldn't bill user! Please make sure the given user exists!");
}
}
}
} else if (commandParts[0].equals("!billAuction")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
if (commandParts.length != 4) {
System.err.println("Invalid command! Must be !bill <username>");
} else {
try {
bss.billAuction(commandParts[1], Long.parseLong(commandParts[2]), Double.parseDouble(commandParts[3]));
} catch (RemoteException e) {
System.err.println("Couldn't bill user! Please make sure the given user exists!");
e.printStackTrace();
}
}
}
} else if (commandParts[0].equals("!logout")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
bss = null;
}
} else if (commandParts[0].equals("!subscribe")) {
if (commandParts.length != 2) {
System.err.println("Invalid command! Must be !subscribe <filter>");
} else {
try {
as.subscribe(this, commandParts[1]);
} catch (RemoteException e) {
System.err.println("Couldn't subscribe!");
e.printStackTrace();
}
}
} else if (commandParts[0].equals("!unsubscribe")) {
if (commandParts.length != 2) {
System.err.println("Invalid command! Must be !unsubscribe <id>");
} else {
try {
as.unsubscribe(this, Integer.parseInt(commandParts[1]));
} catch (RemoteException e) {
System.err.println("Couldn't unsubscribe!");
e.printStackTrace();
} catch (NumberFormatException e1) {
System.err.println("ID must be a Integer!");
e1.printStackTrace();
}
}
} else if (commandParts[0].equals("!auto")) {
auto();
}else if (commandParts[0].equals("!hide")) {
hide();
}else if (commandParts[0].equals("!print")) {
printBuffer();
}else {
System.err.println("Unknown command!");
}
System.out.print(PROMPT);
}
} catch (IOException e) {
System.err.println("Console I/O Error!");
e.printStackTrace();
}
}
| public void listen() {
try {
String command = "";
String[] commandParts;
while ((command = keys.readLine()) != "\n") {
command = command.trim(); // remove leading and trailing whitespaces
commandParts = command.split("\\s+");
if (commandParts[0].equals("!login")) {
if (bss != null) {
System.err.println("You are already logged in! Logout first!");
} else {
if (commandParts.length != 3) {
System.err.println("Invalid command! Must be !login <username> <password>");
} else {
bss = (BillingServerSecure) bs.login(commandParts[1], commandParts[2]);
if (bss == null) {
System.err.println("Login failed!");
} else {
System.out.println(commandParts[1] + " successfully logged in");
PROMPT = commandParts[1] + "> ";
}
}
}
} else if (commandParts[0].equals("!steps")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
System.out.printf("%-9s %-9s %-9s %-9s%n", "Min_Price", "Max_Price", "Fee_Fixed", "Fee_Variable");
for (PriceStep p : bss.getPriceSteps().getPriceSteps()) {
System.out.printf("%-9.0f %-9.0f %-9.1f %-9.1f%n", p.getStartPrice(), p.getEndPrice(), p.getFixedPrice(), p.getVariablePricePercent());
}
}
} else if (commandParts[0].equals("!addStep")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
if (commandParts.length != 5) {
System.err.println("Invalid command! Must be !addStep <startPrice> <endPrice> <fixedPrice> <variablePricePercent>");
} else {
try {
double startPrice = Double.parseDouble(commandParts[1]);
double endPrice = Double.parseDouble(commandParts[2]);
double fixedPrice = Double.parseDouble(commandParts[3]);
double variablePricePercent = Double.parseDouble(commandParts[4]);
bss.createPriceStep(startPrice, endPrice, fixedPrice, variablePricePercent);
} catch (NumberFormatException e) {
System.err.println("Error! Non-numeric argument, where numeric argument expected!");
} catch (RemoteException e) {
System.err.println("Couldn't create price step! Please check if price steps are overlapping!");
}
}
}
} else if (commandParts[0].equals("!removeStep")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
if (commandParts.length != 3) {
System.err.println("Invalid command! Must be !removeStep <startPrice> <endPrice>");
} else {
try {
double startPrice = Double.parseDouble(commandParts[1]);
double endPrice = Double.parseDouble(commandParts[2]);
bss.deletePriceStep(startPrice, endPrice);
} catch (NumberFormatException e) {
System.err.println("Error! Non-numeric argument, where numeric argument expected!");
} catch (RemoteException e) {
System.err.println("Couldn't delete price step! Please make sure the given price step exists!");
}
}
}
} else if (commandParts[0].equals("!bill")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
if (commandParts.length != 2) {
System.err.println("Invalid command! Must be !bill <username>");
} else {
try {
Bill bill = bss.getBill(commandParts[1]);
System.out.printf("%-12s %-12s %-12s %-12s %-12s%n", "auction_ID", "strike_price", "fee_fixed", "fee_variable", "fee_total");
for (AuctionCharging ac : bill.getAuctionChargings()) {
System.out.printf("%-12d %-12.0f %-12.0f %-12.1f %-12.1f%n", ac.getAuctionId(), ac.getStrikePrice(), ac.getFixedFee(),
ac.getVariableFee(), ac.getVariableFee() + ac.getFixedFee());
}
} catch (RemoteException e) {
System.err.println("Couldn't bill user! Please make sure the given user exists!");
}
}
}
} else if (commandParts[0].equals("!billAuction")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
if (commandParts.length != 4) {
System.err.println("Invalid command! Must be !bill <username>");
} else {
try {
bss.billAuction(commandParts[1], Long.parseLong(commandParts[2]), Double.parseDouble(commandParts[3]));
} catch (RemoteException e) {
System.err.println("Couldn't bill user! Please make sure the given user exists!");
e.printStackTrace();
}
}
}
} else if (commandParts[0].equals("!logout")) {
if (bss == null) {
System.err.println("You need to login first!");
} else {
bss = null;
}
} else if (commandParts[0].equals("!subscribe")) {
if (commandParts.length != 2) {
System.err.println("Invalid command! Must be !subscribe <filter>");
} else {
try {
System.out.println(as.subscribe(this, commandParts[1]));
} catch (RemoteException e) {
System.err.println("Couldn't subscribe!");
e.printStackTrace();
}
}
} else if (commandParts[0].equals("!unsubscribe")) {
if (commandParts.length != 2) {
System.err.println("Invalid command! Must be !unsubscribe <id>");
} else {
try {
System.out.println(as.unsubscribe(this, Integer.parseInt(commandParts[1])));
} catch (RemoteException e) {
System.err.println("Couldn't unsubscribe!");
e.printStackTrace();
} catch (NumberFormatException e1) {
System.err.println("ID must be a Integer!");
e1.printStackTrace();
}
}
} else if (commandParts[0].equals("!auto")) {
auto();
}else if (commandParts[0].equals("!hide")) {
hide();
}else if (commandParts[0].equals("!print")) {
printBuffer();
}else {
System.err.println("Unknown command!");
}
System.out.print(PROMPT);
}
} catch (IOException e) {
System.err.println("Console I/O Error!");
e.printStackTrace();
}
}
|
diff --git a/src/main/org/jboss/messaging/core/plugin/ClusteredPostOfficeService.java b/src/main/org/jboss/messaging/core/plugin/ClusteredPostOfficeService.java
index 3e192fd85..01769857c 100644
--- a/src/main/org/jboss/messaging/core/plugin/ClusteredPostOfficeService.java
+++ b/src/main/org/jboss/messaging/core/plugin/ClusteredPostOfficeService.java
@@ -1,420 +1,420 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.messaging.core.plugin;
import javax.management.ObjectName;
import javax.management.NotificationListener;
import javax.management.NotificationFilter;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.transaction.TransactionManager;
import org.jboss.jms.selector.SelectorFactory;
import org.jboss.jms.server.JMSConditionFactory;
import org.jboss.jms.server.QueuedExecutorPool;
import org.jboss.jms.server.ServerPeer;
import org.jboss.jms.util.ExceptionUtil;
import org.jboss.messaging.core.FilterFactory;
import org.jboss.messaging.core.plugin.contract.ConditionFactory;
import org.jboss.messaging.core.plugin.contract.FailoverMapper;
import org.jboss.messaging.core.plugin.contract.MessageStore;
import org.jboss.messaging.core.plugin.contract.MessagingComponent;
import org.jboss.messaging.core.plugin.contract.PersistenceManager;
import org.jboss.messaging.core.plugin.postoffice.cluster.ClusterRouterFactory;
import org.jboss.messaging.core.plugin.postoffice.cluster.DefaultClusteredPostOffice;
import org.jboss.messaging.core.plugin.postoffice.cluster.DefaultFailoverMapper;
import org.jboss.messaging.core.plugin.postoffice.cluster.MessagePullPolicy;
import org.jboss.messaging.core.plugin.postoffice.cluster.Peer;
import org.jboss.messaging.core.plugin.postoffice.cluster.jchannelfactory.JChannelFactory;
import org.jboss.messaging.core.plugin.postoffice.cluster.jchannelfactory.MultiplexerJChannelFactory;
import org.jboss.messaging.core.plugin.postoffice.cluster.jchannelfactory.XMLJChannelFactory;
import org.jboss.messaging.core.tx.TransactionRepository;
import org.w3c.dom.Element;
import java.util.Set;
import java.util.Collections;
/**
* A ClusteredPostOfficeService
*
* MBean wrapper for a clustered post office
*
* @author <a href="mailto:[email protected]">Tim Fox</a>
* @author <a href="mailto:[email protected]">Ovidiu Feodorov</a>
* @version <tt>$Revision$</tt>
*
* $Id$
*
*/
public class ClusteredPostOfficeService extends JDBCServiceSupport implements Peer
{
// Constants -----------------------------------------------------
// Static --------------------------------------------------------
// Attributes ----------------------------------------------------
private boolean started;
// This group of properties is used on JGroups Channel configuration
private Element syncChannelConfig;
private Element asyncChannelConfig;
private ObjectName channelFactoryName;
private String syncChannelName;
private String asyncChannelName;
private String channelPartitionName;
private ObjectName serverPeerObjectName;
private String officeName;
private long stateTimeout = 5000;
private long castTimeout = 5000;
private String groupName;
private long statsSendPeriod = 1000;
private String clusterRouterFactory;
private String messagePullPolicy;
private DefaultClusteredPostOffice postOffice;
// Constructors --------------------------------------------------
// ServerPlugin implementation -----------------------------------
public MessagingComponent getInstance()
{
return postOffice;
}
// Peer implementation -------------------------------------------
public Set getNodeIDView()
{
if (postOffice == null)
{
return Collections.EMPTY_SET;
}
return postOffice.getNodeIDView();
}
// NotificationBroadcaster implementation ------------------------
public void addNotificationListener(NotificationListener listener,
NotificationFilter filter,
Object object) throws IllegalArgumentException
{
postOffice.addNotificationListener(listener, filter, object);
}
public void removeNotificationListener(NotificationListener listener)
throws ListenerNotFoundException
{
postOffice.removeNotificationListener(listener);
}
public MBeanNotificationInfo[] getNotificationInfo()
{
return postOffice.getNotificationInfo();
}
// MBean attributes ----------------------------------------------
public synchronized ObjectName getServerPeer()
{
return serverPeerObjectName;
}
public synchronized void setServerPeer(ObjectName on)
{
if (started)
{
log.warn("Cannot set attribute when service is started");
return;
}
this.serverPeerObjectName = on;
}
public synchronized String getPostOfficeName()
{
return officeName;
}
public synchronized void setPostOfficeName(String name)
{
if (started)
{
log.warn("Cannot set attribute when service is started");
return;
}
this.officeName = name;
}
public ObjectName getChannelFactoryName()
{
return channelFactoryName;
}
public void setChannelFactoryName(ObjectName channelFactoryName)
{
this.channelFactoryName = channelFactoryName;
}
public String getSyncChannelName()
{
return syncChannelName;
}
public void setSyncChannelName(String syncChannelName)
{
this.syncChannelName = syncChannelName;
}
public String getAsyncChannelName()
{
return asyncChannelName;
}
public void setAsyncChannelName(String asyncChannelName)
{
this.asyncChannelName = asyncChannelName;
}
public String getChannelPartitionName()
{
return channelPartitionName;
}
public void setChannelPartitionName(String channelPartitionName)
{
this.channelPartitionName = channelPartitionName;
}
public void setSyncChannelConfig(Element config) throws Exception
{
syncChannelConfig = config;
}
public Element getSyncChannelConfig()
{
return syncChannelConfig;
}
public void setAsyncChannelConfig(Element config) throws Exception
{
asyncChannelConfig = config;
}
public Element getAsyncChannelConfig()
{
return asyncChannelConfig;
}
public void setStateTimeout(long timeout)
{
this.stateTimeout = timeout;
}
public long getStateTimeout()
{
return stateTimeout;
}
public void setCastTimeout(long timeout)
{
this.castTimeout = timeout;
}
public long getCastTimeout()
{
return castTimeout;
}
public void setGroupName(String groupName)
{
this.groupName = groupName;
}
public String getGroupName()
{
return groupName;
}
public void setStatsSendPeriod(long period)
{
this.statsSendPeriod = period;
}
public long getStatsSendPeriod()
{
return statsSendPeriod;
}
public String getClusterRouterFactory()
{
return clusterRouterFactory;
}
public String getMessagePullPolicy()
{
return messagePullPolicy;
}
public void setClusterRouterFactory(String clusterRouterFactory)
{
this.clusterRouterFactory = clusterRouterFactory;
}
public void setMessagePullPolicy(String messagePullPolicy)
{
this.messagePullPolicy = messagePullPolicy;
}
public String listBindings()
{
return postOffice.printBindingInformation();
}
// Public --------------------------------------------------------
// Package protected ---------------------------------------------
// ServiceMBeanSupport overrides ---------------------------------
protected synchronized void startService() throws Exception
{
if (started)
{
throw new IllegalStateException("Service is already started");
}
super.startService();
try
{
TransactionManager tm = getTransactionManagerReference();
ServerPeer serverPeer = (ServerPeer)server.getAttribute(serverPeerObjectName, "Instance");
MessageStore ms = serverPeer.getMessageStore();
TransactionRepository tr = serverPeer.getTxRepository();
PersistenceManager pm = serverPeer.getPersistenceManagerInstance();
QueuedExecutorPool pool = serverPeer.getQueuedExecutorPool();
int nodeId = serverPeer.getServerPeerID();
Class clazz = Class.forName(messagePullPolicy);
MessagePullPolicy pullPolicy = (MessagePullPolicy)clazz.newInstance();
clazz = Class.forName(clusterRouterFactory);
ClusterRouterFactory rf = (ClusterRouterFactory)clazz.newInstance();
ConditionFactory cf = new JMSConditionFactory();
FilterFactory ff = new SelectorFactory();
FailoverMapper mapper = new DefaultFailoverMapper();
JChannelFactory jChannelFactory = null;
if (channelFactoryName != null)
{
Object info = null;
try
{
info = server.getMBeanInfo(channelFactoryName);
}
catch (Exception e)
{
- log.error("Error", e);
+ // log.error("Error", e);
// noop... means we couldn't find the channel hence we should use regular XMLChannelFactories
}
if (info!=null)
{
log.debug(this + " uses MultiplexerJChannelFactory");
jChannelFactory =
new MultiplexerJChannelFactory(server, channelFactoryName, channelPartitionName,
syncChannelName, asyncChannelName);
}
else
{
log.debug(this + " uses XMLJChannelFactory");
jChannelFactory = new XMLJChannelFactory(syncChannelConfig, asyncChannelConfig);
}
}
else
{
log.debug(this + " uses XMLJChannelFactory");
jChannelFactory = new XMLJChannelFactory(syncChannelConfig, asyncChannelConfig);
}
postOffice = new DefaultClusteredPostOffice(ds, tm, sqlProperties,
createTablesOnStartup,
nodeId, officeName, ms,
pm, tr, ff, cf, pool,
groupName,
jChannelFactory,
stateTimeout, castTimeout,
pullPolicy, rf,
mapper,
statsSendPeriod);
postOffice.start();
started = true;
}
catch (Throwable t)
{
throw ExceptionUtil.handleJMXInvocation(t, this + " startService");
}
}
protected void stopService() throws Exception
{
if (!started)
{
throw new IllegalStateException("Service is not started");
}
super.stopService();
try
{
postOffice.stop();
postOffice = null;
started = false;
log.debug(this + " stopped");
}
catch (Throwable t)
{
throw ExceptionUtil.handleJMXInvocation(t, this + " startService");
}
}
// Protected -----------------------------------------------------
// Private -------------------------------------------------------
// Inner classes -------------------------------------------------
}
| true | true | protected synchronized void startService() throws Exception
{
if (started)
{
throw new IllegalStateException("Service is already started");
}
super.startService();
try
{
TransactionManager tm = getTransactionManagerReference();
ServerPeer serverPeer = (ServerPeer)server.getAttribute(serverPeerObjectName, "Instance");
MessageStore ms = serverPeer.getMessageStore();
TransactionRepository tr = serverPeer.getTxRepository();
PersistenceManager pm = serverPeer.getPersistenceManagerInstance();
QueuedExecutorPool pool = serverPeer.getQueuedExecutorPool();
int nodeId = serverPeer.getServerPeerID();
Class clazz = Class.forName(messagePullPolicy);
MessagePullPolicy pullPolicy = (MessagePullPolicy)clazz.newInstance();
clazz = Class.forName(clusterRouterFactory);
ClusterRouterFactory rf = (ClusterRouterFactory)clazz.newInstance();
ConditionFactory cf = new JMSConditionFactory();
FilterFactory ff = new SelectorFactory();
FailoverMapper mapper = new DefaultFailoverMapper();
JChannelFactory jChannelFactory = null;
if (channelFactoryName != null)
{
Object info = null;
try
{
info = server.getMBeanInfo(channelFactoryName);
}
catch (Exception e)
{
log.error("Error", e);
// noop... means we couldn't find the channel hence we should use regular XMLChannelFactories
}
if (info!=null)
{
log.debug(this + " uses MultiplexerJChannelFactory");
jChannelFactory =
new MultiplexerJChannelFactory(server, channelFactoryName, channelPartitionName,
syncChannelName, asyncChannelName);
}
else
{
log.debug(this + " uses XMLJChannelFactory");
jChannelFactory = new XMLJChannelFactory(syncChannelConfig, asyncChannelConfig);
}
}
else
{
log.debug(this + " uses XMLJChannelFactory");
jChannelFactory = new XMLJChannelFactory(syncChannelConfig, asyncChannelConfig);
}
postOffice = new DefaultClusteredPostOffice(ds, tm, sqlProperties,
createTablesOnStartup,
nodeId, officeName, ms,
pm, tr, ff, cf, pool,
groupName,
jChannelFactory,
stateTimeout, castTimeout,
pullPolicy, rf,
mapper,
statsSendPeriod);
postOffice.start();
started = true;
}
catch (Throwable t)
{
throw ExceptionUtil.handleJMXInvocation(t, this + " startService");
}
}
| protected synchronized void startService() throws Exception
{
if (started)
{
throw new IllegalStateException("Service is already started");
}
super.startService();
try
{
TransactionManager tm = getTransactionManagerReference();
ServerPeer serverPeer = (ServerPeer)server.getAttribute(serverPeerObjectName, "Instance");
MessageStore ms = serverPeer.getMessageStore();
TransactionRepository tr = serverPeer.getTxRepository();
PersistenceManager pm = serverPeer.getPersistenceManagerInstance();
QueuedExecutorPool pool = serverPeer.getQueuedExecutorPool();
int nodeId = serverPeer.getServerPeerID();
Class clazz = Class.forName(messagePullPolicy);
MessagePullPolicy pullPolicy = (MessagePullPolicy)clazz.newInstance();
clazz = Class.forName(clusterRouterFactory);
ClusterRouterFactory rf = (ClusterRouterFactory)clazz.newInstance();
ConditionFactory cf = new JMSConditionFactory();
FilterFactory ff = new SelectorFactory();
FailoverMapper mapper = new DefaultFailoverMapper();
JChannelFactory jChannelFactory = null;
if (channelFactoryName != null)
{
Object info = null;
try
{
info = server.getMBeanInfo(channelFactoryName);
}
catch (Exception e)
{
// log.error("Error", e);
// noop... means we couldn't find the channel hence we should use regular XMLChannelFactories
}
if (info!=null)
{
log.debug(this + " uses MultiplexerJChannelFactory");
jChannelFactory =
new MultiplexerJChannelFactory(server, channelFactoryName, channelPartitionName,
syncChannelName, asyncChannelName);
}
else
{
log.debug(this + " uses XMLJChannelFactory");
jChannelFactory = new XMLJChannelFactory(syncChannelConfig, asyncChannelConfig);
}
}
else
{
log.debug(this + " uses XMLJChannelFactory");
jChannelFactory = new XMLJChannelFactory(syncChannelConfig, asyncChannelConfig);
}
postOffice = new DefaultClusteredPostOffice(ds, tm, sqlProperties,
createTablesOnStartup,
nodeId, officeName, ms,
pm, tr, ff, cf, pool,
groupName,
jChannelFactory,
stateTimeout, castTimeout,
pullPolicy, rf,
mapper,
statsSendPeriod);
postOffice.start();
started = true;
}
catch (Throwable t)
{
throw ExceptionUtil.handleJMXInvocation(t, this + " startService");
}
}
|
diff --git a/tools/makedict/src/com/android/inputmethod/latin/FusionDictionary.java b/tools/makedict/src/com/android/inputmethod/latin/FusionDictionary.java
index 031f35df..f6220eea 100644
--- a/tools/makedict/src/com/android/inputmethod/latin/FusionDictionary.java
+++ b/tools/makedict/src/com/android/inputmethod/latin/FusionDictionary.java
@@ -1,602 +1,602 @@
/*
* 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.inputmethod.latin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* A dictionary that can fusion heads and tails of words for more compression.
*/
public class FusionDictionary implements Iterable<Word> {
/**
* A node of the dictionary, containing several CharGroups.
*
* A node is but an ordered array of CharGroups, which essentially contain all the
* real information.
* This class also contains fields to cache size and address, to help with binary
* generation.
*/
public static class Node {
ArrayList<CharGroup> mData;
// To help with binary generation
int mCachedSize;
int mCachedAddress;
public Node() {
mData = new ArrayList<CharGroup>();
mCachedSize = Integer.MIN_VALUE;
mCachedAddress = Integer.MIN_VALUE;
}
public Node(ArrayList<CharGroup> data) {
mData = data;
mCachedSize = Integer.MIN_VALUE;
mCachedAddress = Integer.MIN_VALUE;
}
}
/**
* A string with a frequency.
*
* This represents an "attribute", that is either a bigram or a shortcut.
*/
public static class WeightedString {
final String mWord;
final int mFrequency;
public WeightedString(String word, int frequency) {
mWord = word;
mFrequency = frequency;
}
}
/**
* A group of characters, with a frequency, shortcuts, bigrams, and children.
*
* This is the central class of the in-memory representation. A CharGroup is what can
* be seen as a traditional "trie node", except it can hold several characters at the
* same time. A CharGroup essentially represents one or several characters in the middle
* of the trie trie; as such, it can be a terminal, and it can have children.
* In this in-memory representation, whether the CharGroup is a terminal or not is represented
* in the frequency, where NOT_A_TERMINAL (= -1) means this is not a terminal and any other
* value is the frequency of this terminal. A terminal may have non-null shortcuts and/or
* bigrams, but a non-terminal may not. Moreover, children, if present, are null.
*/
public static class CharGroup {
public static final int NOT_A_TERMINAL = -1;
final int mChars[];
final ArrayList<WeightedString> mBigrams;
final int mFrequency; // NOT_A_TERMINAL == mFrequency indicates this is not a terminal.
Node mChildren;
// The two following members to help with binary generation
int mCachedSize;
int mCachedAddress;
public CharGroup(final int[] chars,
final ArrayList<WeightedString> bigrams, final int frequency) {
mChars = chars;
mFrequency = frequency;
mBigrams = bigrams;
mChildren = null;
}
public CharGroup(final int[] chars,
final ArrayList<WeightedString> bigrams, final int frequency, final Node children) {
mChars = chars;
mFrequency = frequency;
mBigrams = bigrams;
mChildren = children;
}
public void addChild(CharGroup n) {
if (null == mChildren) {
mChildren = new Node();
}
mChildren.mData.add(n);
}
public boolean isTerminal() {
return NOT_A_TERMINAL != mFrequency;
}
public boolean hasSeveralChars() {
assert(mChars.length > 0);
return 1 < mChars.length;
}
}
/**
* Options global to the dictionary.
*
* There are no options at the moment, so this class is empty.
*/
public static class DictionaryOptions {
}
public final DictionaryOptions mOptions;
public final Node mRoot;
public FusionDictionary() {
mOptions = new DictionaryOptions();
mRoot = new Node();
}
public FusionDictionary(final Node root, final DictionaryOptions options) {
mRoot = root;
mOptions = options;
}
/**
* Helper method to convert a String to an int array.
*/
static private int[] getCodePoints(String word) {
final int wordLength = word.length();
int[] array = new int[word.codePointCount(0, wordLength)];
for (int i = 0; i < wordLength; ++i) {
array[i] = word.codePointAt(i);
}
return array;
}
/**
* Helper method to add a word as a string.
*
* This method adds a word to the dictionary with the given frequency. Optional
* lists of bigrams and shortcuts can be passed here. For each word inside,
* they will be added to the dictionary as necessary.
*
* @param word the word to add.
* @param frequency the frequency of the word, in the range [0..255].
* @param bigrams a list of bigrams, or null.
*/
public void add(String word, int frequency, ArrayList<WeightedString> bigrams) {
if (null != bigrams) {
for (WeightedString bigram : bigrams) {
final CharGroup t = findWordInTree(mRoot, bigram.mWord);
if (null == t) {
add(getCodePoints(bigram.mWord), 0, null);
}
}
}
add(getCodePoints(word), frequency, bigrams);
}
/**
* Sanity check for a node.
*
* This method checks that all CharGroups in a node are ordered as expected.
* If they are, nothing happens. If they aren't, an exception is thrown.
*/
private void checkStack(Node node) {
ArrayList<CharGroup> stack = node.mData;
int lastValue = -1;
for (int i = 0; i < stack.size(); ++i) {
int currentValue = stack.get(i).mChars[0];
if (currentValue <= lastValue)
throw new RuntimeException("Invalid stack");
else
lastValue = currentValue;
}
}
/**
* Add a word to this dictionary.
*
* The bigrams, if any, have to be in the dictionary already. If they aren't,
* an exception is thrown.
*
* @param word the word, as an int array.
* @param frequency the frequency of the word, in the range [0..255].
* @param bigrams an optional list of bigrams for this word (null if none).
*/
private void add(int[] word, int frequency, ArrayList<WeightedString> bigrams) {
assert(frequency >= 0 && frequency <= 255);
Node currentNode = mRoot;
int charIndex = 0;
CharGroup currentGroup = null;
int differentCharIndex = 0; // Set by the loop to the index of the char that differs
int nodeIndex = findIndexOfChar(mRoot, word[charIndex]);
while (CHARACTER_NOT_FOUND != nodeIndex) {
currentGroup = currentNode.mData.get(nodeIndex);
- differentCharIndex = compareArrays(currentGroup.mChars, word, charIndex) ;
+ differentCharIndex = compareArrays(currentGroup.mChars, word, charIndex);
if (ARRAYS_ARE_EQUAL != differentCharIndex
&& differentCharIndex < currentGroup.mChars.length) break;
if (null == currentGroup.mChildren) break;
charIndex += currentGroup.mChars.length;
if (charIndex >= word.length) break;
currentNode = currentGroup.mChildren;
nodeIndex = findIndexOfChar(currentNode, word[charIndex]);
}
if (-1 == nodeIndex) {
// No node at this point to accept the word. Create one.
final int insertionIndex = findInsertionIndex(currentNode, word[charIndex]);
final CharGroup newGroup = new CharGroup(
Arrays.copyOfRange(word, charIndex, word.length), bigrams, frequency);
currentNode.mData.add(insertionIndex, newGroup);
checkStack(currentNode);
} else {
// There is a word with a common prefix.
if (differentCharIndex == currentGroup.mChars.length) {
if (charIndex + differentCharIndex >= word.length) {
// The new word is a prefix of an existing word, but the node on which it
// should end already exists as is.
if (currentGroup.mFrequency > 0) {
throw new RuntimeException("Such a word already exists in the dictionary : "
+ new String(word, 0, word.length));
} else {
final CharGroup newNode = new CharGroup(currentGroup.mChars,
bigrams, frequency, currentGroup.mChildren);
currentNode.mData.set(nodeIndex, newNode);
checkStack(currentNode);
}
} else {
// The new word matches the full old word and extends past it.
// We only have to create a new node and add it to the end of this.
final CharGroup newNode = new CharGroup(
Arrays.copyOfRange(word, charIndex + differentCharIndex, word.length),
bigrams, frequency);
currentGroup.mChildren = new Node();
currentGroup.mChildren.mData.add(newNode);
}
} else {
if (0 == differentCharIndex) {
// Exact same word. Check the frequency is 0 or -1, and update.
if (0 != frequency) {
if (0 < currentGroup.mFrequency) {
throw new RuntimeException("This word already exists with frequency "
+ currentGroup.mFrequency + " : "
+ new String(word, 0, word.length));
}
final CharGroup newGroup = new CharGroup(word,
- currentGroup.mBigrams, frequency);
+ currentGroup.mBigrams, frequency, currentGroup.mChildren);
currentNode.mData.set(nodeIndex, newGroup);
}
} else {
// Partial prefix match only. We have to replace the current node with a node
// containing the current prefix and create two new ones for the tails.
Node newChildren = new Node();
final CharGroup newOldWord = new CharGroup(
Arrays.copyOfRange(currentGroup.mChars, differentCharIndex,
currentGroup.mChars.length),
currentGroup.mBigrams, currentGroup.mFrequency, currentGroup.mChildren);
newChildren.mData.add(newOldWord);
final CharGroup newParent;
if (charIndex + differentCharIndex >= word.length) {
newParent = new CharGroup(
Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex),
bigrams, frequency, newChildren);
} else {
newParent = new CharGroup(
Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex),
null, -1, newChildren);
final CharGroup newWord = new CharGroup(
Arrays.copyOfRange(word, charIndex + differentCharIndex,
word.length), bigrams, frequency);
final int addIndex = word[charIndex + differentCharIndex]
> currentGroup.mChars[differentCharIndex] ? 1 : 0;
newChildren.mData.add(addIndex, newWord);
}
currentNode.mData.set(nodeIndex, newParent);
}
checkStack(currentNode);
}
}
}
/**
* Custom comparison of two int arrays taken to contain character codes.
*
* This method compares the two arrays passed as an argument in a lexicographic way,
* with an offset in the dst string.
* This method does NOT test for the first character. It is taken to be equal.
* I repeat: this method starts the comparison at 1 <> dstOffset + 1.
* The index where the strings differ is returned. ARRAYS_ARE_EQUAL = 0 is returned if the
* strings are equal. This works BECAUSE we don't look at the first character.
*
* @param src the left-hand side string of the comparison.
* @param dst the right-hand side string of the comparison.
* @param dstOffset the offset in the right-hand side string.
* @return the index at which the strings differ, or ARRAYS_ARE_EQUAL = 0 if they don't.
*/
private static int ARRAYS_ARE_EQUAL = 0;
private static int compareArrays(final int[] src, final int[] dst, int dstOffset) {
// We do NOT test the first char, because we come from a method that already
// tested it.
for (int i = 1; i < src.length; ++i) {
if (dstOffset + i >= dst.length) return i;
if (src[i] != dst[dstOffset + i]) return i;
}
if (dst.length > src.length) return src.length;
return ARRAYS_ARE_EQUAL;
}
/**
* Helper class that compares and sorts two chargroups according to their
* first element only. I repeat: ONLY the first element is considered, the rest
* is ignored.
* This comparator imposes orderings that are inconsistent with equals.
*/
static private class CharGroupComparator implements java.util.Comparator {
public int compare(Object o1, Object o2) {
final CharGroup c1 = (CharGroup)o1;
final CharGroup c2 = (CharGroup)o2;
if (c1.mChars[0] == c2.mChars[0]) return 0;
return c1.mChars[0] < c2.mChars[0] ? -1 : 1;
}
public boolean equals(Object o) {
return o instanceof CharGroupComparator;
}
}
final static private CharGroupComparator CHARGROUP_COMPARATOR = new CharGroupComparator();
/**
* Finds the insertion index of a character within a node.
*/
private static int findInsertionIndex(final Node node, int character) {
final List data = node.mData;
final CharGroup reference = new CharGroup(new int[] { character }, null, 0);
int result = Collections.binarySearch(data, reference, CHARGROUP_COMPARATOR);
return result >= 0 ? result : -result - 1;
}
/**
* Find the index of a char in a node, if it exists.
*
* @param node the node to search in.
* @param character the character to search for.
* @return the position of the character if it's there, or CHARACTER_NOT_FOUND = -1 else.
*/
private static int CHARACTER_NOT_FOUND = -1;
private static int findIndexOfChar(final Node node, int character) {
final int insertionIndex = findInsertionIndex(node, character);
if (node.mData.size() <= insertionIndex) return CHARACTER_NOT_FOUND;
return character == node.mData.get(insertionIndex).mChars[0] ? insertionIndex
: CHARACTER_NOT_FOUND;
}
/**
* Helper method to find a word in a given branch.
*/
public static CharGroup findWordInTree(Node node, final String s) {
int index = 0;
final StringBuilder checker = new StringBuilder();
CharGroup currentGroup;
do {
int indexOfGroup = findIndexOfChar(node, s.codePointAt(index));
if (CHARACTER_NOT_FOUND == indexOfGroup) return null;
currentGroup = node.mData.get(indexOfGroup);
checker.append(new String(currentGroup.mChars, 0, currentGroup.mChars.length));
index += currentGroup.mChars.length;
if (index < s.length()) {
node = currentGroup.mChildren;
}
} while (null != node && index < s.length());
if (!s.equals(checker.toString())) return null;
return currentGroup;
}
/**
* Recursively count the number of character groups in a given branch of the trie.
*
* @param node the parent node.
* @return the number of char groups in all the branch under this node.
*/
public static int countCharGroups(final Node node) {
final int nodeSize = node.mData.size();
int size = nodeSize;
for (int i = nodeSize - 1; i >= 0; --i) {
CharGroup group = node.mData.get(i);
if (null != group.mChildren)
size += countCharGroups(group.mChildren);
}
return size;
}
/**
* Recursively count the number of nodes in a given branch of the trie.
*
* @param node the node to count.
* @result the number of nodes in this branch.
*/
public static int countNodes(final Node node) {
int size = 1;
for (int i = node.mData.size() - 1; i >= 0; --i) {
CharGroup group = node.mData.get(i);
if (null != group.mChildren)
size += countNodes(group.mChildren);
}
return size;
}
// Historically, the tails of the words were going to be merged to save space.
// However, that would prevent the code to search for a specific address in log(n)
// time so this was abandoned.
// The code is still of interest as it does add some compression to any dictionary
// that has no need for attributes. Implementations that does not read attributes should be
// able to read a dictionary with merged tails.
// Also, the following code does support frequencies, as in, it will only merges
// tails that share the same frequency. Though it would result in the above loss of
// performance while searching by address, it is still technically possible to merge
// tails that contain attributes, but this code does not take that into account - it does
// not compare attributes and will merge terminals with different attributes regardless.
public void mergeTails() {
MakedictLog.i("Do not merge tails");
return;
// MakedictLog.i("Merging nodes. Number of nodes : " + countNodes(root));
// MakedictLog.i("Number of groups : " + countCharGroups(root));
//
// final HashMap<String, ArrayList<Node>> repository =
// new HashMap<String, ArrayList<Node>>();
// mergeTailsInner(repository, root);
//
// MakedictLog.i("Number of different pseudohashes : " + repository.size());
// int size = 0;
// for (ArrayList<Node> a : repository.values()) {
// size += a.size();
// }
// MakedictLog.i("Number of nodes after merge : " + (1 + size));
// MakedictLog.i("Recursively seen nodes : " + countNodes(root));
}
// The following methods are used by the deactivated mergeTails()
// private static boolean isEqual(Node a, Node b) {
// if (null == a && null == b) return true;
// if (null == a || null == b) return false;
// if (a.data.size() != b.data.size()) return false;
// final int size = a.data.size();
// for (int i = size - 1; i >= 0; --i) {
// CharGroup aGroup = a.data.get(i);
// CharGroup bGroup = b.data.get(i);
// if (aGroup.frequency != bGroup.frequency) return false;
// if (aGroup.alternates == null && bGroup.alternates != null) return false;
// if (aGroup.alternates != null && !aGroup.equals(bGroup.alternates)) return false;
// if (!Arrays.equals(aGroup.chars, bGroup.chars)) return false;
// if (!isEqual(aGroup.children, bGroup.children)) return false;
// }
// return true;
// }
// static private HashMap<String, ArrayList<Node>> mergeTailsInner(
// final HashMap<String, ArrayList<Node>> map, final Node node) {
// final ArrayList<CharGroup> branches = node.data;
// final int nodeSize = branches.size();
// for (int i = 0; i < nodeSize; ++i) {
// CharGroup group = branches.get(i);
// if (null != group.children) {
// String pseudoHash = getPseudoHash(group.children);
// ArrayList<Node> similarList = map.get(pseudoHash);
// if (null == similarList) {
// similarList = new ArrayList<Node>();
// map.put(pseudoHash, similarList);
// }
// boolean merged = false;
// for (Node similar : similarList) {
// if (isEqual(group.children, similar)) {
// group.children = similar;
// merged = true;
// break;
// }
// }
// if (!merged) {
// similarList.add(group.children);
// }
// mergeTailsInner(map, group.children);
// }
// }
// return map;
// }
// private static String getPseudoHash(final Node node) {
// StringBuilder s = new StringBuilder();
// for (CharGroup g : node.data) {
// s.append(g.frequency);
// for (int ch : g.chars){
// s.append(Character.toChars(ch));
// }
// }
// return s.toString();
// }
/**
* Iterator to walk through a dictionary.
*
* This is purely for convenience.
*/
public static class DictionaryIterator implements Iterator<Word> {
private static class Position {
public Iterator<CharGroup> pos;
public int length;
public Position(ArrayList<CharGroup> groups) {
pos = groups.iterator();
length = 0;
}
}
final StringBuilder mCurrentString;
final LinkedList<Position> mPositions;
public DictionaryIterator(ArrayList<CharGroup> root) {
mCurrentString = new StringBuilder();
mPositions = new LinkedList<Position>();
final Position rootPos = new Position(root);
mPositions.add(rootPos);
}
@Override
public boolean hasNext() {
for (Position p : mPositions) {
if (p.pos.hasNext()) {
return true;
}
}
return false;
}
@Override
public Word next() {
Position currentPos = mPositions.getLast();
mCurrentString.setLength(mCurrentString.length() - currentPos.length);
do {
if (currentPos.pos.hasNext()) {
final CharGroup currentGroup = currentPos.pos.next();
currentPos.length = currentGroup.mChars.length;
for (int i : currentGroup.mChars)
mCurrentString.append(Character.toChars(i));
if (null != currentGroup.mChildren) {
currentPos = new Position(currentGroup.mChildren.mData);
mPositions.addLast(currentPos);
}
if (currentGroup.mFrequency >= 0)
return new Word(mCurrentString.toString(), currentGroup.mFrequency,
currentGroup.mBigrams);
} else {
mPositions.removeLast();
currentPos = mPositions.getLast();
mCurrentString.setLength(mCurrentString.length() - mPositions.getLast().length);
}
} while(true);
}
@Override
public void remove() {
throw new UnsupportedOperationException("Unsupported yet");
}
}
/**
* Method to return an iterator.
*
* This method enables Java's enhanced for loop. With this you can have a FusionDictionary x
* and say : for (Word w : x) {}
*/
@Override
public Iterator<Word> iterator() {
return new DictionaryIterator(mRoot.mData);
}
}
| false | true | private void add(int[] word, int frequency, ArrayList<WeightedString> bigrams) {
assert(frequency >= 0 && frequency <= 255);
Node currentNode = mRoot;
int charIndex = 0;
CharGroup currentGroup = null;
int differentCharIndex = 0; // Set by the loop to the index of the char that differs
int nodeIndex = findIndexOfChar(mRoot, word[charIndex]);
while (CHARACTER_NOT_FOUND != nodeIndex) {
currentGroup = currentNode.mData.get(nodeIndex);
differentCharIndex = compareArrays(currentGroup.mChars, word, charIndex) ;
if (ARRAYS_ARE_EQUAL != differentCharIndex
&& differentCharIndex < currentGroup.mChars.length) break;
if (null == currentGroup.mChildren) break;
charIndex += currentGroup.mChars.length;
if (charIndex >= word.length) break;
currentNode = currentGroup.mChildren;
nodeIndex = findIndexOfChar(currentNode, word[charIndex]);
}
if (-1 == nodeIndex) {
// No node at this point to accept the word. Create one.
final int insertionIndex = findInsertionIndex(currentNode, word[charIndex]);
final CharGroup newGroup = new CharGroup(
Arrays.copyOfRange(word, charIndex, word.length), bigrams, frequency);
currentNode.mData.add(insertionIndex, newGroup);
checkStack(currentNode);
} else {
// There is a word with a common prefix.
if (differentCharIndex == currentGroup.mChars.length) {
if (charIndex + differentCharIndex >= word.length) {
// The new word is a prefix of an existing word, but the node on which it
// should end already exists as is.
if (currentGroup.mFrequency > 0) {
throw new RuntimeException("Such a word already exists in the dictionary : "
+ new String(word, 0, word.length));
} else {
final CharGroup newNode = new CharGroup(currentGroup.mChars,
bigrams, frequency, currentGroup.mChildren);
currentNode.mData.set(nodeIndex, newNode);
checkStack(currentNode);
}
} else {
// The new word matches the full old word and extends past it.
// We only have to create a new node and add it to the end of this.
final CharGroup newNode = new CharGroup(
Arrays.copyOfRange(word, charIndex + differentCharIndex, word.length),
bigrams, frequency);
currentGroup.mChildren = new Node();
currentGroup.mChildren.mData.add(newNode);
}
} else {
if (0 == differentCharIndex) {
// Exact same word. Check the frequency is 0 or -1, and update.
if (0 != frequency) {
if (0 < currentGroup.mFrequency) {
throw new RuntimeException("This word already exists with frequency "
+ currentGroup.mFrequency + " : "
+ new String(word, 0, word.length));
}
final CharGroup newGroup = new CharGroup(word,
currentGroup.mBigrams, frequency);
currentNode.mData.set(nodeIndex, newGroup);
}
} else {
// Partial prefix match only. We have to replace the current node with a node
// containing the current prefix and create two new ones for the tails.
Node newChildren = new Node();
final CharGroup newOldWord = new CharGroup(
Arrays.copyOfRange(currentGroup.mChars, differentCharIndex,
currentGroup.mChars.length),
currentGroup.mBigrams, currentGroup.mFrequency, currentGroup.mChildren);
newChildren.mData.add(newOldWord);
final CharGroup newParent;
if (charIndex + differentCharIndex >= word.length) {
newParent = new CharGroup(
Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex),
bigrams, frequency, newChildren);
} else {
newParent = new CharGroup(
Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex),
null, -1, newChildren);
final CharGroup newWord = new CharGroup(
Arrays.copyOfRange(word, charIndex + differentCharIndex,
word.length), bigrams, frequency);
final int addIndex = word[charIndex + differentCharIndex]
> currentGroup.mChars[differentCharIndex] ? 1 : 0;
newChildren.mData.add(addIndex, newWord);
}
currentNode.mData.set(nodeIndex, newParent);
}
checkStack(currentNode);
}
}
}
| private void add(int[] word, int frequency, ArrayList<WeightedString> bigrams) {
assert(frequency >= 0 && frequency <= 255);
Node currentNode = mRoot;
int charIndex = 0;
CharGroup currentGroup = null;
int differentCharIndex = 0; // Set by the loop to the index of the char that differs
int nodeIndex = findIndexOfChar(mRoot, word[charIndex]);
while (CHARACTER_NOT_FOUND != nodeIndex) {
currentGroup = currentNode.mData.get(nodeIndex);
differentCharIndex = compareArrays(currentGroup.mChars, word, charIndex);
if (ARRAYS_ARE_EQUAL != differentCharIndex
&& differentCharIndex < currentGroup.mChars.length) break;
if (null == currentGroup.mChildren) break;
charIndex += currentGroup.mChars.length;
if (charIndex >= word.length) break;
currentNode = currentGroup.mChildren;
nodeIndex = findIndexOfChar(currentNode, word[charIndex]);
}
if (-1 == nodeIndex) {
// No node at this point to accept the word. Create one.
final int insertionIndex = findInsertionIndex(currentNode, word[charIndex]);
final CharGroup newGroup = new CharGroup(
Arrays.copyOfRange(word, charIndex, word.length), bigrams, frequency);
currentNode.mData.add(insertionIndex, newGroup);
checkStack(currentNode);
} else {
// There is a word with a common prefix.
if (differentCharIndex == currentGroup.mChars.length) {
if (charIndex + differentCharIndex >= word.length) {
// The new word is a prefix of an existing word, but the node on which it
// should end already exists as is.
if (currentGroup.mFrequency > 0) {
throw new RuntimeException("Such a word already exists in the dictionary : "
+ new String(word, 0, word.length));
} else {
final CharGroup newNode = new CharGroup(currentGroup.mChars,
bigrams, frequency, currentGroup.mChildren);
currentNode.mData.set(nodeIndex, newNode);
checkStack(currentNode);
}
} else {
// The new word matches the full old word and extends past it.
// We only have to create a new node and add it to the end of this.
final CharGroup newNode = new CharGroup(
Arrays.copyOfRange(word, charIndex + differentCharIndex, word.length),
bigrams, frequency);
currentGroup.mChildren = new Node();
currentGroup.mChildren.mData.add(newNode);
}
} else {
if (0 == differentCharIndex) {
// Exact same word. Check the frequency is 0 or -1, and update.
if (0 != frequency) {
if (0 < currentGroup.mFrequency) {
throw new RuntimeException("This word already exists with frequency "
+ currentGroup.mFrequency + " : "
+ new String(word, 0, word.length));
}
final CharGroup newGroup = new CharGroup(word,
currentGroup.mBigrams, frequency, currentGroup.mChildren);
currentNode.mData.set(nodeIndex, newGroup);
}
} else {
// Partial prefix match only. We have to replace the current node with a node
// containing the current prefix and create two new ones for the tails.
Node newChildren = new Node();
final CharGroup newOldWord = new CharGroup(
Arrays.copyOfRange(currentGroup.mChars, differentCharIndex,
currentGroup.mChars.length),
currentGroup.mBigrams, currentGroup.mFrequency, currentGroup.mChildren);
newChildren.mData.add(newOldWord);
final CharGroup newParent;
if (charIndex + differentCharIndex >= word.length) {
newParent = new CharGroup(
Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex),
bigrams, frequency, newChildren);
} else {
newParent = new CharGroup(
Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex),
null, -1, newChildren);
final CharGroup newWord = new CharGroup(
Arrays.copyOfRange(word, charIndex + differentCharIndex,
word.length), bigrams, frequency);
final int addIndex = word[charIndex + differentCharIndex]
> currentGroup.mChars[differentCharIndex] ? 1 : 0;
newChildren.mData.add(addIndex, newWord);
}
currentNode.mData.set(nodeIndex, newParent);
}
checkStack(currentNode);
}
}
}
|
diff --git a/org.eclipse.egit.core/src/org/eclipse/egit/core/op/CloneOperation.java b/org.eclipse.egit.core/src/org/eclipse/egit/core/op/CloneOperation.java
index c75bde69..c90a9064 100644
--- a/org.eclipse.egit.core/src/org/eclipse/egit/core/op/CloneOperation.java
+++ b/org.eclipse.egit.core/src/org/eclipse/egit/core/op/CloneOperation.java
@@ -1,199 +1,201 @@
/*******************************************************************************
* Copyright (C) 2007, Dave Watson <[email protected]>
* Copyright (C) 2008, Robin Rosenberg <[email protected]>
* Copyright (C) 2008, Roger C. Soares <[email protected]>
* Copyright (C) 2008, Shawn O. Pearce <[email protected]>
* Copyright (C) 2008, Marek Zawirski <[email protected]>
*
* 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
*******************************************************************************/
package org.eclipse.egit.core.op;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.egit.core.CoreText;
import org.eclipse.egit.core.EclipseGitProgressTransformer;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.jgit.util.FileUtils;
import org.eclipse.osgi.util.NLS;
/**
* Clones a repository from a remote location to a local location.
*/
public class CloneOperation {
private final URIish uri;
private final boolean allSelected;
private final Collection<Ref> selectedBranches;
private final File workdir;
private final File gitdir;
private final String refName;
private final String remoteName;
private final int timeout;
private CredentialsProvider credentialsProvider;
private List<PostCloneTask> postCloneTasks;
/**
* Create a new clone operation.
*
* @param uri
* remote we should fetch from.
* @param allSelected
* true when all branches have to be fetched (indicates wildcard
* in created fetch refspec), false otherwise.
* @param selectedBranches
* collection of branches to fetch. Ignored when allSelected is
* true.
* @param workdir
* working directory to clone to. The directory may or may not
* already exist.
* @param refName
* full name of ref to be checked out after clone, e.g.
* refs/heads/master, or null for no checkout
* @param remoteName
* name of created remote config as source remote (typically
* named "origin").
* @param timeout
* timeout in seconds
*/
public CloneOperation(final URIish uri, final boolean allSelected,
final Collection<Ref> selectedBranches, final File workdir,
final String refName, final String remoteName, int timeout) {
this.uri = uri;
this.allSelected = allSelected;
this.selectedBranches = selectedBranches;
this.workdir = workdir;
this.gitdir = new File(workdir, Constants.DOT_GIT);
this.refName = refName;
this.remoteName = remoteName;
this.timeout = timeout;
}
/**
* Sets a credentials provider
* @param credentialsProvider
*/
public void setCredentialsProvider(CredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider;
}
/**
* @param pm
* the monitor to be used for reporting progress and responding
* to cancellation. The monitor is never <code>null</code>
* @throws InvocationTargetException
* @throws InterruptedException
*/
public void run(final IProgressMonitor pm)
throws InvocationTargetException, InterruptedException {
final IProgressMonitor monitor;
if (pm == null)
monitor = new NullProgressMonitor();
else
monitor = pm;
EclipseGitProgressTransformer gitMonitor = new EclipseGitProgressTransformer(
monitor);
Repository repository = null;
try {
monitor.beginTask(NLS.bind(CoreText.CloneOperation_title, uri),
5000);
CloneCommand cloneRepository = Git.cloneRepository();
cloneRepository.setCredentialsProvider(credentialsProvider);
if (refName != null)
cloneRepository.setBranch(refName);
cloneRepository.setDirectory(workdir);
cloneRepository.setProgressMonitor(gitMonitor);
cloneRepository.setRemote(remoteName);
cloneRepository.setURI(uri.toString());
cloneRepository.setTimeout(timeout);
cloneRepository.setCloneAllBranches(allSelected);
if (selectedBranches != null) {
List<String> branches = new ArrayList<String>();
for (Ref branch : selectedBranches)
branches.add(branch.getName());
cloneRepository.setBranchesToClone(branches);
}
Git git = cloneRepository.call();
repository = git.getRepository();
- if (postCloneTasks != null)
- for (PostCloneTask task : postCloneTasks)
- task.execute(git.getRepository(), monitor);
+ synchronized (this) {
+ if (postCloneTasks != null)
+ for (PostCloneTask task : postCloneTasks)
+ task.execute(git.getRepository(), monitor);
+ }
} catch (final Exception e) {
try {
if (repository != null)
repository.close();
FileUtils.delete(workdir, FileUtils.RECURSIVE);
} catch (IOException ioe) {
throw new InvocationTargetException(ioe);
}
if (monitor.isCanceled())
throw new InterruptedException();
else
throw new InvocationTargetException(e);
} finally {
monitor.done();
if (repository != null)
repository.close();
}
}
/**
* @return The git directory which will contain the repository
*/
public File getGitDir() {
return gitdir;
}
/**
* @param task to be performed after clone
*/
public synchronized void addPostCloneTask(PostCloneTask task) {
if (postCloneTasks == null)
postCloneTasks = new ArrayList<PostCloneTask>();
postCloneTasks.add(task);
}
/**
* A task which can be added to be performed after clone
*/
public interface PostCloneTask {
/**
* Executes the task
* @param repository the cloned git repository
*
* @param monitor
* a progress monitor, or <code>null</code> if progress reporting
* and cancellation are not desired
* @throws CoreException
*/
void execute(Repository repository, IProgressMonitor monitor) throws CoreException;
}
}
| true | true | public void run(final IProgressMonitor pm)
throws InvocationTargetException, InterruptedException {
final IProgressMonitor monitor;
if (pm == null)
monitor = new NullProgressMonitor();
else
monitor = pm;
EclipseGitProgressTransformer gitMonitor = new EclipseGitProgressTransformer(
monitor);
Repository repository = null;
try {
monitor.beginTask(NLS.bind(CoreText.CloneOperation_title, uri),
5000);
CloneCommand cloneRepository = Git.cloneRepository();
cloneRepository.setCredentialsProvider(credentialsProvider);
if (refName != null)
cloneRepository.setBranch(refName);
cloneRepository.setDirectory(workdir);
cloneRepository.setProgressMonitor(gitMonitor);
cloneRepository.setRemote(remoteName);
cloneRepository.setURI(uri.toString());
cloneRepository.setTimeout(timeout);
cloneRepository.setCloneAllBranches(allSelected);
if (selectedBranches != null) {
List<String> branches = new ArrayList<String>();
for (Ref branch : selectedBranches)
branches.add(branch.getName());
cloneRepository.setBranchesToClone(branches);
}
Git git = cloneRepository.call();
repository = git.getRepository();
if (postCloneTasks != null)
for (PostCloneTask task : postCloneTasks)
task.execute(git.getRepository(), monitor);
} catch (final Exception e) {
try {
if (repository != null)
repository.close();
FileUtils.delete(workdir, FileUtils.RECURSIVE);
} catch (IOException ioe) {
throw new InvocationTargetException(ioe);
}
if (monitor.isCanceled())
throw new InterruptedException();
else
throw new InvocationTargetException(e);
} finally {
monitor.done();
if (repository != null)
repository.close();
}
}
| public void run(final IProgressMonitor pm)
throws InvocationTargetException, InterruptedException {
final IProgressMonitor monitor;
if (pm == null)
monitor = new NullProgressMonitor();
else
monitor = pm;
EclipseGitProgressTransformer gitMonitor = new EclipseGitProgressTransformer(
monitor);
Repository repository = null;
try {
monitor.beginTask(NLS.bind(CoreText.CloneOperation_title, uri),
5000);
CloneCommand cloneRepository = Git.cloneRepository();
cloneRepository.setCredentialsProvider(credentialsProvider);
if (refName != null)
cloneRepository.setBranch(refName);
cloneRepository.setDirectory(workdir);
cloneRepository.setProgressMonitor(gitMonitor);
cloneRepository.setRemote(remoteName);
cloneRepository.setURI(uri.toString());
cloneRepository.setTimeout(timeout);
cloneRepository.setCloneAllBranches(allSelected);
if (selectedBranches != null) {
List<String> branches = new ArrayList<String>();
for (Ref branch : selectedBranches)
branches.add(branch.getName());
cloneRepository.setBranchesToClone(branches);
}
Git git = cloneRepository.call();
repository = git.getRepository();
synchronized (this) {
if (postCloneTasks != null)
for (PostCloneTask task : postCloneTasks)
task.execute(git.getRepository(), monitor);
}
} catch (final Exception e) {
try {
if (repository != null)
repository.close();
FileUtils.delete(workdir, FileUtils.RECURSIVE);
} catch (IOException ioe) {
throw new InvocationTargetException(ioe);
}
if (monitor.isCanceled())
throw new InterruptedException();
else
throw new InvocationTargetException(e);
} finally {
monitor.done();
if (repository != null)
repository.close();
}
}
|
diff --git a/src/main/java/net/pterodactylus/sone/template/ImageLinkFilter.java b/src/main/java/net/pterodactylus/sone/template/ImageLinkFilter.java
index 9e758cfd..063a1deb 100644
--- a/src/main/java/net/pterodactylus/sone/template/ImageLinkFilter.java
+++ b/src/main/java/net/pterodactylus/sone/template/ImageLinkFilter.java
@@ -1,108 +1,103 @@
/*
* Sone - ImageLinkFilter.java - Copyright © 2011 David Roden
*
* 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 net.pterodactylus.sone.template;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;
import net.pterodactylus.sone.data.Image;
import net.pterodactylus.util.number.Numbers;
import net.pterodactylus.util.object.Default;
import net.pterodactylus.util.template.Filter;
import net.pterodactylus.util.template.Template;
import net.pterodactylus.util.template.TemplateContext;
import net.pterodactylus.util.template.TemplateContextFactory;
import net.pterodactylus.util.template.TemplateParser;
/**
* Template filter that turns an {@link Image} into an HTML <img> tag,
* using some parameters to influence parameters of the image.
*
* @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a>
*/
public class ImageLinkFilter implements Filter {
/** The template to render for the <img> tag. */
private static final Template linkTemplate = TemplateParser.parse(new StringReader("<img<%ifnull !class> class=\"<%class|css>\"<%/if> src=\"<%src|html>\" alt=\"<%alt|html>\" title=\"<%title|html>\" width=\"<%width|html>\" height=\"<%height|html>\" style=\"position: relative;<%ifnull ! top>top: <% top|html>;<%/if><%ifnull ! left>left: <% left|html>;<%/if>\"/>"));
/** The template context factory. */
private final TemplateContextFactory templateContextFactory;
/**
* Creates a new image link filter.
*
* @param templateContextFactory
* The template context factory
*/
public ImageLinkFilter(TemplateContextFactory templateContextFactory) {
this.templateContextFactory = templateContextFactory;
}
/**
* {@inheritDoc}
*/
@Override
public Object format(TemplateContext templateContext, Object data, Map<String, String> parameters) {
Image image = (Image) data;
String imageClass = parameters.get("class");
int maxWidth = Numbers.safeParseInteger(parameters.get("max-width"), Integer.MAX_VALUE);
int maxHeight = Numbers.safeParseInteger(parameters.get("max-height"), Integer.MAX_VALUE);
String mode = String.valueOf(parameters.get("mode"));
String title = parameters.get("title");
if ((title != null) && title.startsWith("=")) {
title = String.valueOf(templateContext.get(title.substring(1)));
}
TemplateContext linkTemplateContext = templateContextFactory.createTemplateContext();
linkTemplateContext.set("class", imageClass);
if (image.isInserted()) {
linkTemplateContext.set("src", "/" + image.getKey());
} else {
linkTemplateContext.set("src", "getImage.html?image=" + image.getId());
}
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
if ("enlarge".equals(mode)) {
double scale = Math.max(maxWidth / (double) imageWidth, maxHeight / (double) imageHeight);
linkTemplateContext.set("width", (int) (imageWidth * scale + 0.5));
linkTemplateContext.set("height", (int) (imageHeight * scale + 0.5));
- if (scale >= 1) {
- linkTemplateContext.set("left", String.format("%dpx", (int) ((imageWidth * scale) - maxWidth) / 2));
- linkTemplateContext.set("top", String.format("%dpx", (int) ((imageHeight * scale) - maxHeight) / 2));
- } else {
- linkTemplateContext.set("left", String.format("%dpx", (int) (maxWidth - (imageWidth * scale)) / 2));
- linkTemplateContext.set("top", String.format("%dpx", (int) (maxHeight - (imageHeight * scale)) / 2));
- }
+ linkTemplateContext.set("left", String.format("%dpx", (int) (maxWidth - (imageWidth * scale)) / 2));
+ linkTemplateContext.set("top", String.format("%dpx", (int) (maxHeight - (imageHeight * scale)) / 2));
} else {
double scale = 1;
if ((imageWidth > maxWidth) || (imageHeight > maxHeight)) {
scale = Math.min(maxWidth / (double) imageWidth, maxHeight / (double) imageHeight);
}
linkTemplateContext.set("width", (int) (imageWidth * scale + 0.5));
linkTemplateContext.set("height", (int) (imageHeight * scale + 0.5));
}
linkTemplateContext.set("alt", Default.forNull(title, image.getDescription()));
linkTemplateContext.set("title", Default.forNull(title, image.getTitle()));
StringWriter stringWriter = new StringWriter();
linkTemplate.render(linkTemplateContext, stringWriter);
return stringWriter.toString();
}
}
| true | true | public Object format(TemplateContext templateContext, Object data, Map<String, String> parameters) {
Image image = (Image) data;
String imageClass = parameters.get("class");
int maxWidth = Numbers.safeParseInteger(parameters.get("max-width"), Integer.MAX_VALUE);
int maxHeight = Numbers.safeParseInteger(parameters.get("max-height"), Integer.MAX_VALUE);
String mode = String.valueOf(parameters.get("mode"));
String title = parameters.get("title");
if ((title != null) && title.startsWith("=")) {
title = String.valueOf(templateContext.get(title.substring(1)));
}
TemplateContext linkTemplateContext = templateContextFactory.createTemplateContext();
linkTemplateContext.set("class", imageClass);
if (image.isInserted()) {
linkTemplateContext.set("src", "/" + image.getKey());
} else {
linkTemplateContext.set("src", "getImage.html?image=" + image.getId());
}
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
if ("enlarge".equals(mode)) {
double scale = Math.max(maxWidth / (double) imageWidth, maxHeight / (double) imageHeight);
linkTemplateContext.set("width", (int) (imageWidth * scale + 0.5));
linkTemplateContext.set("height", (int) (imageHeight * scale + 0.5));
if (scale >= 1) {
linkTemplateContext.set("left", String.format("%dpx", (int) ((imageWidth * scale) - maxWidth) / 2));
linkTemplateContext.set("top", String.format("%dpx", (int) ((imageHeight * scale) - maxHeight) / 2));
} else {
linkTemplateContext.set("left", String.format("%dpx", (int) (maxWidth - (imageWidth * scale)) / 2));
linkTemplateContext.set("top", String.format("%dpx", (int) (maxHeight - (imageHeight * scale)) / 2));
}
} else {
double scale = 1;
if ((imageWidth > maxWidth) || (imageHeight > maxHeight)) {
scale = Math.min(maxWidth / (double) imageWidth, maxHeight / (double) imageHeight);
}
linkTemplateContext.set("width", (int) (imageWidth * scale + 0.5));
linkTemplateContext.set("height", (int) (imageHeight * scale + 0.5));
}
linkTemplateContext.set("alt", Default.forNull(title, image.getDescription()));
linkTemplateContext.set("title", Default.forNull(title, image.getTitle()));
StringWriter stringWriter = new StringWriter();
linkTemplate.render(linkTemplateContext, stringWriter);
return stringWriter.toString();
}
| public Object format(TemplateContext templateContext, Object data, Map<String, String> parameters) {
Image image = (Image) data;
String imageClass = parameters.get("class");
int maxWidth = Numbers.safeParseInteger(parameters.get("max-width"), Integer.MAX_VALUE);
int maxHeight = Numbers.safeParseInteger(parameters.get("max-height"), Integer.MAX_VALUE);
String mode = String.valueOf(parameters.get("mode"));
String title = parameters.get("title");
if ((title != null) && title.startsWith("=")) {
title = String.valueOf(templateContext.get(title.substring(1)));
}
TemplateContext linkTemplateContext = templateContextFactory.createTemplateContext();
linkTemplateContext.set("class", imageClass);
if (image.isInserted()) {
linkTemplateContext.set("src", "/" + image.getKey());
} else {
linkTemplateContext.set("src", "getImage.html?image=" + image.getId());
}
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
if ("enlarge".equals(mode)) {
double scale = Math.max(maxWidth / (double) imageWidth, maxHeight / (double) imageHeight);
linkTemplateContext.set("width", (int) (imageWidth * scale + 0.5));
linkTemplateContext.set("height", (int) (imageHeight * scale + 0.5));
linkTemplateContext.set("left", String.format("%dpx", (int) (maxWidth - (imageWidth * scale)) / 2));
linkTemplateContext.set("top", String.format("%dpx", (int) (maxHeight - (imageHeight * scale)) / 2));
} else {
double scale = 1;
if ((imageWidth > maxWidth) || (imageHeight > maxHeight)) {
scale = Math.min(maxWidth / (double) imageWidth, maxHeight / (double) imageHeight);
}
linkTemplateContext.set("width", (int) (imageWidth * scale + 0.5));
linkTemplateContext.set("height", (int) (imageHeight * scale + 0.5));
}
linkTemplateContext.set("alt", Default.forNull(title, image.getDescription()));
linkTemplateContext.set("title", Default.forNull(title, image.getTitle()));
StringWriter stringWriter = new StringWriter();
linkTemplate.render(linkTemplateContext, stringWriter);
return stringWriter.toString();
}
|
diff --git a/app/controllers/Contents.java b/app/controllers/Contents.java
index 5ff26c0..30c4d1c 100644
--- a/app/controllers/Contents.java
+++ b/app/controllers/Contents.java
@@ -1,88 +1,88 @@
package controllers;
import external.InstagramParser;
import helpers.TwitterHelper;
import models.Feature;
import play.api.templates.Html;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;
public class Contents extends Controller{
public static Result contentOfFeature(String id)
{
Feature feature = Feature.find().byId(id);
if (feature == null) {
return ok("This POI does not exist anymore.");
}
else {
String decString = feature.properties.get("description").toString();
decString = decString.replaceAll("^\"|\"$", "");
String description = TwitterHelper.parse(decString, "Overlay");
String image = "";
if (feature.properties.get("standard_resolution") != null) {
image = "<div id=\"image-holder\"> " +
- "<img src="+feature.properties.get("standard_resolution").toString()+" alt=\"Smiley face\" width=\"612\" height=\"612\" > " +
+ "<img src="+feature.properties.get("standard_resolution").toString()+" alt=\"Smiley face\" width=\"612\" > " +
"</div> " ;
}
Html content = new Html(image+description);
return ok(index.render(feature,content));
}
}
public static Result contentOfInstaPOI(String id)
{
Feature feature;
try {
feature = InstagramParser.getInstaByMediaId(id);
String decString = feature.properties.get("description").toString();
decString = decString.replaceAll("^\"|\"$", "");
String description = TwitterHelper.parse(decString, "Instagram");
String image = "";
if (feature.properties.get("standard_resolution") != null) {
image = "<div id=\"image-holder\"> " +
"<img src="+feature.properties.get("standard_resolution").toString()+" alt=\"Smiley face\" width=\"612\" height=\"612\" > " +
"</div> " ;
}
Html content = new Html(image+description);
return ok(index.render(feature,content));
} catch (Exception e) {
return ok("This POI does not exist anymore.");
}
}
}
| true | true | public static Result contentOfFeature(String id)
{
Feature feature = Feature.find().byId(id);
if (feature == null) {
return ok("This POI does not exist anymore.");
}
else {
String decString = feature.properties.get("description").toString();
decString = decString.replaceAll("^\"|\"$", "");
String description = TwitterHelper.parse(decString, "Overlay");
String image = "";
if (feature.properties.get("standard_resolution") != null) {
image = "<div id=\"image-holder\"> " +
"<img src="+feature.properties.get("standard_resolution").toString()+" alt=\"Smiley face\" width=\"612\" height=\"612\" > " +
"</div> " ;
}
Html content = new Html(image+description);
return ok(index.render(feature,content));
}
}
| public static Result contentOfFeature(String id)
{
Feature feature = Feature.find().byId(id);
if (feature == null) {
return ok("This POI does not exist anymore.");
}
else {
String decString = feature.properties.get("description").toString();
decString = decString.replaceAll("^\"|\"$", "");
String description = TwitterHelper.parse(decString, "Overlay");
String image = "";
if (feature.properties.get("standard_resolution") != null) {
image = "<div id=\"image-holder\"> " +
"<img src="+feature.properties.get("standard_resolution").toString()+" alt=\"Smiley face\" width=\"612\" > " +
"</div> " ;
}
Html content = new Html(image+description);
return ok(index.render(feature,content));
}
}
|
diff --git a/adapter/stopwatch/src/main/java/org/fiteagle/adapter/stopwatch/StopwatchAdapter.java b/adapter/stopwatch/src/main/java/org/fiteagle/adapter/stopwatch/StopwatchAdapter.java
index 32df360f..02e8cc0e 100644
--- a/adapter/stopwatch/src/main/java/org/fiteagle/adapter/stopwatch/StopwatchAdapter.java
+++ b/adapter/stopwatch/src/main/java/org/fiteagle/adapter/stopwatch/StopwatchAdapter.java
@@ -1,79 +1,79 @@
package org.fiteagle.adapter.stopwatch;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
//import org.fiteagle.adapter.common.InMemoryResourceDatabase;
import org.fiteagle.adapter.common.ResourceAdapter;
public class StopwatchAdapter extends ResourceAdapter {
private static boolean loaded = false;
private transient boolean runningState = false;
public StopwatchAdapter(){
super();
this.setType("org.fiteagle.adapter.stopwatch.StopwatchAdapter");
this.create();
}
public boolean isRunning() {
return runningState;
}
@Override
public void stop() {
this.runningState = false;
}
@Override
public void start() {
this.runningState=true;
}
@Override
public void create() {
//adding some test data to specify stopwatch
HashMap<String, Object> props = this.getProperties();
props.put("format", "SimpleDateFormat");
}
@Override
public void configure() {
// TODO Auto-generated method stub
}
@Override
public void release() {
// TODO Auto-generated method stub
}
@Override
public List<ResourceAdapter> getJavaInstances() {
List<ResourceAdapter> resourceAdapters = new ArrayList<ResourceAdapter>();
-// ResourceAdapter dummyResourceAdapter = new StopwatchAdapter();
-// dummyResourceAdapter.setExclusive(false);
-// dummyResourceAdapter.setAvailable(true);
-// resourceAdapters.add(dummyResourceAdapter);
+ ResourceAdapter dummyResourceAdapter = new StopwatchAdapter();
+ dummyResourceAdapter.setExclusive(false);
+ dummyResourceAdapter.setAvailable(true);
+ resourceAdapters.add(dummyResourceAdapter);
return resourceAdapters;
}
@Override
public boolean isLoaded() {
return loaded;
}
@Override
public void setLoaded(boolean loaded) {
this.loaded=loaded;
}
}
| true | true | public List<ResourceAdapter> getJavaInstances() {
List<ResourceAdapter> resourceAdapters = new ArrayList<ResourceAdapter>();
// ResourceAdapter dummyResourceAdapter = new StopwatchAdapter();
// dummyResourceAdapter.setExclusive(false);
// dummyResourceAdapter.setAvailable(true);
// resourceAdapters.add(dummyResourceAdapter);
return resourceAdapters;
}
| public List<ResourceAdapter> getJavaInstances() {
List<ResourceAdapter> resourceAdapters = new ArrayList<ResourceAdapter>();
ResourceAdapter dummyResourceAdapter = new StopwatchAdapter();
dummyResourceAdapter.setExclusive(false);
dummyResourceAdapter.setAvailable(true);
resourceAdapters.add(dummyResourceAdapter);
return resourceAdapters;
}
|
diff --git a/sk.stuba.fiit.perconik.core.java/src/sk/stuba/fiit/perconik/core/java/dom/NodeCounters.java b/sk.stuba.fiit.perconik.core.java/src/sk/stuba/fiit/perconik/core/java/dom/NodeCounters.java
index 41b43fa0..e0ba461f 100644
--- a/sk.stuba.fiit.perconik.core.java/src/sk/stuba/fiit/perconik/core/java/dom/NodeCounters.java
+++ b/sk.stuba.fiit.perconik.core.java/src/sk/stuba/fiit/perconik/core/java/dom/NodeCounters.java
@@ -1,153 +1,153 @@
package sk.stuba.fiit.perconik.core.java.dom;
import javax.annotation.Nullable;
import org.eclipse.jdt.core.dom.ASTNode;
import sk.stuba.fiit.perconik.utilities.MoreStrings;
import sk.stuba.fiit.perconik.utilities.function.Numerate;
import com.google.common.base.Predicate;
public final class NodeCounters
{
private NodeCounters()
{
throw new AssertionError();
}
private static enum NodeCounter implements Numerate<ASTNode>
{
INSTANCE;
public final int apply(@Nullable final ASTNode node)
{
AbstractCountingVisitor<ASTNode> visitor = new AbstractCountingVisitor<ASTNode>()
{
@Override
public final void preVisit(final ASTNode node)
{
this.count ++;
}
};
return visitor.perform(node);
}
@Override
public final String toString()
{
return "nodes";
}
}
private static enum LineCounter implements Numerate<ASTNode>
{
INSTANCE;
public final int apply(@Nullable final ASTNode node)
{
if (node == null || !Nodes.hasSource(node))
{
return 0;
}
String source = Nodes.source(node, NodeRangeType.STANDARD);
return source != null ? source.split("\r?\n|\r").length : 0;
}
@Override
public final String toString()
{
return "lines(?)";
}
}
private static enum CharacterCounter implements Numerate<ASTNode>
{
INSTANCE;
public final int apply(@Nullable final ASTNode node)
{
return node != null ? node.getLength() : 0;
}
@Override
public final String toString()
{
return "characters";
}
}
private static enum MemoryCounter implements Numerate<ASTNode>
{
INSTANCE;
public final int apply(@Nullable final ASTNode node)
{
return node != null ? node.subtreeBytes() : 0;
}
@Override
public final String toString()
{
return "memory";
}
}
private static final <N extends ASTNode> Numerate<N> cast(final Numerate<?> numerate)
{
// only for stateless internal singletons shared across all types
@SuppressWarnings("unchecked")
Numerate<N> result = (Numerate<N>) numerate;
return result;
}
public static final <N extends ASTNode> Numerate<N> nodes()
{
return cast(NodeCounter.INSTANCE);
}
public static final <N extends ASTNode> Numerate<N> lines()
{
return cast(LineCounter.INSTANCE);
}
public static final <N extends ASTNode> Numerate<N> lines(final String source)
{
return new Numerate<N>()
{
public final int apply(final N node)
{
int index;
if (node == null || (index = node.getStartPosition()) == -1)
{
return 0;
}
- return MoreStrings.lines(source.substring(index, index + node.getLength() - 1)).size();
+ return MoreStrings.lines(source.substring(index, index + node.getLength())).size();
}
@Override
public String toString()
{
return "lines(source)";
}
};
}
public static final <N extends ASTNode> Numerate<N> characters()
{
return cast(CharacterCounter.INSTANCE);
}
public static final <N extends ASTNode> Numerate<N> memory()
{
return cast(MemoryCounter.INSTANCE);
}
public static final <N extends ASTNode> Numerate<N> usingFilter(final Predicate<ASTNode> filter)
{
return NodeFilteringCounter.using(filter);
}
}
| true | true | public static final <N extends ASTNode> Numerate<N> lines(final String source)
{
return new Numerate<N>()
{
public final int apply(final N node)
{
int index;
if (node == null || (index = node.getStartPosition()) == -1)
{
return 0;
}
return MoreStrings.lines(source.substring(index, index + node.getLength() - 1)).size();
}
@Override
public String toString()
{
return "lines(source)";
}
};
}
| public static final <N extends ASTNode> Numerate<N> lines(final String source)
{
return new Numerate<N>()
{
public final int apply(final N node)
{
int index;
if (node == null || (index = node.getStartPosition()) == -1)
{
return 0;
}
return MoreStrings.lines(source.substring(index, index + node.getLength())).size();
}
@Override
public String toString()
{
return "lines(source)";
}
};
}
|
diff --git a/src/main/java/com/theminequest/MineQuest/SQLExecutor.java b/src/main/java/com/theminequest/MineQuest/SQLExecutor.java
index 5083cc7..83d5ca3 100644
--- a/src/main/java/com/theminequest/MineQuest/SQLExecutor.java
+++ b/src/main/java/com/theminequest/MineQuest/SQLExecutor.java
@@ -1,133 +1,134 @@
package com.theminequest.MineQuest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.ResultSet;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.logging.Logger;
import lib.PatPeter.SQLibrary.DatabaseHandler;
import lib.PatPeter.SQLibrary.H2;
import lib.PatPeter.SQLibrary.MySQL;
import lib.PatPeter.SQLibrary.SQLite;
public class SQLExecutor {
private enum Mode{
MySQL, SQlite, H2;
}
private Mode databasetype;
private DatabaseHandler db;
private File datafolder;
public SQLExecutor(){
MineQuest.log("Loading and connecting to SQL...");
PropertiesFile config = MineQuest.configuration.databaseConfig;
String dbtype = config.getString("db_type","h2");
if (dbtype.equalsIgnoreCase("mysql"))
databasetype = Mode.MySQL;
else if (dbtype.equalsIgnoreCase("sqlite"))
databasetype = Mode.SQlite;
else
databasetype = Mode.H2;
MineQuest.log("[SQL] Using "+databasetype.name()+" as database.");
String hostname = config.getString("db_hostname","localhost");
String port = config.getString("db_port","3306");
String databasename = config.getString("db_name","minequest");
String username = config.getString("db_username","root");
String password = config.getString("db_password","toor");
if (databasetype == Mode.MySQL)
db = new MySQL(Logger.getLogger("Minecraft"),"mq_",hostname,port,databasename,username,password);
else if (databasetype == Mode.SQlite)
db = new SQLite(Logger.getLogger("Minecraft"),"mq_","minequest",MineQuest.activePlugin.getDataFolder().getAbsolutePath());
else
db = new H2(Logger.getLogger("Minecraft"),"mq_","minequest",MineQuest.activePlugin.getDataFolder().getAbsolutePath());
datafolder = new File(MineQuest.activePlugin.getDataFolder().getAbsolutePath()+File.separator+"sql");
checkInitialization();
}
private void checkInitialization() {
if (!datafolder.exists()){
datafolder.mkdir();
}
File versionfile = new File(datafolder+File.separator+"version");
Scanner s = null;
String lastv = null;
try {
s = new Scanner(versionfile);
- lastv = s.nextLine();
+ if (s.hasNextLine())
+ lastv = s.nextLine();
} catch (FileNotFoundException e) {
try {
versionfile.createNewFile();
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
if (lastv==null || lastv.compareTo(MineQuest.getVersion())!=0){
if (lastv==null)
lastv = "initial";
querySQL("update/"+lastv,"");
Writer out;
try {
out = new OutputStreamWriter(new FileOutputStream(versionfile));
out.write(MineQuest.getVersion());
out.close();
} catch (FileNotFoundException e) {
// never going to happen
} catch (IOException e) {
// never going to happen either
}
}
}
public DatabaseHandler getDB(){
return db;
}
/**
* Query an SQL and return a {@link java.sql.ResultSet} of the result.
* If the SQL file contains {@code %s} in the query, the parameters
* specified will replace {@code %s} in the query. Remember that if the query
* is not a {@code SELECT} query, this will ALWAYS return null.
* @param queryfilename sql filename to use
* @param params parameters for sql file
* @return ResultSet of SQL query (or null... if there really is nothing good.)
*/
public ResultSet querySQL(String queryfilename, String ...params) {
InputStream i = MineQuest.activePlugin.getResource("sql/"+queryfilename+".sql");
if (i==null)
throw new NoSuchElementException("No such resource: " + queryfilename + ".sql");
String[] filecontents = convertStreamToString(i).split("\n");
for (String line : filecontents){
// ignore comments
if (!line.startsWith("#") || !line.equals("")){
if (params!=null && params.length!=0){
int paramsposition = 0;
while (paramsposition<params.length && line.contains("%s")){
line = line.replaceFirst("%s", params[paramsposition]);
}
}
ResultSet result = db.query(line);
if (result!=null)
return result;
}
}
return null;
}
private String convertStreamToString(InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
}
| true | true | private void checkInitialization() {
if (!datafolder.exists()){
datafolder.mkdir();
}
File versionfile = new File(datafolder+File.separator+"version");
Scanner s = null;
String lastv = null;
try {
s = new Scanner(versionfile);
lastv = s.nextLine();
} catch (FileNotFoundException e) {
try {
versionfile.createNewFile();
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
if (lastv==null || lastv.compareTo(MineQuest.getVersion())!=0){
if (lastv==null)
lastv = "initial";
querySQL("update/"+lastv,"");
Writer out;
try {
out = new OutputStreamWriter(new FileOutputStream(versionfile));
out.write(MineQuest.getVersion());
out.close();
} catch (FileNotFoundException e) {
// never going to happen
} catch (IOException e) {
// never going to happen either
}
}
}
| private void checkInitialization() {
if (!datafolder.exists()){
datafolder.mkdir();
}
File versionfile = new File(datafolder+File.separator+"version");
Scanner s = null;
String lastv = null;
try {
s = new Scanner(versionfile);
if (s.hasNextLine())
lastv = s.nextLine();
} catch (FileNotFoundException e) {
try {
versionfile.createNewFile();
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
if (lastv==null || lastv.compareTo(MineQuest.getVersion())!=0){
if (lastv==null)
lastv = "initial";
querySQL("update/"+lastv,"");
Writer out;
try {
out = new OutputStreamWriter(new FileOutputStream(versionfile));
out.write(MineQuest.getVersion());
out.close();
} catch (FileNotFoundException e) {
// never going to happen
} catch (IOException e) {
// never going to happen either
}
}
}
|
diff --git a/src/org/crossref/pdfmark/Main.java b/src/org/crossref/pdfmark/Main.java
index fa97ffe..3ea8d13 100644
--- a/src/org/crossref/pdfmark/Main.java
+++ b/src/org/crossref/pdfmark/Main.java
@@ -1,211 +1,211 @@
/*
* Copyright 2009 CrossRef.org (email: [email protected])
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.crossref.pdfmark;
import jargs.gnu.CmdLineParser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import static jargs.gnu.CmdLineParser.Option;
public class Main {
private MetadataGrabber grabber = new MetadataGrabber();
public static void printUsage() {
System.err.println("Usage: pdfmark" +
" [{-f, --force}]" +
" [{-p, --xmp-file} xmp_file]" +
" [{-o, --output-dir} output_dir] " +
" [{-d, --doi} doi]" +
" [{-s, --search-for-doi]" +
" [--no-copyright]" +
" [--rights-agent rights_agent_str]" +
" pdf_files");
}
public static void main(String[] args) {
new Main(args);
}
private void shutDown() {
grabber.shutDown();
}
public Main(String[] args) {
if (args.length == 0) {
printUsage();
System.exit(2);
}
CmdLineParser parser = new CmdLineParser();
Option provideXmpOp = parser.addStringOption('p', "xmp-file");
Option overwriteOp = parser.addBooleanOption('f', "force");
Option outputOp = parser.addStringOption('o', "output-dir");
Option doiOp = parser.addStringOption('d', "doi");
Option searchOp = parser.addBooleanOption('s', "search-for-doi");
- Option copyrightOp = parser.addStringOption("copyright");
- Option rightsOp = parser.addStringOption("rights");
+ Option copyrightOp = parser.addStringOption("no-copyright");
+ Option rightsOp = parser.addStringOption("rights-agent");
try {
parser.parse(args);
} catch (CmdLineParser.OptionException e) {
printUsage();
System.exit(2);
}
String optionalXmpPath = (String)
parser.getOptionValue(provideXmpOp, "");
String outputDir = (String)
parser.getOptionValue(outputOp, "");
String explicitDoi = (String)
parser.getOptionValue(doiOp, "");
boolean forceOverwrite = (Boolean)
parser.getOptionValue(overwriteOp, Boolean.FALSE);
boolean searchForDoi = (Boolean)
parser.getOptionValue(searchOp, Boolean.FALSE);
boolean noCopyright = (Boolean)
parser.getOptionValue(copyrightOp, Boolean.FALSE);
String rightsAgent = (String)
parser.getOptionValue(rightsOp, "");
if (!explicitDoi.equals("") && searchForDoi) {
exitWithError(2, "-d and -s are mutually exclusive options.");
}
if (!outputDir.isEmpty() && !new File(outputDir).exists()) {
exitWithError(2, "The output directory, '" + outputDir
+ "' does not exist.");
}
byte[] optionalXmpData = null;
if (!optionalXmpPath.equals("")) {
/* We will take XMP data from a file. */
FileInfo xmpFile = FileInfo.readFileFully(optionalXmpPath);
if (xmpFile.missing) {
exitWithError(2, "Error: File '" + xmpFile.path
+ "' does not exist.");
} else if (xmpFile.error != null) {
exitWithError(2, "Error: Could not read '" + xmpFile.path
+ "' because of:\n" + xmpFile.error);
}
optionalXmpData = xmpFile.data;
}
/* Now we're ready to merge our imported or generated XMP data with what
* is already in each PDF. */
for (String pdfFilePath : parser.getRemainingArgs()) {
String outputPath = pdfFilePath + ".out";
if (!outputDir.isEmpty()) {
outputPath = outputDir + File.separator + outputPath;
}
File pdfFile = new File(pdfFilePath);
File outputFile = new File(pdfFilePath + ".out");
byte[] resolvedXmpData = null;
if (!pdfFile.exists()) {
exitWithError(2, "Error: File '" + pdfFilePath
+ "' does not exist.");
}
if (outputFile.exists() && !forceOverwrite) {
exitWithError(2, "Error: File '" + outputPath
+ "' already exists.\nTry using -f (force).");
}
if (!explicitDoi.equals("")) {
resolvedXmpData = getXmpForDoi(explicitDoi,
!noCopyright,
rightsAgent);
}
try {
FileInputStream fileIn = new FileInputStream(pdfFile);
FileOutputStream fileOut = new FileOutputStream(outputFile);
PdfReader reader = new PdfReader(fileIn);
PdfStamper stamper = new PdfStamper(reader, fileOut);
byte[] merged = reader.getMetadata();
if (optionalXmpData != null) {
merged = XmpUtils.mergeXmp(merged, optionalXmpData);
}
if (resolvedXmpData != null) {
merged = XmpUtils.mergeXmp(merged, resolvedXmpData);
}
stamper.setXmpMetadata(merged);
stamper.close();
reader.close();
} catch (IOException e) {
exitWithError(2, "Error: Couldn't handle '" + pdfFilePath
+ "' because of:\n" + e);
} catch (DocumentException e) {
exitWithError(2, "Error: Couldn't handle '" + pdfFilePath
+ "' because of:\n" + e);
} catch (XmpException e) {
exitWithError(2, "Error: Couldn't handle '" + pdfFilePath
+ "' because of:\n" + e);
}
}
shutDown();
}
private byte[] getXmpForDoi(String doi, boolean genCr, String agent) {
MarkBuilder builder = new MarkBuilder(genCr, agent) {
@Override
public void onFailure(String doi, int code, String msg) {
if (code == MetadataGrabber.CRUMMY_XML_CODE) {
exitWithError(2, "Failed to parse metadata XML because of:\n"
+ code + ": " + msg);
} else {
System.err.println();
exitWithError(2, "Failed to retreive metadata because of:\n"
+ code + ": " + msg);
}
}
};
grabber.grabOne(doi, builder);
System.out.println("Grabbing metadata for '" + doi + "'...");
grabber.waitForEmpty();
return builder.getXmpData();
}
private void exitWithError(int code, String error) {
shutDown();
System.err.println();
System.err.println(error);
System.exit(code);
}
}
| true | true | public Main(String[] args) {
if (args.length == 0) {
printUsage();
System.exit(2);
}
CmdLineParser parser = new CmdLineParser();
Option provideXmpOp = parser.addStringOption('p', "xmp-file");
Option overwriteOp = parser.addBooleanOption('f', "force");
Option outputOp = parser.addStringOption('o', "output-dir");
Option doiOp = parser.addStringOption('d', "doi");
Option searchOp = parser.addBooleanOption('s', "search-for-doi");
Option copyrightOp = parser.addStringOption("copyright");
Option rightsOp = parser.addStringOption("rights");
try {
parser.parse(args);
} catch (CmdLineParser.OptionException e) {
printUsage();
System.exit(2);
}
String optionalXmpPath = (String)
parser.getOptionValue(provideXmpOp, "");
String outputDir = (String)
parser.getOptionValue(outputOp, "");
String explicitDoi = (String)
parser.getOptionValue(doiOp, "");
boolean forceOverwrite = (Boolean)
parser.getOptionValue(overwriteOp, Boolean.FALSE);
boolean searchForDoi = (Boolean)
parser.getOptionValue(searchOp, Boolean.FALSE);
boolean noCopyright = (Boolean)
parser.getOptionValue(copyrightOp, Boolean.FALSE);
String rightsAgent = (String)
parser.getOptionValue(rightsOp, "");
if (!explicitDoi.equals("") && searchForDoi) {
exitWithError(2, "-d and -s are mutually exclusive options.");
}
if (!outputDir.isEmpty() && !new File(outputDir).exists()) {
exitWithError(2, "The output directory, '" + outputDir
+ "' does not exist.");
}
byte[] optionalXmpData = null;
if (!optionalXmpPath.equals("")) {
/* We will take XMP data from a file. */
FileInfo xmpFile = FileInfo.readFileFully(optionalXmpPath);
if (xmpFile.missing) {
exitWithError(2, "Error: File '" + xmpFile.path
+ "' does not exist.");
} else if (xmpFile.error != null) {
exitWithError(2, "Error: Could not read '" + xmpFile.path
+ "' because of:\n" + xmpFile.error);
}
optionalXmpData = xmpFile.data;
}
/* Now we're ready to merge our imported or generated XMP data with what
* is already in each PDF. */
for (String pdfFilePath : parser.getRemainingArgs()) {
String outputPath = pdfFilePath + ".out";
if (!outputDir.isEmpty()) {
outputPath = outputDir + File.separator + outputPath;
}
File pdfFile = new File(pdfFilePath);
File outputFile = new File(pdfFilePath + ".out");
byte[] resolvedXmpData = null;
if (!pdfFile.exists()) {
exitWithError(2, "Error: File '" + pdfFilePath
+ "' does not exist.");
}
if (outputFile.exists() && !forceOverwrite) {
exitWithError(2, "Error: File '" + outputPath
+ "' already exists.\nTry using -f (force).");
}
if (!explicitDoi.equals("")) {
resolvedXmpData = getXmpForDoi(explicitDoi,
!noCopyright,
rightsAgent);
}
try {
FileInputStream fileIn = new FileInputStream(pdfFile);
FileOutputStream fileOut = new FileOutputStream(outputFile);
PdfReader reader = new PdfReader(fileIn);
PdfStamper stamper = new PdfStamper(reader, fileOut);
byte[] merged = reader.getMetadata();
if (optionalXmpData != null) {
merged = XmpUtils.mergeXmp(merged, optionalXmpData);
}
if (resolvedXmpData != null) {
merged = XmpUtils.mergeXmp(merged, resolvedXmpData);
}
stamper.setXmpMetadata(merged);
stamper.close();
reader.close();
} catch (IOException e) {
exitWithError(2, "Error: Couldn't handle '" + pdfFilePath
+ "' because of:\n" + e);
} catch (DocumentException e) {
exitWithError(2, "Error: Couldn't handle '" + pdfFilePath
+ "' because of:\n" + e);
} catch (XmpException e) {
exitWithError(2, "Error: Couldn't handle '" + pdfFilePath
+ "' because of:\n" + e);
}
}
shutDown();
}
| public Main(String[] args) {
if (args.length == 0) {
printUsage();
System.exit(2);
}
CmdLineParser parser = new CmdLineParser();
Option provideXmpOp = parser.addStringOption('p', "xmp-file");
Option overwriteOp = parser.addBooleanOption('f', "force");
Option outputOp = parser.addStringOption('o', "output-dir");
Option doiOp = parser.addStringOption('d', "doi");
Option searchOp = parser.addBooleanOption('s', "search-for-doi");
Option copyrightOp = parser.addStringOption("no-copyright");
Option rightsOp = parser.addStringOption("rights-agent");
try {
parser.parse(args);
} catch (CmdLineParser.OptionException e) {
printUsage();
System.exit(2);
}
String optionalXmpPath = (String)
parser.getOptionValue(provideXmpOp, "");
String outputDir = (String)
parser.getOptionValue(outputOp, "");
String explicitDoi = (String)
parser.getOptionValue(doiOp, "");
boolean forceOverwrite = (Boolean)
parser.getOptionValue(overwriteOp, Boolean.FALSE);
boolean searchForDoi = (Boolean)
parser.getOptionValue(searchOp, Boolean.FALSE);
boolean noCopyright = (Boolean)
parser.getOptionValue(copyrightOp, Boolean.FALSE);
String rightsAgent = (String)
parser.getOptionValue(rightsOp, "");
if (!explicitDoi.equals("") && searchForDoi) {
exitWithError(2, "-d and -s are mutually exclusive options.");
}
if (!outputDir.isEmpty() && !new File(outputDir).exists()) {
exitWithError(2, "The output directory, '" + outputDir
+ "' does not exist.");
}
byte[] optionalXmpData = null;
if (!optionalXmpPath.equals("")) {
/* We will take XMP data from a file. */
FileInfo xmpFile = FileInfo.readFileFully(optionalXmpPath);
if (xmpFile.missing) {
exitWithError(2, "Error: File '" + xmpFile.path
+ "' does not exist.");
} else if (xmpFile.error != null) {
exitWithError(2, "Error: Could not read '" + xmpFile.path
+ "' because of:\n" + xmpFile.error);
}
optionalXmpData = xmpFile.data;
}
/* Now we're ready to merge our imported or generated XMP data with what
* is already in each PDF. */
for (String pdfFilePath : parser.getRemainingArgs()) {
String outputPath = pdfFilePath + ".out";
if (!outputDir.isEmpty()) {
outputPath = outputDir + File.separator + outputPath;
}
File pdfFile = new File(pdfFilePath);
File outputFile = new File(pdfFilePath + ".out");
byte[] resolvedXmpData = null;
if (!pdfFile.exists()) {
exitWithError(2, "Error: File '" + pdfFilePath
+ "' does not exist.");
}
if (outputFile.exists() && !forceOverwrite) {
exitWithError(2, "Error: File '" + outputPath
+ "' already exists.\nTry using -f (force).");
}
if (!explicitDoi.equals("")) {
resolvedXmpData = getXmpForDoi(explicitDoi,
!noCopyright,
rightsAgent);
}
try {
FileInputStream fileIn = new FileInputStream(pdfFile);
FileOutputStream fileOut = new FileOutputStream(outputFile);
PdfReader reader = new PdfReader(fileIn);
PdfStamper stamper = new PdfStamper(reader, fileOut);
byte[] merged = reader.getMetadata();
if (optionalXmpData != null) {
merged = XmpUtils.mergeXmp(merged, optionalXmpData);
}
if (resolvedXmpData != null) {
merged = XmpUtils.mergeXmp(merged, resolvedXmpData);
}
stamper.setXmpMetadata(merged);
stamper.close();
reader.close();
} catch (IOException e) {
exitWithError(2, "Error: Couldn't handle '" + pdfFilePath
+ "' because of:\n" + e);
} catch (DocumentException e) {
exitWithError(2, "Error: Couldn't handle '" + pdfFilePath
+ "' because of:\n" + e);
} catch (XmpException e) {
exitWithError(2, "Error: Couldn't handle '" + pdfFilePath
+ "' because of:\n" + e);
}
}
shutDown();
}
|
diff --git a/tour/product/db/src/main/java/com/tourapp/tour/product/base/db/StatusDescConverter.java b/tour/product/db/src/main/java/com/tourapp/tour/product/base/db/StatusDescConverter.java
index 134dda75..01609e03 100644
--- a/tour/product/db/src/main/java/com/tourapp/tour/product/base/db/StatusDescConverter.java
+++ b/tour/product/db/src/main/java/com/tourapp/tour/product/base/db/StatusDescConverter.java
@@ -1,107 +1,113 @@
/**
* @(#)StatusDescConverter.
* Copyright © 2012 tourapp.com. All rights reserved.
* GPL3 Open Source Software License.
*/
package com.tourapp.tour.product.base.db;
import java.util.*;
import org.jbundle.base.db.*;
import org.jbundle.thin.base.util.*;
import org.jbundle.thin.base.db.*;
import org.jbundle.base.db.event.*;
import org.jbundle.base.db.filter.*;
import org.jbundle.base.field.*;
import org.jbundle.base.field.convert.*;
import org.jbundle.base.field.event.*;
import org.jbundle.base.model.*;
import org.jbundle.base.util.*;
import org.jbundle.model.*;
import org.jbundle.model.db.*;
import org.jbundle.model.screen.*;
import org.jbundle.base.screen.model.util.*;
import com.tourapp.thin.app.booking.entry.*;
import org.jbundle.base.screen.model.*;
import com.tourapp.model.tour.booking.detail.db.*;
/**
* StatusDescConverter - .
*/
public class StatusDescConverter extends DescConverter
{
/**
* Default constructor.
*/
public StatusDescConverter()
{
super();
}
/**
* Constructor.
*/
public StatusDescConverter(Converter converter)
{
this();
this.init(converter);
}
/**
* Initialize class fields.
*/
public void init(BaseField field)
{
super.init(field);
}
/**
* GetMaxLength Method.
*/
public int getMaxLength()
{
return 30;
}
/**
* GetProductType Method.
*/
public String getProductType()
{
BookingDetailModel recCustSaleDetail = (BookingDetailModel)((BaseField)this.getField()).getRecord();
String strProductType = recCustSaleDetail.getField(BookingDetailModel.PRODUCT_TYPE).toString();
if ((strProductType == null) || (strProductType.length() == 0))
strProductType = ProductType.ITEM;
return strProductType;
}
/**
* GetString Method.
*/
public String getString()
{
- ResourceBundle resources = ((BaseApplication)((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()).getResources(ResourceConstants.BOOKING_RESOURCE, true);
- String strProductType = resources.getString(this.getProductType());
+ ResourceBundle resources = null;
+ if ((((BaseField)this.getField()).getRecord().getRecordOwner()) != null)
+ if ((((BaseField)this.getField()).getRecord().getRecordOwner().getTask()) != null)
+ if ((((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()) != null)
+ resources = ((BaseApplication)((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()).getResources(ResourceConstants.BOOKING_RESOURCE, true);
+ String strProductType = this.getProductType();
+ if (resources != null)
+ strProductType = resources.getString(this.getProductType());
int iStatus = (int)this.getValue();
boolean bNormalStatus = true;
if ((iStatus & (1 << BookingConstants.INFO_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.INFO);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.COST_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.COST);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.INVENTORY_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.INVENTORY);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.PRODUCT_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.PRODUCT);
bNormalStatus = false;
}
if (!bNormalStatus)
strProductType += ' ' + resources.getString("Pending");
return strProductType;
}
}
| true | true | public String getString()
{
ResourceBundle resources = ((BaseApplication)((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()).getResources(ResourceConstants.BOOKING_RESOURCE, true);
String strProductType = resources.getString(this.getProductType());
int iStatus = (int)this.getValue();
boolean bNormalStatus = true;
if ((iStatus & (1 << BookingConstants.INFO_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.INFO);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.COST_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.COST);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.INVENTORY_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.INVENTORY);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.PRODUCT_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.PRODUCT);
bNormalStatus = false;
}
if (!bNormalStatus)
strProductType += ' ' + resources.getString("Pending");
return strProductType;
}
| public String getString()
{
ResourceBundle resources = null;
if ((((BaseField)this.getField()).getRecord().getRecordOwner()) != null)
if ((((BaseField)this.getField()).getRecord().getRecordOwner().getTask()) != null)
if ((((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()) != null)
resources = ((BaseApplication)((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()).getResources(ResourceConstants.BOOKING_RESOURCE, true);
String strProductType = this.getProductType();
if (resources != null)
strProductType = resources.getString(this.getProductType());
int iStatus = (int)this.getValue();
boolean bNormalStatus = true;
if ((iStatus & (1 << BookingConstants.INFO_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.INFO);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.COST_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.COST);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.INVENTORY_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.INVENTORY);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.PRODUCT_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.PRODUCT);
bNormalStatus = false;
}
if (!bNormalStatus)
strProductType += ' ' + resources.getString("Pending");
return strProductType;
}
|
diff --git a/src/org/reber/Numbers/ScoreList.java b/src/org/reber/Numbers/ScoreList.java
index 9717ebc..cea278c 100644
--- a/src/org/reber/Numbers/ScoreList.java
+++ b/src/org/reber/Numbers/ScoreList.java
@@ -1,61 +1,61 @@
package org.reber.Numbers;
import java.util.ArrayList;
public class ScoreList extends ArrayList<Score> {
private static final long serialVersionUID = 1L;
private static int MAX_SIZE = 10;
public ScoreList() {
super(MAX_SIZE);
}
@Override
public boolean add(Score object) {
int canAdd = getLocationToAdd(object);
if (canAdd > -1) {
add(canAdd, object);
return true;
} else {
return false;
}
}
public boolean canAdd(Score score) {
return getLocationToAdd(score) > -1;
}
private int getLocationToAdd(Score score) {
// If we are at the max size and the given score is greater than the last score in the
// list, we can't add it
- if (size() == MAX_SIZE && score.compareTo(get(size())) > 0) {
+ if (size() == MAX_SIZE && score.compareTo(get(size() - 1)) > 0) {
return -1;
} else {
if (size() == 0 || score.compareTo(get(0)) < 0) {
return 0;
}
for (int i = 0; i < size(); i++) {
- if (score.compareTo(get(i)) > 0) {
- return i + 1;
+ if (score.compareTo(get(i)) < 0) {
+ return i;
}
}
if (size() != MAX_SIZE) {
return size();
} else {
return -1;
}
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Score s : this) {
sb.append(s);
sb.append(",");
}
return sb.toString();
}
}
| false | true | private int getLocationToAdd(Score score) {
// If we are at the max size and the given score is greater than the last score in the
// list, we can't add it
if (size() == MAX_SIZE && score.compareTo(get(size())) > 0) {
return -1;
} else {
if (size() == 0 || score.compareTo(get(0)) < 0) {
return 0;
}
for (int i = 0; i < size(); i++) {
if (score.compareTo(get(i)) > 0) {
return i + 1;
}
}
if (size() != MAX_SIZE) {
return size();
} else {
return -1;
}
}
}
| private int getLocationToAdd(Score score) {
// If we are at the max size and the given score is greater than the last score in the
// list, we can't add it
if (size() == MAX_SIZE && score.compareTo(get(size() - 1)) > 0) {
return -1;
} else {
if (size() == 0 || score.compareTo(get(0)) < 0) {
return 0;
}
for (int i = 0; i < size(); i++) {
if (score.compareTo(get(i)) < 0) {
return i;
}
}
if (size() != MAX_SIZE) {
return size();
} else {
return -1;
}
}
}
|
diff --git a/AmDroid/src/main/java/com/jaeckel/amenoid/AmenDetailActivity.java b/AmDroid/src/main/java/com/jaeckel/amenoid/AmenDetailActivity.java
index 0ba52e2..abd0441 100644
--- a/AmDroid/src/main/java/com/jaeckel/amenoid/AmenDetailActivity.java
+++ b/AmDroid/src/main/java/com/jaeckel/amenoid/AmenDetailActivity.java
@@ -1,708 +1,708 @@
package com.jaeckel.amenoid;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.jaeckel.amenoid.api.AmenService;
import com.jaeckel.amenoid.api.model.Amen;
import com.jaeckel.amenoid.api.model.Comment;
import com.jaeckel.amenoid.api.model.Statement;
import com.jaeckel.amenoid.api.model.Topic;
import com.jaeckel.amenoid.api.model.User;
import com.jaeckel.amenoid.app.AmenoidApp;
import com.jaeckel.amenoid.cwac.cache.CacheBase;
import com.jaeckel.amenoid.cwac.cache.SimpleWebImageCache;
import com.jaeckel.amenoid.cwac.thumbnail.ThumbnailAdapter;
import com.jaeckel.amenoid.cwac.thumbnail.ThumbnailBus;
import com.jaeckel.amenoid.cwac.thumbnail.ThumbnailMessage;
import com.jaeckel.amenoid.statement.ChooseStatementTypeActivity;
import com.jaeckel.amenoid.util.AmenLibTask;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
* User: biafra
* Date: 9/25/11
* Time: 10:27 AM
*/
public class AmenDetailActivity extends SherlockListActivity {
private static final String TAG = "AmenDetailActivity";
private Amen currentAmen;
private Statement currentStatement;
private Topic topicWithRankedStatements;
private TextView statementView;
private TextView userView;
private TextView amenCount;
private TextView commentsCount;
private Button amenTakeBackButton;
private Button hellNoButton;
private UserListAdapter adapter;
private ThumbnailAdapter thumbs;
private AmenService service;
private static final int[] IMAGE_IDS = {R.id.user_image};
private String lastError = null;
private SimpleWebImageCache<ThumbnailBus, ThumbnailMessage> cache;
private Typeface amenTypeThin;
private Typeface amenTypeBold;
private TextView commentsTextView;
@Override
public boolean onSearchRequested() {
return super.onSearchRequested();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, "onConfigurationChanged(): " + newConfig);
// setContentView(R.layout.myLayout);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
service = AmenoidApp.getInstance().getService();
cache = AmenoidApp.getInstance().getCache();
setContentView(R.layout.details);
setTitle("Amendetails");
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
amenTypeThin = AmenoidApp.getInstance().getAmenTypeThin();
amenTypeBold = AmenoidApp.getInstance().getAmenTypeBold();
ListView list = (ListView) findViewById(android.R.id.list);
View header = getLayoutInflater().inflate(R.layout.details_header, null, false);
list.addHeaderView(header);
commentsTextView = (TextView) findViewById(R.id.comments);
commentsTextView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(AmenDetailActivity.this, CommentsListActivity.class);
intent.putExtra(Constants.EXTRA_AMEN, currentAmen);
startActivity(intent);
}
});
Intent startingIntent = getIntent();
currentAmen = startingIntent.getParcelableExtra(Constants.EXTRA_AMEN);
Log.d(TAG, "Current (OLD!) Amen: " + currentAmen);
if (currentAmen == null) {
// when coming from scorecard or subjectcard. They contain only statements
currentStatement = startingIntent.getParcelableExtra(Constants.EXTRA_STATEMENT);
// start downloading statement again to get the first_amen_id
new GetStatementTask(this).execute(currentStatement.getId());
} else {
currentStatement = currentAmen.getStatement();
new GetAmenTask(this).execute(currentAmen.getId());
}
// header.setOnClickListener(new View.OnClickListener() {
// public void onClick(View view) {
// startScoreBoardActivity();
//
// }
// });
final List<User> users = currentStatement.getAgreeingNetwork();
// adapter = new UserListAdapter(this, android.R.layout.simple_list_item_1, users);
// for (User u : users) {
// Log.d(TAG, "AgreeingNetwork: " + u);
// }
thumbs = new ThumbnailAdapter(this, new UserListAdapter(this, android.R.layout.activity_list_item, users), cache, IMAGE_IDS);
setListAdapter(thumbs);
ImageView mediaPhotoImageView = (ImageView) header.findViewById(R.id.media_photo);
if (currentAmen != null && currentAmen.getMedia() != null && currentAmen.getMedia().size() > 0) {
final String mediaUrl = currentStatement.getObjekt().getMedia().get(0).getContentUrl();
Log.d(TAG, "currentStatement.getMedia().get(0).getContentUrl(): "
+ mediaUrl);
mediaPhotoImageView.setVisibility(View.VISIBLE);
int result = cache.getStatus(mediaUrl);
if (result == CacheBase.CACHE_MEMORY) {
Log.d(TAG, "cache.getStatus(" + mediaUrl + "): CACHE_MEMORY");
mediaPhotoImageView.setImageDrawable(cache.get(mediaUrl));
} else {
mediaPhotoImageView.setImageResource(R.drawable.placeholder);
ThumbnailMessage msg = cache.getBus().createMessage(thumbs.toString());
msg.setImageView(mediaPhotoImageView);
msg.setUrl(mediaUrl);
try {
cache.notify(msg.getUrl(), msg);
} catch (Throwable t) {
Log.e(TAG, "Exception trying to fetch image", t);
throw new RuntimeException(t);
}
}
} else {
Log.d(TAG, " currentAmen: " + currentAmen);
if (currentAmen != null) {
Log.d(TAG, " currentAmen.getMedia(): " + currentAmen.getMedia());
}
- if (currentAmen.getMedia() != null) {
+ if (currentAmen != null && currentAmen.getMedia() != null) {
Log.d(TAG, "currentAmen.getMedia().size(): " + currentAmen.getMedia().size());
}
mediaPhotoImageView.setVisibility(View.INVISIBLE);
}
ImageView objektPhotoImageView = (ImageView) header.findViewById(R.id.objekt_photo);
View objektPhotoImageViewWrapper = (View) header.findViewById(R.id.objekt_photo_wrapper);
if (currentStatement.getObjekt().getMedia() != null && currentStatement.getObjekt().getMedia().size() > 0) {
final String mediaUrl = currentStatement.getObjekt().getMedia().get(0).getContentUrl();
Log.d(TAG, "currentStatement.getMedia().get(0).getContentUrl(): " + mediaUrl);
objektPhotoImageViewWrapper.setVisibility(View.VISIBLE);
int result = cache.getStatus(mediaUrl);
if (result == CacheBase.CACHE_MEMORY) {
Log.d(TAG, "cache.getStatus(" + mediaUrl + "): CACHE_MEMORY");
objektPhotoImageView.setImageDrawable(cache.get(mediaUrl));
} else {
mediaPhotoImageView.setImageResource(R.drawable.placeholder);
ThumbnailMessage msg = cache.getBus().createMessage(thumbs.toString());
msg.setImageView(mediaPhotoImageView);
msg.setUrl(mediaUrl);
try {
cache.notify(msg.getUrl(), msg);
} catch (Throwable t) {
Log.e(TAG, "Exception trying to fetch image", t);
throw new RuntimeException(t);
}
}
} else {
Log.d(TAG, " currentStatement.getObjekt().getMedia(): " + currentStatement.getObjekt().getMedia());
if (currentStatement.getObjekt().getMedia() != null) {
Log.d(TAG, "currentStatement.getObjekt().getMedia().size(): " + currentStatement.getObjekt().getMedia().size());
}
objektPhotoImageViewWrapper.setVisibility(View.INVISIBLE);
}
Intent resultIntent = new Intent();
resultIntent.putExtra(Constants.EXTRA_STATEMENT_ID, currentStatement.getId());
setResult(AmenListActivity.REQUEST_CODE_AMEN_DETAILS, resultIntent);
final View commentLayout = findViewById(R.id.comment_edit_layout);
Button addComment = (Button) findViewById(R.id.add_comment);
addComment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
commentLayout.setVisibility(View.VISIBLE);
}
});
final EditText commentField = (EditText) findViewById(R.id.comment_edit_text);
Button saveComment = (Button) findViewById(R.id.save_comment);
saveComment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
service.createComment(currentAmen.getId(), commentField.getText().toString());
new GetAmenTask(AmenDetailActivity.this).execute(currentAmen.getId());
commentField.setText("");
commentLayout.setVisibility(View.GONE);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
private void startScoreBoardActivity() {
Intent intent = new Intent(this, ScoreBoardActivity.class);
intent.putExtra(Constants.EXTRA_TOPIC, currentStatement.getTopic());
intent.putExtra(Constants.EXTRA_OBJEKT_KIND, currentStatement.getObjekt().getKindId());
startActivity(intent);
}
public void onResume() {
super.onResume();
statementView = (TextView) findViewById(R.id.statement);
statementView.setTypeface(amenTypeBold);
userView = (TextView) findViewById(R.id.user);
userView.setTypeface(amenTypeThin);
amenCount = (TextView) findViewById(R.id.amen_count);
amenCount.setTypeface(amenTypeThin);
commentsCount = (TextView) findViewById(R.id.comments_count);
commentsCount.setTypeface(amenTypeThin);
amenTakeBackButton = (Button) findViewById(R.id.amen_take_back);
amenTakeBackButton.setTypeface(amenTypeBold);
amenTakeBackButton.setEnabled(false);
hellNoButton = (Button) findViewById(R.id.hell_no);
hellNoButton.setTypeface(amenTypeBold);
hellNoButton.setEnabled(false);
populateFormWithAmen(true);
if (!AmenoidApp.getInstance().isSignedIn()) {
amenTakeBackButton.setEnabled(false);
hellNoButton.setEnabled(false);
}
}
private void populateFormWithAmen(boolean updateName) {
if (currentAmen == null) {
Log.d(TAG, "currentAmen: " + currentAmen);
Log.d(TAG, "currentStatement: " + currentStatement);
statementView.setText(AmenListAdapter.styleAmenWithColor(currentStatement, false, null, this));
} else {
statementView.setText(AmenListAdapter.styleAmenWithColor(currentAmen, this));
}
// statementView.setText(currentAmen.getStatement().toDisplayString());
//TODO: find a better way to have the original? name here
if (updateName) {
if (currentAmen != null && currentAmen.getUser() != null) {
userView.setText(currentAmen.getUser().getName() + ", " + format(currentAmen.getCreatedAt()));
} else if (currentStatement.getFirstPoster() != null) {
userView.setText(currentStatement.getFirstPoster().getName() + ", " + format(currentStatement.getFirstPostedAt()));
}
}
amenCount.setText(currentStatement.getTotalAmenCount() + " Amen");
StringBuilder agreeing = new StringBuilder();
for (User user : currentStatement.getAgreeingNetwork()) {
agreeing.append(user.getName() + ", ");
}
if (amened(currentStatement)) {
amenTakeBackButton.setText("Take Back");
} else {
amenTakeBackButton.setText("Amen!");
}
if (currentAmen != null && currentAmen.getId() != null) {
setAmenButtonListener();
String commentsCountText = "";
if (currentAmen.getCommentsCount() != null && currentAmen.getCommentsCount() == 1) {
commentsCountText = " / " + currentAmen.getCommentsCount() + " comment";
}
if (currentAmen.getCommentsCount() != null && currentAmen.getCommentsCount() > 1) {
commentsCountText = " / " + currentAmen.getCommentsCount() + " comments";
}
commentsCount.setText(commentsCountText);
}
}
private void setAmenButtonListener() {
if (service.getMe() != null) {
amenTakeBackButton.setEnabled(true);
amenTakeBackButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
amenTakeBackButton.setEnabled(false);
if (amened(currentStatement)) {
Log.d(TAG, "Back taking: " + currentAmen);
new AmenDetailActivity.TakeBackTask(AmenDetailActivity.this).execute(currentStatement.getId());
} else {
Log.d(TAG, "amening: " + currentAmen);
new AmenDetailActivity.AmenTask(AmenDetailActivity.this).execute(currentAmen.getId());
}
populateFormWithAmen(false);
}
});
hellNoButton.setEnabled(true);
hellNoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//TODO: show hellno form here to let user select different objekt
populateFormWithAmen(false);
Intent intent = new Intent(AmenDetailActivity.this, DisputeActivity.class);
intent.putExtra(Constants.EXTRA_AMEN, currentAmen);
startActivity(intent);
}
});
}
}
private boolean amened(Statement currentStatement) {
for (User u : currentStatement.getAgreeingNetwork()) {
if (AmenoidApp.getInstance().isSignedIn() && service.getMe() != null && u.getId() == service.getMe().getId()) {
return true;
}
}
return false;
}
public static String format(Date firstPostedAt) {
SimpleDateFormat fmt = new SimpleDateFormat("dd. MMMMM yyyy - HH:mm");
if (firstPostedAt != null) {
return fmt.format(firstPostedAt);
}
return "<date unknown>";
}
public void onPause() {
super.onPause();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
User user = (User) getListAdapter().getItem(position - 1);
Log.d(TAG, "======> Selected User: " + user);
Intent intent = new Intent(this, UserDetailActivity.class);
intent.putExtra(Constants.EXTRA_USER, user);
startActivity(intent);
}
//
// TakeBackTask
//
private class TakeBackTask extends AmenLibTask<Long, Integer, Amen> {
public TakeBackTask(Activity context) {
super(context);
}
protected Amen wrappedDoInBackground(Long... statementId) throws IOException {
try {
service.takeBack(statementId[0]);
Amen amen = new Amen(service.getStatementForId(statementId[0]));
amen.setId(currentAmen.getId());
Log.d(TAG, "Amen returned from amen(): " + amen);
return amen;
} catch (RuntimeException e) {
lastError = e.getMessage();
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
amenTakeBackButton.setEnabled(false);
}
protected void wrappedOnPostExecute(Amen result) {
if (result != null) {
currentAmen = result;
currentStatement = currentAmen.getStatement();
populateFormWithAmen(false);
Toast.makeText(AmenDetailActivity.this, "Taken Back.", Toast.LENGTH_SHORT).show();
final List<User> users = currentStatement.getAgreeingNetwork();
// adapter = new UserListAdapter(this, android.R.layout.simple_list_item_1, users);
thumbs = new ThumbnailAdapter(AmenDetailActivity.this, new UserListAdapter(AmenDetailActivity.this, android.R.layout.activity_list_item, users), cache, IMAGE_IDS);
setListAdapter(thumbs);
}
if (service.getMe() != null) {
amenTakeBackButton.setEnabled(true);
}
}
}
//
// AmenTask
//
private class AmenTask extends AmenLibTask<Long, Integer, Amen> {
public AmenTask(Activity context) {
super(context);
}
protected Amen wrappedDoInBackground(Long... amenId) throws IOException {
Amen amen = service.amen(amenId[0]);
Log.d(TAG, "Amen returned from amen(): " + amen);
return amen;
}
@Override
protected void onPreExecute() {
amenTakeBackButton.setEnabled(false);
}
protected void wrappedOnPostExecute(Amen result) {
if (result != null) {
currentAmen = result;
currentStatement = currentAmen.getStatement();
populateFormWithAmen(false);
Toast.makeText(AmenDetailActivity.this, "Amen'd.", Toast.LENGTH_SHORT).show();
final List<User> users = currentStatement.getAgreeingNetwork();
// adapter = new UserListAdapter(this, android.R.layout.simple_list_item_1, users);
thumbs = new ThumbnailAdapter(AmenDetailActivity.this, new UserListAdapter(AmenDetailActivity.this, android.R.layout.activity_list_item, users), cache, IMAGE_IDS);
setListAdapter(thumbs);
}
if (service.getMe() != null) {
amenTakeBackButton.setEnabled(true);
}
}
}
//
// StatementTask
//
private class GetStatementTask extends AmenLibTask<Long, Integer, Statement> {
public GetStatementTask(Activity context) {
super(context);
}
protected Statement wrappedDoInBackground(Long... statementIds) throws IOException {
Statement statement = service.getStatementForId(statementIds[0]);
Log.d(TAG, "Statement returned from statement(): " + statement);
return statement;
}
@Override
protected void onPreExecute() {
}
protected void wrappedOnPostExecute(Statement result) {
if (result != null) {
currentAmen = new Amen(result);
currentAmen.setId(result.getFirstAmenId());
setAmenButtonListener();
// Toast.makeText(AmenDetailActivity.this, "setId on currentAmen", Toast.LENGTH_SHORT).show();
currentStatement = result;
populateFormWithAmen(false);
// amen button freischalten
final List<User> users = currentStatement.getAgreeingNetwork();
// adapter = new UserListAdapter(this, android.R.layout.simple_list_item_1, users);
thumbs = new ThumbnailAdapter(AmenDetailActivity.this, new UserListAdapter(AmenDetailActivity.this, android.R.layout.activity_list_item, users), cache, IMAGE_IDS);
setListAdapter(thumbs);
new GetAmenTask(AmenDetailActivity.this).execute(result.getFirstAmenId());
}
}
}
//
// GetAmenTask
//
private class GetAmenTask extends AmenLibTask<Long, Integer, Amen> {
public GetAmenTask(Activity context) {
super(context);
}
protected Amen wrappedDoInBackground(Long... amenIds) throws IOException {
Amen amen = service.getAmenForId(amenIds[0]);
Log.d(TAG, "Amen returned from getAmenForId(): " + amen);
return amen;
}
@Override
protected void onPreExecute() {
}
protected void wrappedOnPostExecute(Amen result) {
if (result != null) {
currentAmen = result;
Log.d(TAG, "Current (NEW!) Amen: " + currentAmen);
StringBuilder commentsText = new StringBuilder();
//commentsText.append("Comment(s):\n");
for (Comment comment : currentAmen.getComments()) {
Log.d(TAG, "comment: " + comment);
commentsText.append(formatCommentDate(comment.getCreatedAt()));
commentsText.append(": ");
commentsText.append(comment.getUser().getName());
commentsText.append(": ");
commentsText.append(comment.getBody());
commentsText.append("\n");
}
commentsTextView.setText(commentsText.toString());
setAmenButtonListener();
currentStatement = result.getStatement();
populateFormWithAmen(true);
final List<User> users = currentStatement.getAgreeingNetwork();
thumbs = new ThumbnailAdapter(AmenDetailActivity.this, new UserListAdapter(AmenDetailActivity.this, android.R.layout.activity_list_item, users), cache, IMAGE_IDS);
setListAdapter(thumbs);
}
}
}
public static String formatCommentDate(Date firstPostedAt) {
SimpleDateFormat fmt = new SimpleDateFormat("yy-MM-dd HH:mm");
if (firstPostedAt != null) {
return fmt.format(firstPostedAt);
}
return "<unknown>";
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.menu_detail, menu);
if (!AmenoidApp.getInstance().isSignedIn()) {
MenuItem amenSth = menu.findItem(R.id.amen);
amenSth.setEnabled(false);
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
Log.d(TAG, "onOptionsItemSelected -> item.getItemId(): " + item.getItemId());
final Intent amenListIntent = new Intent(this, AmenListActivity.class);
amenListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
switch (item.getItemId()) {
case android.R.id.home: {
startActivity(amenListIntent);
return true;
}
case R.id.timeline: {
startActivity(amenListIntent);
return true;
}
case R.id.scoreboard: {
startScoreBoardActivity();
return true;
}
case R.id.share: {
String amenText = currentAmen.getStatement().toDisplayString();
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, amenText + " #getamen https://getamen.com/statements/" + currentAmen.getStatement().getId());
startActivity(Intent.createChooser(sharingIntent, "Share using"));
return true;
}
case R.id.amen:
startActivity(new Intent(this, ChooseStatementTypeActivity.class));
return true;
case R.id.subject_page: {
Intent intent = new Intent(this, SubjectPageActivity.class);
// Toast.makeText(this, "id: " + currentAmen.getStatement().getObjekt().getId(), Toast.LENGTH_SHORT).show();
intent.putExtra(Constants.EXTRA_OBJEKT_ID, currentAmen.getStatement().getObjekt().getId());
startActivity(intent);
return true;
}
// default: {
// Log.d(TAG, "Unexpected item.getItemId(): " + item.getItemId());
// startActivity(amenListIntent);
// return true;
// }
}
return false;
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
service = AmenoidApp.getInstance().getService();
cache = AmenoidApp.getInstance().getCache();
setContentView(R.layout.details);
setTitle("Amendetails");
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
amenTypeThin = AmenoidApp.getInstance().getAmenTypeThin();
amenTypeBold = AmenoidApp.getInstance().getAmenTypeBold();
ListView list = (ListView) findViewById(android.R.id.list);
View header = getLayoutInflater().inflate(R.layout.details_header, null, false);
list.addHeaderView(header);
commentsTextView = (TextView) findViewById(R.id.comments);
commentsTextView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(AmenDetailActivity.this, CommentsListActivity.class);
intent.putExtra(Constants.EXTRA_AMEN, currentAmen);
startActivity(intent);
}
});
Intent startingIntent = getIntent();
currentAmen = startingIntent.getParcelableExtra(Constants.EXTRA_AMEN);
Log.d(TAG, "Current (OLD!) Amen: " + currentAmen);
if (currentAmen == null) {
// when coming from scorecard or subjectcard. They contain only statements
currentStatement = startingIntent.getParcelableExtra(Constants.EXTRA_STATEMENT);
// start downloading statement again to get the first_amen_id
new GetStatementTask(this).execute(currentStatement.getId());
} else {
currentStatement = currentAmen.getStatement();
new GetAmenTask(this).execute(currentAmen.getId());
}
// header.setOnClickListener(new View.OnClickListener() {
// public void onClick(View view) {
// startScoreBoardActivity();
//
// }
// });
final List<User> users = currentStatement.getAgreeingNetwork();
// adapter = new UserListAdapter(this, android.R.layout.simple_list_item_1, users);
// for (User u : users) {
// Log.d(TAG, "AgreeingNetwork: " + u);
// }
thumbs = new ThumbnailAdapter(this, new UserListAdapter(this, android.R.layout.activity_list_item, users), cache, IMAGE_IDS);
setListAdapter(thumbs);
ImageView mediaPhotoImageView = (ImageView) header.findViewById(R.id.media_photo);
if (currentAmen != null && currentAmen.getMedia() != null && currentAmen.getMedia().size() > 0) {
final String mediaUrl = currentStatement.getObjekt().getMedia().get(0).getContentUrl();
Log.d(TAG, "currentStatement.getMedia().get(0).getContentUrl(): "
+ mediaUrl);
mediaPhotoImageView.setVisibility(View.VISIBLE);
int result = cache.getStatus(mediaUrl);
if (result == CacheBase.CACHE_MEMORY) {
Log.d(TAG, "cache.getStatus(" + mediaUrl + "): CACHE_MEMORY");
mediaPhotoImageView.setImageDrawable(cache.get(mediaUrl));
} else {
mediaPhotoImageView.setImageResource(R.drawable.placeholder);
ThumbnailMessage msg = cache.getBus().createMessage(thumbs.toString());
msg.setImageView(mediaPhotoImageView);
msg.setUrl(mediaUrl);
try {
cache.notify(msg.getUrl(), msg);
} catch (Throwable t) {
Log.e(TAG, "Exception trying to fetch image", t);
throw new RuntimeException(t);
}
}
} else {
Log.d(TAG, " currentAmen: " + currentAmen);
if (currentAmen != null) {
Log.d(TAG, " currentAmen.getMedia(): " + currentAmen.getMedia());
}
if (currentAmen.getMedia() != null) {
Log.d(TAG, "currentAmen.getMedia().size(): " + currentAmen.getMedia().size());
}
mediaPhotoImageView.setVisibility(View.INVISIBLE);
}
ImageView objektPhotoImageView = (ImageView) header.findViewById(R.id.objekt_photo);
View objektPhotoImageViewWrapper = (View) header.findViewById(R.id.objekt_photo_wrapper);
if (currentStatement.getObjekt().getMedia() != null && currentStatement.getObjekt().getMedia().size() > 0) {
final String mediaUrl = currentStatement.getObjekt().getMedia().get(0).getContentUrl();
Log.d(TAG, "currentStatement.getMedia().get(0).getContentUrl(): " + mediaUrl);
objektPhotoImageViewWrapper.setVisibility(View.VISIBLE);
int result = cache.getStatus(mediaUrl);
if (result == CacheBase.CACHE_MEMORY) {
Log.d(TAG, "cache.getStatus(" + mediaUrl + "): CACHE_MEMORY");
objektPhotoImageView.setImageDrawable(cache.get(mediaUrl));
} else {
mediaPhotoImageView.setImageResource(R.drawable.placeholder);
ThumbnailMessage msg = cache.getBus().createMessage(thumbs.toString());
msg.setImageView(mediaPhotoImageView);
msg.setUrl(mediaUrl);
try {
cache.notify(msg.getUrl(), msg);
} catch (Throwable t) {
Log.e(TAG, "Exception trying to fetch image", t);
throw new RuntimeException(t);
}
}
} else {
Log.d(TAG, " currentStatement.getObjekt().getMedia(): " + currentStatement.getObjekt().getMedia());
if (currentStatement.getObjekt().getMedia() != null) {
Log.d(TAG, "currentStatement.getObjekt().getMedia().size(): " + currentStatement.getObjekt().getMedia().size());
}
objektPhotoImageViewWrapper.setVisibility(View.INVISIBLE);
}
Intent resultIntent = new Intent();
resultIntent.putExtra(Constants.EXTRA_STATEMENT_ID, currentStatement.getId());
setResult(AmenListActivity.REQUEST_CODE_AMEN_DETAILS, resultIntent);
final View commentLayout = findViewById(R.id.comment_edit_layout);
Button addComment = (Button) findViewById(R.id.add_comment);
addComment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
commentLayout.setVisibility(View.VISIBLE);
}
});
final EditText commentField = (EditText) findViewById(R.id.comment_edit_text);
Button saveComment = (Button) findViewById(R.id.save_comment);
saveComment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
service.createComment(currentAmen.getId(), commentField.getText().toString());
new GetAmenTask(AmenDetailActivity.this).execute(currentAmen.getId());
commentField.setText("");
commentLayout.setVisibility(View.GONE);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
service = AmenoidApp.getInstance().getService();
cache = AmenoidApp.getInstance().getCache();
setContentView(R.layout.details);
setTitle("Amendetails");
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
amenTypeThin = AmenoidApp.getInstance().getAmenTypeThin();
amenTypeBold = AmenoidApp.getInstance().getAmenTypeBold();
ListView list = (ListView) findViewById(android.R.id.list);
View header = getLayoutInflater().inflate(R.layout.details_header, null, false);
list.addHeaderView(header);
commentsTextView = (TextView) findViewById(R.id.comments);
commentsTextView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(AmenDetailActivity.this, CommentsListActivity.class);
intent.putExtra(Constants.EXTRA_AMEN, currentAmen);
startActivity(intent);
}
});
Intent startingIntent = getIntent();
currentAmen = startingIntent.getParcelableExtra(Constants.EXTRA_AMEN);
Log.d(TAG, "Current (OLD!) Amen: " + currentAmen);
if (currentAmen == null) {
// when coming from scorecard or subjectcard. They contain only statements
currentStatement = startingIntent.getParcelableExtra(Constants.EXTRA_STATEMENT);
// start downloading statement again to get the first_amen_id
new GetStatementTask(this).execute(currentStatement.getId());
} else {
currentStatement = currentAmen.getStatement();
new GetAmenTask(this).execute(currentAmen.getId());
}
// header.setOnClickListener(new View.OnClickListener() {
// public void onClick(View view) {
// startScoreBoardActivity();
//
// }
// });
final List<User> users = currentStatement.getAgreeingNetwork();
// adapter = new UserListAdapter(this, android.R.layout.simple_list_item_1, users);
// for (User u : users) {
// Log.d(TAG, "AgreeingNetwork: " + u);
// }
thumbs = new ThumbnailAdapter(this, new UserListAdapter(this, android.R.layout.activity_list_item, users), cache, IMAGE_IDS);
setListAdapter(thumbs);
ImageView mediaPhotoImageView = (ImageView) header.findViewById(R.id.media_photo);
if (currentAmen != null && currentAmen.getMedia() != null && currentAmen.getMedia().size() > 0) {
final String mediaUrl = currentStatement.getObjekt().getMedia().get(0).getContentUrl();
Log.d(TAG, "currentStatement.getMedia().get(0).getContentUrl(): "
+ mediaUrl);
mediaPhotoImageView.setVisibility(View.VISIBLE);
int result = cache.getStatus(mediaUrl);
if (result == CacheBase.CACHE_MEMORY) {
Log.d(TAG, "cache.getStatus(" + mediaUrl + "): CACHE_MEMORY");
mediaPhotoImageView.setImageDrawable(cache.get(mediaUrl));
} else {
mediaPhotoImageView.setImageResource(R.drawable.placeholder);
ThumbnailMessage msg = cache.getBus().createMessage(thumbs.toString());
msg.setImageView(mediaPhotoImageView);
msg.setUrl(mediaUrl);
try {
cache.notify(msg.getUrl(), msg);
} catch (Throwable t) {
Log.e(TAG, "Exception trying to fetch image", t);
throw new RuntimeException(t);
}
}
} else {
Log.d(TAG, " currentAmen: " + currentAmen);
if (currentAmen != null) {
Log.d(TAG, " currentAmen.getMedia(): " + currentAmen.getMedia());
}
if (currentAmen != null && currentAmen.getMedia() != null) {
Log.d(TAG, "currentAmen.getMedia().size(): " + currentAmen.getMedia().size());
}
mediaPhotoImageView.setVisibility(View.INVISIBLE);
}
ImageView objektPhotoImageView = (ImageView) header.findViewById(R.id.objekt_photo);
View objektPhotoImageViewWrapper = (View) header.findViewById(R.id.objekt_photo_wrapper);
if (currentStatement.getObjekt().getMedia() != null && currentStatement.getObjekt().getMedia().size() > 0) {
final String mediaUrl = currentStatement.getObjekt().getMedia().get(0).getContentUrl();
Log.d(TAG, "currentStatement.getMedia().get(0).getContentUrl(): " + mediaUrl);
objektPhotoImageViewWrapper.setVisibility(View.VISIBLE);
int result = cache.getStatus(mediaUrl);
if (result == CacheBase.CACHE_MEMORY) {
Log.d(TAG, "cache.getStatus(" + mediaUrl + "): CACHE_MEMORY");
objektPhotoImageView.setImageDrawable(cache.get(mediaUrl));
} else {
mediaPhotoImageView.setImageResource(R.drawable.placeholder);
ThumbnailMessage msg = cache.getBus().createMessage(thumbs.toString());
msg.setImageView(mediaPhotoImageView);
msg.setUrl(mediaUrl);
try {
cache.notify(msg.getUrl(), msg);
} catch (Throwable t) {
Log.e(TAG, "Exception trying to fetch image", t);
throw new RuntimeException(t);
}
}
} else {
Log.d(TAG, " currentStatement.getObjekt().getMedia(): " + currentStatement.getObjekt().getMedia());
if (currentStatement.getObjekt().getMedia() != null) {
Log.d(TAG, "currentStatement.getObjekt().getMedia().size(): " + currentStatement.getObjekt().getMedia().size());
}
objektPhotoImageViewWrapper.setVisibility(View.INVISIBLE);
}
Intent resultIntent = new Intent();
resultIntent.putExtra(Constants.EXTRA_STATEMENT_ID, currentStatement.getId());
setResult(AmenListActivity.REQUEST_CODE_AMEN_DETAILS, resultIntent);
final View commentLayout = findViewById(R.id.comment_edit_layout);
Button addComment = (Button) findViewById(R.id.add_comment);
addComment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
commentLayout.setVisibility(View.VISIBLE);
}
});
final EditText commentField = (EditText) findViewById(R.id.comment_edit_text);
Button saveComment = (Button) findViewById(R.id.save_comment);
saveComment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
service.createComment(currentAmen.getId(), commentField.getText().toString());
new GetAmenTask(AmenDetailActivity.this).execute(currentAmen.getId());
commentField.setText("");
commentLayout.setVisibility(View.GONE);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
|
diff --git a/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/DocumentationAssociator.java b/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/DocumentationAssociator.java
index 6ce292ad..d274ba00 100644
--- a/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/DocumentationAssociator.java
+++ b/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/DocumentationAssociator.java
@@ -1,111 +1,114 @@
/**
* Copyright (c) 2011 Cloudsmith Inc. and other contributors, as listed below.
* 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:
* Cloudsmith
*
*/
package org.cloudsmith.geppetto.pp.dsl.linking;
import java.util.List;
import org.cloudsmith.geppetto.pp.Definition;
import org.cloudsmith.geppetto.pp.HostClassDefinition;
import org.cloudsmith.geppetto.pp.NodeDefinition;
import org.cloudsmith.geppetto.pp.dsl.adapters.DocumentationAdapter;
import org.cloudsmith.geppetto.pp.dsl.adapters.DocumentationAdapterFactory;
import org.cloudsmith.geppetto.pp.dsl.services.PPGrammarAccess;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.IGrammarAccess;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
/**
* Provides handling of documentation comments.
*
*/
public class DocumentationAssociator {
private final PPGrammarAccess ga;
/**
* Expression that may have associated documentation. (TODO: Puppetdoc also lists Nodes global variables, custom facts, and
* Puppet plugins located in modules - but don't know which of those are applicable).
*/
private static final Class<?>[] documentable = { HostClassDefinition.class, Definition.class, NodeDefinition.class, };
@Inject
public DocumentationAssociator(IGrammarAccess ga) {
this.ga = (PPGrammarAccess) ga;
}
private void associateDocumentation(EObject semantic, List<INode> commentSequence) {
StringBuffer buf = new StringBuffer();
for(INode n : commentSequence)
buf.append(n.getText());
DocumentationAdapter adapter = DocumentationAdapterFactory.eINSTANCE.adapt(semantic);
adapter.setNodes(commentSequence);
}
/**
* Links comment nodes to classes listed in {@link #documentable} by collecting them in an
* adapter (for later processing by formatter/styler).
*
* TODO: provide checks that documentation is consistent with the model
*/
protected void linkDocumentation(EObject model, IMessageAcceptor acceptor) {
// a sequence of SL comment or a single ML comment that is immediately (no NL) before
// a definition, class, or node is taken to be a documentation comment, as is associated with
// the following semantic object using an adapter.
//
ICompositeNode node = NodeModelUtils.getNode(model);
ICompositeNode root = node.getRootNode();
List<INode> commentSequence = Lists.newArrayList();
for(INode x : root.getAsTreeIterable()) {
EObject grammarElement = x.getGrammarElement();
// process comments
if(grammarElement == ga.getSL_COMMENTRule() || grammarElement == ga.getML_COMMENTRule()) {
// if nothing follows the comment (we are probably at the end)
if(!x.hasNextSibling()) {
commentSequence.clear();
continue;
}
// if next is a blank line, throw away any collected comments.
INode sibling = x.getNextSibling();
if(sibling.getGrammarElement() == ga.getWSRule() && sibling.getText().contains("\n")) {
commentSequence.clear();
continue;
}
// if adding a ML comment, use only the last
if(grammarElement == ga.getML_COMMENTRule())
commentSequence.clear();
commentSequence.add(x);
// if next is not a comment, it may be an element that the documentation should be associated with
EObject siblingElement = sibling.getGrammarElement();
if(siblingElement == ga.getSL_COMMENTRule() || siblingElement == ga.getML_COMMENTRule())
continue; // keep on collecting
EObject semantic = NodeModelUtils.findActualSemanticObjectFor(sibling);
- for(Class<?> clazz : documentable) {
- if(clazz.isAssignableFrom(semantic.getClass())) {
- // found sequence is documentation for semantic
- associateDocumentation(semantic, commentSequence);
- break;
+ found: {
+ for(Class<?> clazz : documentable) {
+ if(clazz.isAssignableFrom(semantic.getClass())) {
+ // found sequence is documentation for semantic
+ associateDocumentation(semantic, commentSequence);
+ break found;
+ }
}
+ commentSequence.clear();
}
}
}
}
}
| false | true | protected void linkDocumentation(EObject model, IMessageAcceptor acceptor) {
// a sequence of SL comment or a single ML comment that is immediately (no NL) before
// a definition, class, or node is taken to be a documentation comment, as is associated with
// the following semantic object using an adapter.
//
ICompositeNode node = NodeModelUtils.getNode(model);
ICompositeNode root = node.getRootNode();
List<INode> commentSequence = Lists.newArrayList();
for(INode x : root.getAsTreeIterable()) {
EObject grammarElement = x.getGrammarElement();
// process comments
if(grammarElement == ga.getSL_COMMENTRule() || grammarElement == ga.getML_COMMENTRule()) {
// if nothing follows the comment (we are probably at the end)
if(!x.hasNextSibling()) {
commentSequence.clear();
continue;
}
// if next is a blank line, throw away any collected comments.
INode sibling = x.getNextSibling();
if(sibling.getGrammarElement() == ga.getWSRule() && sibling.getText().contains("\n")) {
commentSequence.clear();
continue;
}
// if adding a ML comment, use only the last
if(grammarElement == ga.getML_COMMENTRule())
commentSequence.clear();
commentSequence.add(x);
// if next is not a comment, it may be an element that the documentation should be associated with
EObject siblingElement = sibling.getGrammarElement();
if(siblingElement == ga.getSL_COMMENTRule() || siblingElement == ga.getML_COMMENTRule())
continue; // keep on collecting
EObject semantic = NodeModelUtils.findActualSemanticObjectFor(sibling);
for(Class<?> clazz : documentable) {
if(clazz.isAssignableFrom(semantic.getClass())) {
// found sequence is documentation for semantic
associateDocumentation(semantic, commentSequence);
break;
}
}
}
}
}
| protected void linkDocumentation(EObject model, IMessageAcceptor acceptor) {
// a sequence of SL comment or a single ML comment that is immediately (no NL) before
// a definition, class, or node is taken to be a documentation comment, as is associated with
// the following semantic object using an adapter.
//
ICompositeNode node = NodeModelUtils.getNode(model);
ICompositeNode root = node.getRootNode();
List<INode> commentSequence = Lists.newArrayList();
for(INode x : root.getAsTreeIterable()) {
EObject grammarElement = x.getGrammarElement();
// process comments
if(grammarElement == ga.getSL_COMMENTRule() || grammarElement == ga.getML_COMMENTRule()) {
// if nothing follows the comment (we are probably at the end)
if(!x.hasNextSibling()) {
commentSequence.clear();
continue;
}
// if next is a blank line, throw away any collected comments.
INode sibling = x.getNextSibling();
if(sibling.getGrammarElement() == ga.getWSRule() && sibling.getText().contains("\n")) {
commentSequence.clear();
continue;
}
// if adding a ML comment, use only the last
if(grammarElement == ga.getML_COMMENTRule())
commentSequence.clear();
commentSequence.add(x);
// if next is not a comment, it may be an element that the documentation should be associated with
EObject siblingElement = sibling.getGrammarElement();
if(siblingElement == ga.getSL_COMMENTRule() || siblingElement == ga.getML_COMMENTRule())
continue; // keep on collecting
EObject semantic = NodeModelUtils.findActualSemanticObjectFor(sibling);
found: {
for(Class<?> clazz : documentable) {
if(clazz.isAssignableFrom(semantic.getClass())) {
// found sequence is documentation for semantic
associateDocumentation(semantic, commentSequence);
break found;
}
}
commentSequence.clear();
}
}
}
}
|
diff --git a/eXoApplication/faq/webapp/src/main/java/org/exoplatform/faq/webui/popup/UISelectForumForm.java b/eXoApplication/faq/webapp/src/main/java/org/exoplatform/faq/webui/popup/UISelectForumForm.java
index be49d5175..86192f6e7 100644
--- a/eXoApplication/faq/webapp/src/main/java/org/exoplatform/faq/webui/popup/UISelectForumForm.java
+++ b/eXoApplication/faq/webapp/src/main/java/org/exoplatform/faq/webui/popup/UISelectForumForm.java
@@ -1,187 +1,189 @@
/***************************************************************************
* Copyright (C) 2003-2009 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see<http://www.gnu.org/licenses/>.
***************************************************************************/
package org.exoplatform.faq.webui.popup;
import java.util.ArrayList;
import java.util.List;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.faq.service.Answer;
import org.exoplatform.faq.service.Comment;
import org.exoplatform.faq.service.FAQService;
import org.exoplatform.faq.service.FAQSetting;
import org.exoplatform.faq.service.Question;
import org.exoplatform.faq.webui.FAQUtils;
import org.exoplatform.faq.webui.UIFAQPortlet;
import org.exoplatform.forum.service.Forum;
import org.exoplatform.forum.service.ForumService;
import org.exoplatform.forum.service.Post;
import org.exoplatform.forum.service.Topic;
import org.exoplatform.portal.application.PortalRequestContext;
import org.exoplatform.portal.webui.util.SessionProviderFactory;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.services.jcr.ext.common.SessionProvider;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.EventListener;
import org.exoplatform.webui.event.Event.Phase;
import org.exoplatform.webui.form.UIForm;
/**
* Created by The eXo Platform SARL
* Author : Vu Duy Tu
* [email protected]
* 14-01-2009 - 04:20:05
*/
@ComponentConfig(
lifecycle = UIFormLifecycle.class,
template = "app:/templates/faq/webui/popup/UISelectForumForm.gtmpl",
events = {
@EventConfig(listeners = UISelectForumForm.CloseActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UISelectForumForm.SelectForumActionListener.class, phase = Phase.DECODE)
}
)
public class UISelectForumForm extends UIForm implements UIPopupComponent {
private String questionId;
private String categoryId;
private static String link = "";
private List<Forum> listForum;
public UISelectForumForm() {
}
@SuppressWarnings("unused")
private void setLink(String link_) { link = link_;}
public void activate() throws Exception { }
public void deActivate() throws Exception { }
public void setQuestionId(String questionId) {
this.questionId = questionId;
}
public List<Forum> getListForum() {
FAQSetting faqSetting = new FAQSetting();
FAQUtils.getPorletPreference(faqSetting);
String catePath = faqSetting.getPathNameCategoryForum();
listForum = new ArrayList<Forum>();
if (catePath.indexOf(";") > 0) {
catePath = catePath.substring(0, catePath.indexOf(";"));
categoryId = catePath.substring(catePath.lastIndexOf("/") + 1);
SessionProvider sProvider = SessionProviderFactory.createSystemProvider();
try {
ForumService forumService = (ForumService) PortalContainer.getInstance().getComponentInstanceOfType(ForumService.class);
String strQuery = "@exo:isClosed='false' and @exo:isLock='false'";
listForum = forumService.getForums(sProvider, categoryId, strQuery);
} catch (Exception e) {
e.printStackTrace();
} finally {
sProvider.close();
}
}
return listForum;
}
static public class CloseActionListener extends EventListener<UISelectForumForm> {
public void execute(Event<UISelectForumForm> event) throws Exception {
UISelectForumForm uiForm = event.getSource();
UIFAQPortlet portlet = uiForm.getAncestorOfType(UIFAQPortlet.class);
portlet.cancelAction();
}
}
static public class SelectForumActionListener extends EventListener<UISelectForumForm> {
@SuppressWarnings("unchecked")
public void execute(Event<UISelectForumForm> event) throws Exception {
UISelectForumForm uiForm = event.getSource();
String forumId = event.getRequestContext().getRequestParameter(OBJECTID);
SessionProvider sProvider = SessionProviderFactory.createSystemProvider();
try {
// set url for Topic link.
link = link.replaceAll("faq", "forum").replaceFirst("UISelectForumForm", "UIBreadcumbs").replaceFirst("SelectForum", "ChangePath").replaceAll("&", "&");
String selectedNode = Util.getUIPortal().getSelectedNode().getUri() ;
String portalName = "/" + Util.getUIPortal().getName() ;
if(link.indexOf(portalName) > 0) {
if(link.indexOf(portalName + "/" + selectedNode) < 0){
link = link.replaceFirst(portalName, portalName + "/" + selectedNode) ;
}
}
PortalRequestContext portalContext = Util.getPortalRequestContext();
String url = portalContext.getRequest().getRequestURL().toString();
url = url.replaceFirst("http://", "") ;
url = url.substring(0, url.indexOf("/")) ;
url = "http://" + url;
/*-----------------------------------------------*/
FAQService faqService = (FAQService)PortalContainer.getInstance().getComponentInstanceOfType(FAQService.class) ;
Question question = faqService.getQuestionById(uiForm.questionId, sProvider);
Topic topic = new Topic();
String path = uiForm.categoryId+"/"+forumId+"/"+topic.getId() ;
link = link.replaceFirst("OBJECTID", path);
link = url + link;
topic.setOwner(question.getAuthor());
topic.setTopicName(question.getQuestion());
topic.setDescription(question.getDetail());
topic.setIcon("IconsView");
topic.setIsModeratePost(true);
topic.setLink(link);
ForumService forumService = (ForumService) PortalContainer.getInstance().getComponentInstanceOfType(ForumService.class);
forumService.saveTopic(sProvider, uiForm.categoryId, forumId, topic, true, false, "");
faqService.savePathDiscussQuestion(uiForm.questionId, path, sProvider);
- Post post;
+ Post post = new Post();
List<Answer> listAnswer = faqService.getPageListAnswer(sProvider, uiForm.questionId, false).getPageItem(0);
if(listAnswer != null && listAnswer.size() > 0) {
Answer[] AllAnswer = new Answer[listAnswer.size()];;
int i = 0;
for (Answer answer : listAnswer) {
post = new Post();
post.setIcon("IconsView");
post.setName("Re: " + question.getQuestion());
post.setMessage(answer.getResponses());
post.setOwner(answer.getResponseBy());
post.setLink(link);
forumService.savePost(sProvider, uiForm.categoryId, forumId, topic.getId(), post, true, "");
answer.setPostId(post.getId());
AllAnswer[i] = answer;
++i;
}
- faqService.saveAnswer(uiForm.questionId, AllAnswer, sProvider);
+ if(AllAnswer != null && AllAnswer.length > 0) {
+ faqService.saveAnswer(uiForm.questionId, AllAnswer, sProvider);
+ }
}
List<Comment> listComment = faqService.getPageListComment(sProvider, uiForm.questionId).getPageItem(0);
for (Comment comment : listComment) {
post = new Post();
post.setIcon("IconsView");
post.setName("Re: " + question.getQuestion());
post.setMessage(comment.getComments());
post.setOwner(comment.getCommentBy());
post.setLink(link);
forumService.savePost(sProvider, uiForm.categoryId, forumId, topic.getId(), post, true, "");
comment.setPostId(post.getId());
faqService.saveComment(uiForm.questionId, comment, false, sProvider);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sProvider.close();
}
UIFAQPortlet portlet = uiForm.getAncestorOfType(UIFAQPortlet.class);
portlet.cancelAction();
event.getRequestContext().addUIComponentToUpdateByAjax(portlet);
}
}
}
| false | true | public void execute(Event<UISelectForumForm> event) throws Exception {
UISelectForumForm uiForm = event.getSource();
String forumId = event.getRequestContext().getRequestParameter(OBJECTID);
SessionProvider sProvider = SessionProviderFactory.createSystemProvider();
try {
// set url for Topic link.
link = link.replaceAll("faq", "forum").replaceFirst("UISelectForumForm", "UIBreadcumbs").replaceFirst("SelectForum", "ChangePath").replaceAll("&", "&");
String selectedNode = Util.getUIPortal().getSelectedNode().getUri() ;
String portalName = "/" + Util.getUIPortal().getName() ;
if(link.indexOf(portalName) > 0) {
if(link.indexOf(portalName + "/" + selectedNode) < 0){
link = link.replaceFirst(portalName, portalName + "/" + selectedNode) ;
}
}
PortalRequestContext portalContext = Util.getPortalRequestContext();
String url = portalContext.getRequest().getRequestURL().toString();
url = url.replaceFirst("http://", "") ;
url = url.substring(0, url.indexOf("/")) ;
url = "http://" + url;
/*-----------------------------------------------*/
FAQService faqService = (FAQService)PortalContainer.getInstance().getComponentInstanceOfType(FAQService.class) ;
Question question = faqService.getQuestionById(uiForm.questionId, sProvider);
Topic topic = new Topic();
String path = uiForm.categoryId+"/"+forumId+"/"+topic.getId() ;
link = link.replaceFirst("OBJECTID", path);
link = url + link;
topic.setOwner(question.getAuthor());
topic.setTopicName(question.getQuestion());
topic.setDescription(question.getDetail());
topic.setIcon("IconsView");
topic.setIsModeratePost(true);
topic.setLink(link);
ForumService forumService = (ForumService) PortalContainer.getInstance().getComponentInstanceOfType(ForumService.class);
forumService.saveTopic(sProvider, uiForm.categoryId, forumId, topic, true, false, "");
faqService.savePathDiscussQuestion(uiForm.questionId, path, sProvider);
Post post;
List<Answer> listAnswer = faqService.getPageListAnswer(sProvider, uiForm.questionId, false).getPageItem(0);
if(listAnswer != null && listAnswer.size() > 0) {
Answer[] AllAnswer = new Answer[listAnswer.size()];;
int i = 0;
for (Answer answer : listAnswer) {
post = new Post();
post.setIcon("IconsView");
post.setName("Re: " + question.getQuestion());
post.setMessage(answer.getResponses());
post.setOwner(answer.getResponseBy());
post.setLink(link);
forumService.savePost(sProvider, uiForm.categoryId, forumId, topic.getId(), post, true, "");
answer.setPostId(post.getId());
AllAnswer[i] = answer;
++i;
}
faqService.saveAnswer(uiForm.questionId, AllAnswer, sProvider);
}
List<Comment> listComment = faqService.getPageListComment(sProvider, uiForm.questionId).getPageItem(0);
for (Comment comment : listComment) {
post = new Post();
post.setIcon("IconsView");
post.setName("Re: " + question.getQuestion());
post.setMessage(comment.getComments());
post.setOwner(comment.getCommentBy());
post.setLink(link);
forumService.savePost(sProvider, uiForm.categoryId, forumId, topic.getId(), post, true, "");
comment.setPostId(post.getId());
faqService.saveComment(uiForm.questionId, comment, false, sProvider);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sProvider.close();
}
UIFAQPortlet portlet = uiForm.getAncestorOfType(UIFAQPortlet.class);
portlet.cancelAction();
event.getRequestContext().addUIComponentToUpdateByAjax(portlet);
}
| public void execute(Event<UISelectForumForm> event) throws Exception {
UISelectForumForm uiForm = event.getSource();
String forumId = event.getRequestContext().getRequestParameter(OBJECTID);
SessionProvider sProvider = SessionProviderFactory.createSystemProvider();
try {
// set url for Topic link.
link = link.replaceAll("faq", "forum").replaceFirst("UISelectForumForm", "UIBreadcumbs").replaceFirst("SelectForum", "ChangePath").replaceAll("&", "&");
String selectedNode = Util.getUIPortal().getSelectedNode().getUri() ;
String portalName = "/" + Util.getUIPortal().getName() ;
if(link.indexOf(portalName) > 0) {
if(link.indexOf(portalName + "/" + selectedNode) < 0){
link = link.replaceFirst(portalName, portalName + "/" + selectedNode) ;
}
}
PortalRequestContext portalContext = Util.getPortalRequestContext();
String url = portalContext.getRequest().getRequestURL().toString();
url = url.replaceFirst("http://", "") ;
url = url.substring(0, url.indexOf("/")) ;
url = "http://" + url;
/*-----------------------------------------------*/
FAQService faqService = (FAQService)PortalContainer.getInstance().getComponentInstanceOfType(FAQService.class) ;
Question question = faqService.getQuestionById(uiForm.questionId, sProvider);
Topic topic = new Topic();
String path = uiForm.categoryId+"/"+forumId+"/"+topic.getId() ;
link = link.replaceFirst("OBJECTID", path);
link = url + link;
topic.setOwner(question.getAuthor());
topic.setTopicName(question.getQuestion());
topic.setDescription(question.getDetail());
topic.setIcon("IconsView");
topic.setIsModeratePost(true);
topic.setLink(link);
ForumService forumService = (ForumService) PortalContainer.getInstance().getComponentInstanceOfType(ForumService.class);
forumService.saveTopic(sProvider, uiForm.categoryId, forumId, topic, true, false, "");
faqService.savePathDiscussQuestion(uiForm.questionId, path, sProvider);
Post post = new Post();
List<Answer> listAnswer = faqService.getPageListAnswer(sProvider, uiForm.questionId, false).getPageItem(0);
if(listAnswer != null && listAnswer.size() > 0) {
Answer[] AllAnswer = new Answer[listAnswer.size()];;
int i = 0;
for (Answer answer : listAnswer) {
post = new Post();
post.setIcon("IconsView");
post.setName("Re: " + question.getQuestion());
post.setMessage(answer.getResponses());
post.setOwner(answer.getResponseBy());
post.setLink(link);
forumService.savePost(sProvider, uiForm.categoryId, forumId, topic.getId(), post, true, "");
answer.setPostId(post.getId());
AllAnswer[i] = answer;
++i;
}
if(AllAnswer != null && AllAnswer.length > 0) {
faqService.saveAnswer(uiForm.questionId, AllAnswer, sProvider);
}
}
List<Comment> listComment = faqService.getPageListComment(sProvider, uiForm.questionId).getPageItem(0);
for (Comment comment : listComment) {
post = new Post();
post.setIcon("IconsView");
post.setName("Re: " + question.getQuestion());
post.setMessage(comment.getComments());
post.setOwner(comment.getCommentBy());
post.setLink(link);
forumService.savePost(sProvider, uiForm.categoryId, forumId, topic.getId(), post, true, "");
comment.setPostId(post.getId());
faqService.saveComment(uiForm.questionId, comment, false, sProvider);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sProvider.close();
}
UIFAQPortlet portlet = uiForm.getAncestorOfType(UIFAQPortlet.class);
portlet.cancelAction();
event.getRequestContext().addUIComponentToUpdateByAjax(portlet);
}
|
diff --git a/src/com/tulskiy/musique/gui/dialogs/TracksInfoEditFieldDialog.java b/src/com/tulskiy/musique/gui/dialogs/TracksInfoEditFieldDialog.java
index e6cda18..0ef5b95 100644
--- a/src/com/tulskiy/musique/gui/dialogs/TracksInfoEditFieldDialog.java
+++ b/src/com/tulskiy/musique/gui/dialogs/TracksInfoEditFieldDialog.java
@@ -1,312 +1,306 @@
/*
* Copyright (c) 2008, 2009, 2010 Denis Tulskiy
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with this work. If not, see <http://www.gnu.org/licenses/>.
*/
package com.tulskiy.musique.gui.dialogs;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import com.tulskiy.musique.gui.components.GroupTable;
import com.tulskiy.musique.gui.model.MultiTagFieldModel;
import com.tulskiy.musique.gui.model.SingleTagFieldModel;
import com.tulskiy.musique.gui.model.TagFieldModel;
import com.tulskiy.musique.util.Util;
/**
* Author: Denis Tulskiy
* Date: Jul 15, 2010
*/
public class TracksInfoEditFieldDialog extends JDialog {
private JButton cancel;
private int DEFAULT_COLUMN_WIDTH = 280;
public TracksInfoEditFieldDialog(final GroupTable properties, final SingleTagFieldModel tagFieldModel) {
setTitle(tagFieldModel.isMultiTrackEditMode() ? "Edit multiple files" : "Edit single file");
setModal(false);
JComponent tagsTable = createTable(properties, tagFieldModel);
add(tagsTable, BorderLayout.CENTER);
Box b1 = new Box(BoxLayout.X_AXIS);
b1.add(Box.createHorizontalGlue());
JButton update = new JButton("Update");
b1.add(update);
update.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// update state with this dialog values
tagFieldModel.approveModel();
// sync parent dialog values with approved state
((TagFieldModel) properties.getModel()).refreshModel();
properties.revalidate();
properties.repaint();
setVisible(false);
dispose();
properties.requestFocus();
}
});
cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tagFieldModel.rejectModel();
setVisible(false);
dispose();
properties.requestFocus();
}
});
b1.add(Box.createHorizontalStrut(5));
b1.add(cancel);
b1.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 10));
add(b1, BorderLayout.SOUTH);
setSize(600, 380);
setLocationRelativeTo(SwingUtilities.windowForComponent(properties));
}
private JComponent createTable(final GroupTable parent, final TableModel model) {
final GroupTable table = new GroupTable() {
public Component prepareRenderer(final TableCellRenderer renderer,
final int row, final int column) {
final Component prepareRenderer = super
.prepareRenderer(renderer, row, column);
final TableColumn tableColumn = getColumnModel().getColumn(column);
tableColumn.setPreferredWidth(Math.max(
prepareRenderer.getPreferredSize().width + 20,
tableColumn.getPreferredWidth()));
tableColumn.setPreferredWidth(Math.max(
DEFAULT_COLUMN_WIDTH,
tableColumn.getPreferredWidth()));
return prepareRenderer;
}
};
table.setModel(model);
table.setFont(table.getFont().deriveFont(11f));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// table.getColumn("Key").setMaxWidth(120);
table.setShowVerticalLines(true);
table.setIntercellSpacing(new Dimension(1, 1));
table.setGridColor(Color.lightGray);
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
final JTextField editor = new JTextField();
table.setDefaultEditor(Object.class, new DefaultCellEditor(editor) {
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
- TableModel tableModel = table.getModel();
- if (tableModel instanceof SingleTagFieldModel) {
- if (((SingleTagFieldModel) tableModel).getTrackInfoItem().isMultiple()) {
- value = "";
- }
- }
JTextField c = (JTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);
c.setBorder(BorderFactory.createEmptyBorder());
c.setFont(table.getFont());
c.selectAll();
return c;
}
@Override
public void cancelCellEditing() {
super.cancelCellEditing();
}
@Override
protected void fireEditingStopped() {
TableModel tableModel = table.getModel();
if (tableModel instanceof MultiTagFieldModel) {
String value = (String) table.getCellEditor().getCellEditorValue();
if (Util.isEmpty(value) && ((MultiTagFieldModel) tableModel).getTrackInfoItems().get(table.getEditingRow()).isMultiple()) {
super.fireEditingCanceled();
return;
}
}
super.fireEditingStopped();
}
});
table.addKeyboardAction(KeyStroke.getKeyStroke("ENTER"), "startEditing", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
table.editCellAt(table.getSelectedRow(), 1);
editor.requestFocusInWindow();
}
});
table.addKeyboardAction(KeyStroke.getKeyStroke("DELETE"), "clearCell", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
table.getModel().setValueAt("", table.getSelectedRow(), 1);
table.repaint();
}
});
table.addKeyboardAction(KeyStroke.getKeyStroke("ESCAPE"), "exitOrStop", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
table.getCellEditor().cancelCellEditing();
} else {
cancel.doClick();
}
}
});
editor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (table.isEditing() && (
e.getKeyCode() == KeyEvent.VK_DOWN ||
e.getKeyCode() == KeyEvent.VK_UP)) {
table.getCellEditor().cancelCellEditing();
}
}
});
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
show(e);
}
@Override
public void mousePressed(MouseEvent e) {
show(e);
}
public void show(MouseEvent e) {
if (e.isPopupTrigger()) {
int index = table.rowAtPoint(e.getPoint());
if (index != -1) {
if (!table.isRowSelected(index)) {
table.setRowSelectionInterval(index, index);
}
}
JPopupMenu contextMenu = buildContextMenu(table);
contextMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return scrollPane;
}
private JPopupMenu buildContextMenu(final GroupTable properties) {
final SingleTagFieldModel tagFieldModel = (SingleTagFieldModel) properties.getModel();
final List<Integer> selectedRows = new LinkedList<Integer>();
if (properties.getSelectedRowCount() > 0) {
for (int row : properties.getSelectedRows()) {
selectedRows.add(row);
}
}
ImageIcon emptyIcon = new ImageIcon(new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB));
final JPopupMenu menu = new JPopupMenu();
if (tagFieldModel.isMultiTrackEditMode()) {
if (!selectedRows.isEmpty()) {
final SingleTagFieldModel editTagFieldModel = new SingleTagFieldModel(tagFieldModel.getTrackInfoItem(),
tagFieldModel.getTrackInfoItem().getTracks().get(selectedRows.get(0)));
JMenuItem menuItemEdit = new JMenuItem("Edit");
menuItemEdit.setIcon(emptyIcon);
menu.add(menuItemEdit).addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TracksInfoEditFieldDialog dialog = new TracksInfoEditFieldDialog(properties, editTagFieldModel);
dialog.setVisible(true);
}
});
}
}
else {
JMenuItem menuItemAdd = new JMenuItem("Add");
menuItemAdd.setIcon(emptyIcon);
menu.add(menuItemAdd).addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tagFieldModel.addValue();
properties.clearSelection();
properties.revalidate();
properties.repaint();
}
});
if (!selectedRows.isEmpty()) {
JMenuItem menuItemRemove = new JMenuItem("Remove");
menuItemRemove.setIcon(emptyIcon);
menu.add(menuItemRemove).addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int row : selectedRows) {
tagFieldModel.removeValue(row);
}
properties.clearSelection();
properties.revalidate();
properties.repaint();
}
});
}
}
return menu;
}
}
| true | true | private JComponent createTable(final GroupTable parent, final TableModel model) {
final GroupTable table = new GroupTable() {
public Component prepareRenderer(final TableCellRenderer renderer,
final int row, final int column) {
final Component prepareRenderer = super
.prepareRenderer(renderer, row, column);
final TableColumn tableColumn = getColumnModel().getColumn(column);
tableColumn.setPreferredWidth(Math.max(
prepareRenderer.getPreferredSize().width + 20,
tableColumn.getPreferredWidth()));
tableColumn.setPreferredWidth(Math.max(
DEFAULT_COLUMN_WIDTH,
tableColumn.getPreferredWidth()));
return prepareRenderer;
}
};
table.setModel(model);
table.setFont(table.getFont().deriveFont(11f));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// table.getColumn("Key").setMaxWidth(120);
table.setShowVerticalLines(true);
table.setIntercellSpacing(new Dimension(1, 1));
table.setGridColor(Color.lightGray);
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
final JTextField editor = new JTextField();
table.setDefaultEditor(Object.class, new DefaultCellEditor(editor) {
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
TableModel tableModel = table.getModel();
if (tableModel instanceof SingleTagFieldModel) {
if (((SingleTagFieldModel) tableModel).getTrackInfoItem().isMultiple()) {
value = "";
}
}
JTextField c = (JTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);
c.setBorder(BorderFactory.createEmptyBorder());
c.setFont(table.getFont());
c.selectAll();
return c;
}
@Override
public void cancelCellEditing() {
super.cancelCellEditing();
}
@Override
protected void fireEditingStopped() {
TableModel tableModel = table.getModel();
if (tableModel instanceof MultiTagFieldModel) {
String value = (String) table.getCellEditor().getCellEditorValue();
if (Util.isEmpty(value) && ((MultiTagFieldModel) tableModel).getTrackInfoItems().get(table.getEditingRow()).isMultiple()) {
super.fireEditingCanceled();
return;
}
}
super.fireEditingStopped();
}
});
table.addKeyboardAction(KeyStroke.getKeyStroke("ENTER"), "startEditing", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
table.editCellAt(table.getSelectedRow(), 1);
editor.requestFocusInWindow();
}
});
table.addKeyboardAction(KeyStroke.getKeyStroke("DELETE"), "clearCell", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
table.getModel().setValueAt("", table.getSelectedRow(), 1);
table.repaint();
}
});
table.addKeyboardAction(KeyStroke.getKeyStroke("ESCAPE"), "exitOrStop", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
table.getCellEditor().cancelCellEditing();
} else {
cancel.doClick();
}
}
});
editor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (table.isEditing() && (
e.getKeyCode() == KeyEvent.VK_DOWN ||
e.getKeyCode() == KeyEvent.VK_UP)) {
table.getCellEditor().cancelCellEditing();
}
}
});
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
show(e);
}
@Override
public void mousePressed(MouseEvent e) {
show(e);
}
public void show(MouseEvent e) {
if (e.isPopupTrigger()) {
int index = table.rowAtPoint(e.getPoint());
if (index != -1) {
if (!table.isRowSelected(index)) {
table.setRowSelectionInterval(index, index);
}
}
JPopupMenu contextMenu = buildContextMenu(table);
contextMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return scrollPane;
}
| private JComponent createTable(final GroupTable parent, final TableModel model) {
final GroupTable table = new GroupTable() {
public Component prepareRenderer(final TableCellRenderer renderer,
final int row, final int column) {
final Component prepareRenderer = super
.prepareRenderer(renderer, row, column);
final TableColumn tableColumn = getColumnModel().getColumn(column);
tableColumn.setPreferredWidth(Math.max(
prepareRenderer.getPreferredSize().width + 20,
tableColumn.getPreferredWidth()));
tableColumn.setPreferredWidth(Math.max(
DEFAULT_COLUMN_WIDTH,
tableColumn.getPreferredWidth()));
return prepareRenderer;
}
};
table.setModel(model);
table.setFont(table.getFont().deriveFont(11f));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// table.getColumn("Key").setMaxWidth(120);
table.setShowVerticalLines(true);
table.setIntercellSpacing(new Dimension(1, 1));
table.setGridColor(Color.lightGray);
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
final JTextField editor = new JTextField();
table.setDefaultEditor(Object.class, new DefaultCellEditor(editor) {
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
JTextField c = (JTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);
c.setBorder(BorderFactory.createEmptyBorder());
c.setFont(table.getFont());
c.selectAll();
return c;
}
@Override
public void cancelCellEditing() {
super.cancelCellEditing();
}
@Override
protected void fireEditingStopped() {
TableModel tableModel = table.getModel();
if (tableModel instanceof MultiTagFieldModel) {
String value = (String) table.getCellEditor().getCellEditorValue();
if (Util.isEmpty(value) && ((MultiTagFieldModel) tableModel).getTrackInfoItems().get(table.getEditingRow()).isMultiple()) {
super.fireEditingCanceled();
return;
}
}
super.fireEditingStopped();
}
});
table.addKeyboardAction(KeyStroke.getKeyStroke("ENTER"), "startEditing", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
table.editCellAt(table.getSelectedRow(), 1);
editor.requestFocusInWindow();
}
});
table.addKeyboardAction(KeyStroke.getKeyStroke("DELETE"), "clearCell", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
table.getModel().setValueAt("", table.getSelectedRow(), 1);
table.repaint();
}
});
table.addKeyboardAction(KeyStroke.getKeyStroke("ESCAPE"), "exitOrStop", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
table.getCellEditor().cancelCellEditing();
} else {
cancel.doClick();
}
}
});
editor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (table.isEditing() && (
e.getKeyCode() == KeyEvent.VK_DOWN ||
e.getKeyCode() == KeyEvent.VK_UP)) {
table.getCellEditor().cancelCellEditing();
}
}
});
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
show(e);
}
@Override
public void mousePressed(MouseEvent e) {
show(e);
}
public void show(MouseEvent e) {
if (e.isPopupTrigger()) {
int index = table.rowAtPoint(e.getPoint());
if (index != -1) {
if (!table.isRowSelected(index)) {
table.setRowSelectionInterval(index, index);
}
}
JPopupMenu contextMenu = buildContextMenu(table);
contextMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return scrollPane;
}
|
diff --git a/src/main/java/org/apache/bcel/classfile/LocalVariableTable.java b/src/main/java/org/apache/bcel/classfile/LocalVariableTable.java
index 700c6382..f5371953 100644
--- a/src/main/java/org/apache/bcel/classfile/LocalVariableTable.java
+++ b/src/main/java/org/apache/bcel/classfile/LocalVariableTable.java
@@ -1,197 +1,197 @@
/*
* Copyright 2000-2004 The Apache Software Foundation
*
* 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.bcel.classfile;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.apache.bcel.Constants;
/**
* This class represents colection of local variables in a
* method. This attribute is contained in the <em>Code</em> attribute.
*
* @version $Id$
* @author <A HREF="mailto:[email protected]">M. Dahm</A>
* @see Code
* @see LocalVariable
*/
public class LocalVariableTable extends Attribute {
private int local_variable_table_length; // Table of local
private LocalVariable[] local_variable_table; // variables
/**
* Initialize from another object. Note that both objects use the same
* references (shallow copy). Use copy() for a physical copy.
*/
public LocalVariableTable(LocalVariableTable c) {
this(c.getNameIndex(), c.getLength(), c.getLocalVariableTable(), c.getConstantPool());
}
/**
* @param name_index Index in constant pool to `LocalVariableTable'
* @param length Content length in bytes
* @param local_variable_table Table of local variables
* @param constant_pool Array of constants
*/
public LocalVariableTable(int name_index, int length, LocalVariable[] local_variable_table,
ConstantPool constant_pool) {
super(Constants.ATTR_LOCAL_VARIABLE_TABLE, name_index, length, constant_pool);
setLocalVariableTable(local_variable_table);
}
/**
* Construct object from file stream.
* @param name_index Index in constant pool
* @param length Content length in bytes
* @param file Input stream
* @param constant_pool Array of constants
* @throws IOException
*/
LocalVariableTable(int name_index, int length, DataInputStream file, ConstantPool constant_pool)
throws IOException {
this(name_index, length, (LocalVariable[]) null, constant_pool);
local_variable_table_length = (file.readUnsignedShort());
local_variable_table = new LocalVariable[local_variable_table_length];
for (int i = 0; i < local_variable_table_length; i++) {
local_variable_table[i] = new LocalVariable(file, constant_pool);
}
}
/**
* Called by objects that are traversing the nodes of the tree implicitely
* defined by the contents of a Java class. I.e., the hierarchy of methods,
* fields, attributes, etc. spawns a tree of objects.
*
* @param v Visitor object
*/
public void accept( Visitor v ) {
v.visitLocalVariableTable(this);
}
/**
* Dump local variable table attribute to file stream in binary format.
*
* @param file Output file stream
* @throws IOException
*/
public final void dump( DataOutputStream file ) throws IOException {
super.dump(file);
file.writeShort(local_variable_table_length);
for (int i = 0; i < local_variable_table_length; i++) {
local_variable_table[i].dump(file);
}
}
/**
* @return Array of local variables of method.
*/
public final LocalVariable[] getLocalVariableTable() {
return local_variable_table;
}
/**
* @return first matching variable using index
*
* @param index the variable slot
*
* @return the first LocalVariable that matches the slot or null if not found
*
* @deprecated since 5.2 because multiple variables can share the
* same slot, use getLocalVariable(int index, int pc) instead.
*/
public final LocalVariable getLocalVariable( int index ) {
for (int i = 0; i < local_variable_table_length; i++) {
if (local_variable_table[i].getIndex() == index) {
return local_variable_table[i];
}
}
return null;
}
/**
* @return matching variable using index when variable is used at supplied pc
*
* @param index the variable slot
* @param pc the current pc that this variable is alive
*
* @return the LocalVariable that matches or null if not found
*/
public final LocalVariable getLocalVariable( int index, int pc ) {
for (int i = 0; i < local_variable_table_length; i++) {
if (local_variable_table[i].getIndex() == index) {
int start_pc = local_variable_table[i].getStartPC();
int end_pc = start_pc + local_variable_table[i].getLength();
- if ((pc >= start_pc) && (pc < end_pc)) {
+ if ((pc >= start_pc) && (pc <= end_pc)) {
return local_variable_table[i];
}
}
}
return null;
}
public final void setLocalVariableTable( LocalVariable[] local_variable_table ) {
this.local_variable_table = local_variable_table;
local_variable_table_length = (local_variable_table == null)
? 0
: local_variable_table.length;
}
/**
* @return String representation.
*/
public final String toString() {
StringBuffer buf = new StringBuffer("");
for (int i = 0; i < local_variable_table_length; i++) {
buf.append(local_variable_table[i].toString());
if (i < local_variable_table_length - 1) {
buf.append('\n');
}
}
return buf.toString();
}
/**
* @return deep copy of this attribute
*/
public Attribute copy( ConstantPool _constant_pool ) {
LocalVariableTable c = (LocalVariableTable) clone();
c.local_variable_table = new LocalVariable[local_variable_table_length];
for (int i = 0; i < local_variable_table_length; i++) {
c.local_variable_table[i] = local_variable_table[i].copy();
}
c.constant_pool = _constant_pool;
return c;
}
public final int getTableLength() {
return local_variable_table_length;
}
}
| true | true | public final LocalVariable getLocalVariable( int index, int pc ) {
for (int i = 0; i < local_variable_table_length; i++) {
if (local_variable_table[i].getIndex() == index) {
int start_pc = local_variable_table[i].getStartPC();
int end_pc = start_pc + local_variable_table[i].getLength();
if ((pc >= start_pc) && (pc < end_pc)) {
return local_variable_table[i];
}
}
}
return null;
}
| public final LocalVariable getLocalVariable( int index, int pc ) {
for (int i = 0; i < local_variable_table_length; i++) {
if (local_variable_table[i].getIndex() == index) {
int start_pc = local_variable_table[i].getStartPC();
int end_pc = start_pc + local_variable_table[i].getLength();
if ((pc >= start_pc) && (pc <= end_pc)) {
return local_variable_table[i];
}
}
}
return null;
}
|
diff --git a/src/com/bingo/eatime/EaTimeLoginServlet.java b/src/com/bingo/eatime/EaTimeLoginServlet.java
index 9c33809..a29c39e 100644
--- a/src/com/bingo/eatime/EaTimeLoginServlet.java
+++ b/src/com/bingo/eatime/EaTimeLoginServlet.java
@@ -1,49 +1,58 @@
package com.bingo.eatime;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.bingo.eatime.core.Person;
import com.bingo.eatime.core.PersonManager;
public class EaTimeLoginServlet extends HttpServlet {
private static final long serialVersionUID = 4588543340482590495L;
private static final Logger log = Logger.getLogger(EaTimeLoginServlet.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
String user = req.getParameter("user");
String password = req.getParameter("pwd");
HttpSession session = req.getSession();
if ((user.equals("ryan") && password.equals("crd")) || (user.equals("kevin") && password.equals("kevin"))) {
try {
Person me = null;
me = PersonManager.getPersonByUsername(user);
- String username = user;
- session.setAttribute("loginStatus", "true");
- session.setAttribute("user", username);
- session.setAttribute("userImg", me.getGravatarUrlString());
- session.setAttribute("fullname", me.getFullName(true));
- resp.sendRedirect("/eatime");
+ if (me != null) {
+ String username = user;
+ session.setAttribute("loginStatus", "true");
+ session.setAttribute("user", username);
+ session.setAttribute("userImg", me.getGravatarUrlString());
+ session.setAttribute("fullname", me.getFullName(true));
+ resp.sendRedirect("/eatime");
+ } else {
+ try {
+ session.setAttribute("loginStatus", "false");
+ resp.sendRedirect("/login.jsp");
+ } catch (IOException e) {
+ log.log(Level.SEVERE, "Cannot redirect to /login.jsp", e);
+ }
+ }
} catch (IOException e) {
log.log(Level.SEVERE, "Cannot redirect to /eatime.", e);
}
} else {
try {
session.setAttribute("loginStatus", "false");
resp.sendRedirect("/login.jsp");
} catch (IOException e) {
log.log(Level.SEVERE, "Cannot redirect to /login.jsp", e);
}
}
}
}
| true | true | public void doPost(HttpServletRequest req, HttpServletResponse resp) {
String user = req.getParameter("user");
String password = req.getParameter("pwd");
HttpSession session = req.getSession();
if ((user.equals("ryan") && password.equals("crd")) || (user.equals("kevin") && password.equals("kevin"))) {
try {
Person me = null;
me = PersonManager.getPersonByUsername(user);
String username = user;
session.setAttribute("loginStatus", "true");
session.setAttribute("user", username);
session.setAttribute("userImg", me.getGravatarUrlString());
session.setAttribute("fullname", me.getFullName(true));
resp.sendRedirect("/eatime");
} catch (IOException e) {
log.log(Level.SEVERE, "Cannot redirect to /eatime.", e);
}
} else {
try {
session.setAttribute("loginStatus", "false");
resp.sendRedirect("/login.jsp");
} catch (IOException e) {
log.log(Level.SEVERE, "Cannot redirect to /login.jsp", e);
}
}
}
| public void doPost(HttpServletRequest req, HttpServletResponse resp) {
String user = req.getParameter("user");
String password = req.getParameter("pwd");
HttpSession session = req.getSession();
if ((user.equals("ryan") && password.equals("crd")) || (user.equals("kevin") && password.equals("kevin"))) {
try {
Person me = null;
me = PersonManager.getPersonByUsername(user);
if (me != null) {
String username = user;
session.setAttribute("loginStatus", "true");
session.setAttribute("user", username);
session.setAttribute("userImg", me.getGravatarUrlString());
session.setAttribute("fullname", me.getFullName(true));
resp.sendRedirect("/eatime");
} else {
try {
session.setAttribute("loginStatus", "false");
resp.sendRedirect("/login.jsp");
} catch (IOException e) {
log.log(Level.SEVERE, "Cannot redirect to /login.jsp", e);
}
}
} catch (IOException e) {
log.log(Level.SEVERE, "Cannot redirect to /eatime.", e);
}
} else {
try {
session.setAttribute("loginStatus", "false");
resp.sendRedirect("/login.jsp");
} catch (IOException e) {
log.log(Level.SEVERE, "Cannot redirect to /login.jsp", e);
}
}
}
|
diff --git a/x10.compiler/src/x10c/visit/DebugCodeWriter.java b/x10.compiler/src/x10c/visit/DebugCodeWriter.java
index bed7dd4c8..a3655db53 100644
--- a/x10.compiler/src/x10c/visit/DebugCodeWriter.java
+++ b/x10.compiler/src/x10c/visit/DebugCodeWriter.java
@@ -1,180 +1,180 @@
package x10c.visit;
import java.io.IOException;
import java.io.PrintStream;
import polyglot.frontend.Job;
import polyglot.util.CodeWriter;
public class DebugCodeWriter extends CodeWriter {
private final CodeWriter w;
private final String name;
private PrintStream html;
public DebugCodeWriter(CodeWriter w, Job job) {
String htmlname = job.source().name().replaceFirst(".x10", ".html");
if (htmlname.equals(job.source().name())) // double check to prevent overwriting the source
htmlname = htmlname + ".html";
name = htmlname;
try {
html = new PrintStream(name);
} catch (IOException e) {
html = System.err;
}
html.println("<html><head>");
//html.println("<meta http-equiv='Refresh' content='20'/>");
html.println("<style type='text/css'>\n" +
" a:hover {\n" +
" background-color: #DDF;\n" +
" }\n" +
" a.a { position: relative; }\n" +
" a.a span {\n" +
" border: dotted 2px #CCC;\n" +
" background-color: #AEF;\n" +
" display: none;\n" +
" z-index: 1;\n" +
" position: absolute; top: 1em; left: 0px;\n" +
" font-size: smaller;" +
" }\n" +
"</style>");
html.println("<script type='text/javascript'>\n" +
"\n" +
"function toggle() {\n" +
" h = this.getElementsByTagName('span')[0];\n" +
" if (h.style.display == 'block') {\n" +
" h.style.display = 'none';\n" +
" } else {\n" +
" h.style.display = 'block';\n" +
" }\n" +
"}\n" +
"\n" +
- "function onload() {\n" +
+ "function setup() {\n" +
" elements = document.getElementsByTagName('a')\n" +
" for (var i = 0; i < elements.length; i++) {\n" +
" elt = elements[i];\n" +
" if (elt.className != 'a') continue;\n" +
" elt.onclick = toggle;\n" +
" }\n" +
"}\n" +
"\n" +
"</script>\n" +
"");
- html.println("</head><body>");
+ html.println("</head><body onload='setup();'>");
html.println("<pre>");
this.w = w;
}
public void allowBreak(int n, int level, String alt, int altlen) {
w.allowBreak(n, level, alt, altlen);
}
public void allowBreak(int n, String alt) {
w.allowBreak(n, alt);
}
public void allowBreak(int n) {
w.allowBreak(n);
}
public void begin(int n) {
w.begin(n);
}
public void close() throws IOException {
try {
w.close();
} finally {
html.println("</pre></body></html>");
if (html != System.err)
html.close();
}
}
public void end() {
w.end();
}
public boolean equals(Object arg0) {
return w.equals(arg0);
}
public boolean flush() throws IOException {
return w.flush();
}
public boolean flush(boolean format) throws IOException {
return w.flush(format);
}
public int hashCode() {
return w.hashCode();
}
public void newline() {
w.newline();
html.println();
}
public void newline(int n, int level) {
w.newline(n, level);
html.println();
}
public void newline(int n) {
w.newline(n);
html.println();
}
public String toString() {
return w.toString();
}
public void unifiedBreak(int n, int level, String alt, int altlen) {
w.unifiedBreak(n, level, alt, altlen);
}
public void unifiedBreak(int n) {
w.unifiedBreak(n);
}
public void write(String s, int length) {
w.write(s, length);
html.print(html_escape(s));
}
public void write(String s) {
//if (name.equals("polyglot.util.OptimalCodeWriter")) {
StackTraceElement[] stackTrace = new Exception().getStackTrace();
StringBuffer sb = new StringBuffer();
for (int i = 1; i < Math.min(60, stackTrace.length); i++) {
sb.append("<br/>");
sb.append(stackTrace[i].toString());
}
String stack = sb.toString();
// hide location as a stack tooltip
if (s.startsWith("/*location:")) {
stack = s.substring("/*location:".length(), s.indexOf("*/"));
s = s.substring(s.indexOf("*/") + 2);
}
html.print("<a class='a'>" + html_escape(s) +
"<span>" + stack + "</span></a>");
w.write(s);
}
public static String html_escape(String s) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '<': sb.append("<"); break;
case '>': sb.append(">"); break;
case '&': sb.append("&"); break;
default: sb.append(c);
}
}
return sb.toString();
}
}
| false | true | public DebugCodeWriter(CodeWriter w, Job job) {
String htmlname = job.source().name().replaceFirst(".x10", ".html");
if (htmlname.equals(job.source().name())) // double check to prevent overwriting the source
htmlname = htmlname + ".html";
name = htmlname;
try {
html = new PrintStream(name);
} catch (IOException e) {
html = System.err;
}
html.println("<html><head>");
//html.println("<meta http-equiv='Refresh' content='20'/>");
html.println("<style type='text/css'>\n" +
" a:hover {\n" +
" background-color: #DDF;\n" +
" }\n" +
" a.a { position: relative; }\n" +
" a.a span {\n" +
" border: dotted 2px #CCC;\n" +
" background-color: #AEF;\n" +
" display: none;\n" +
" z-index: 1;\n" +
" position: absolute; top: 1em; left: 0px;\n" +
" font-size: smaller;" +
" }\n" +
"</style>");
html.println("<script type='text/javascript'>\n" +
"\n" +
"function toggle() {\n" +
" h = this.getElementsByTagName('span')[0];\n" +
" if (h.style.display == 'block') {\n" +
" h.style.display = 'none';\n" +
" } else {\n" +
" h.style.display = 'block';\n" +
" }\n" +
"}\n" +
"\n" +
"function onload() {\n" +
" elements = document.getElementsByTagName('a')\n" +
" for (var i = 0; i < elements.length; i++) {\n" +
" elt = elements[i];\n" +
" if (elt.className != 'a') continue;\n" +
" elt.onclick = toggle;\n" +
" }\n" +
"}\n" +
"\n" +
"</script>\n" +
"");
html.println("</head><body>");
html.println("<pre>");
this.w = w;
}
| public DebugCodeWriter(CodeWriter w, Job job) {
String htmlname = job.source().name().replaceFirst(".x10", ".html");
if (htmlname.equals(job.source().name())) // double check to prevent overwriting the source
htmlname = htmlname + ".html";
name = htmlname;
try {
html = new PrintStream(name);
} catch (IOException e) {
html = System.err;
}
html.println("<html><head>");
//html.println("<meta http-equiv='Refresh' content='20'/>");
html.println("<style type='text/css'>\n" +
" a:hover {\n" +
" background-color: #DDF;\n" +
" }\n" +
" a.a { position: relative; }\n" +
" a.a span {\n" +
" border: dotted 2px #CCC;\n" +
" background-color: #AEF;\n" +
" display: none;\n" +
" z-index: 1;\n" +
" position: absolute; top: 1em; left: 0px;\n" +
" font-size: smaller;" +
" }\n" +
"</style>");
html.println("<script type='text/javascript'>\n" +
"\n" +
"function toggle() {\n" +
" h = this.getElementsByTagName('span')[0];\n" +
" if (h.style.display == 'block') {\n" +
" h.style.display = 'none';\n" +
" } else {\n" +
" h.style.display = 'block';\n" +
" }\n" +
"}\n" +
"\n" +
"function setup() {\n" +
" elements = document.getElementsByTagName('a')\n" +
" for (var i = 0; i < elements.length; i++) {\n" +
" elt = elements[i];\n" +
" if (elt.className != 'a') continue;\n" +
" elt.onclick = toggle;\n" +
" }\n" +
"}\n" +
"\n" +
"</script>\n" +
"");
html.println("</head><body onload='setup();'>");
html.println("<pre>");
this.w = w;
}
|
diff --git a/com.technophobia.substeps.testlauncher/src/main/java/com/technophobia/substeps/model/structure/DefaultSubstepsTestParentElement.java b/com.technophobia.substeps.testlauncher/src/main/java/com/technophobia/substeps/model/structure/DefaultSubstepsTestParentElement.java
index fb5d934..c87f1f4 100644
--- a/com.technophobia.substeps.testlauncher/src/main/java/com/technophobia/substeps/model/structure/DefaultSubstepsTestParentElement.java
+++ b/com.technophobia.substeps.testlauncher/src/main/java/com/technophobia/substeps/model/structure/DefaultSubstepsTestParentElement.java
@@ -1,151 +1,151 @@
package com.technophobia.substeps.model.structure;
import java.util.ArrayList;
import java.util.List;
public class DefaultSubstepsTestParentElement extends AbstractSubstepsTestElement implements SubstepsTestParentElement {
private final List<SubstepsTestElement> children;
private Status childrenStatus;
private final int testCount;
public DefaultSubstepsTestParentElement(final SubstepsTestParentElement parent, final String id,
final String testName, final int testCount) {
super(parent, id, testName);
this.testCount = testCount;
this.children = new ArrayList<SubstepsTestElement>(testCount);
this.childrenStatus = Status.NOT_RUN;
}
@Override
public Result getTestResult(final boolean includeChildren) {
if (includeChildren) {
return getStatus().asResult();
}
return super.getStatus().asResult();
}
@Override
public int getChildCount() {
return testCount;
}
@Override
public SubstepsTestElement[] getChildren() {
return children.toArray(new SubstepsTestElement[children.size()]);
}
@Override
public void addChild(final SubstepsTestElement child) {
children.add(child);
}
@Override
public Status getStatus() {
final Status suiteStatus = getSuiteStatus();
if (!childrenStatus.equals(Status.NOT_RUN)) {
return Status.combineStatus(childrenStatus, suiteStatus);
}
return suiteStatus;
}
@Override
public void childChangedStatus(final SubstepsTestElement child, final Status childStatus) {
if (isFirstChild(child) && childStatus.isRunning()) {
// is 1st child, and is running, so copy status
updateTimeAndChildrenStatus(childStatus);
return;
}
- final SubstepsTestElement lastChild = children.get(children.size());
+ final SubstepsTestElement lastChild = children.get(getChildCount() - 1);
if (child == lastChild) {
if (childStatus.isComplete()) {
// all children done, collect cumulative status
updateTimeAndChildrenStatus(getCumulatedStatus());
return;
}
} else if (!lastChild.getStatus().isNotRun()) {
// child is not last, but last child has been run - child has been
// rerun or is rerunning
updateTimeAndChildrenStatus(getCumulatedStatus());
return;
}
// finally, set RUNNING_FAILURE/ERROR if child has failed but suite has
// not failed
if (childStatus.isFailure()) {
if (!childrenStatus.isErrorOrFailure()) {
updateTimeAndChildrenStatus(Status.RUNNING_FAILURE);
return;
}
} else if (childStatus.isError()) {
if (!childrenStatus.isError()) {
updateTimeAndChildrenStatus(Status.RUNNING_ERROR);
return;
}
}
}
private boolean isFirstChild(final SubstepsTestElement child) {
return !children.isEmpty() && children.get(0) == child;
}
private void updateTimeAndChildrenStatus(final Status status) {
if (childrenStatus.equals(status)) {
return;
}
if (status.equals(Status.RUNNING)) {
if (time >= 0.0d) {
// re-running child - ignore
} else {
time = -System.currentTimeMillis() / 1000.0d;
}
} else if (status.isComplete()) {
if (time < 0) {
final double endTime = System.currentTimeMillis() / 1000.0d;
time = endTime + time;
}
}
this.childrenStatus = status;
final SubstepsTestParentElement parent = getParent();
if (parent != null) {
parent.childChangedStatus(this, getStatus());
}
}
private Status getCumulatedStatus() {
// copy list to avoid concurrency problems
final SubstepsTestElement[] children = this.children.toArray(new SubstepsTestElement[this.children.size()]);
if (children.length == 0)
return getSuiteStatus();
Status cumulated = children[0].getStatus();
for (int i = 1; i < children.length; i++) {
final Status childStatus = children[i].getStatus();
cumulated = Status.combineStatus(cumulated, childStatus);
}
// not necessary, see special code in Status.combineProgress()
// if (suiteStatus.isErrorOrFailure() && cumulated.isNotRun())
// return suiteStatus; //progress is Done if error in Suite and no
// children run
return cumulated;
}
private Status getSuiteStatus() {
return super.getStatus();
}
}
| true | true | public void childChangedStatus(final SubstepsTestElement child, final Status childStatus) {
if (isFirstChild(child) && childStatus.isRunning()) {
// is 1st child, and is running, so copy status
updateTimeAndChildrenStatus(childStatus);
return;
}
final SubstepsTestElement lastChild = children.get(children.size());
if (child == lastChild) {
if (childStatus.isComplete()) {
// all children done, collect cumulative status
updateTimeAndChildrenStatus(getCumulatedStatus());
return;
}
} else if (!lastChild.getStatus().isNotRun()) {
// child is not last, but last child has been run - child has been
// rerun or is rerunning
updateTimeAndChildrenStatus(getCumulatedStatus());
return;
}
// finally, set RUNNING_FAILURE/ERROR if child has failed but suite has
// not failed
if (childStatus.isFailure()) {
if (!childrenStatus.isErrorOrFailure()) {
updateTimeAndChildrenStatus(Status.RUNNING_FAILURE);
return;
}
} else if (childStatus.isError()) {
if (!childrenStatus.isError()) {
updateTimeAndChildrenStatus(Status.RUNNING_ERROR);
return;
}
}
}
| public void childChangedStatus(final SubstepsTestElement child, final Status childStatus) {
if (isFirstChild(child) && childStatus.isRunning()) {
// is 1st child, and is running, so copy status
updateTimeAndChildrenStatus(childStatus);
return;
}
final SubstepsTestElement lastChild = children.get(getChildCount() - 1);
if (child == lastChild) {
if (childStatus.isComplete()) {
// all children done, collect cumulative status
updateTimeAndChildrenStatus(getCumulatedStatus());
return;
}
} else if (!lastChild.getStatus().isNotRun()) {
// child is not last, but last child has been run - child has been
// rerun or is rerunning
updateTimeAndChildrenStatus(getCumulatedStatus());
return;
}
// finally, set RUNNING_FAILURE/ERROR if child has failed but suite has
// not failed
if (childStatus.isFailure()) {
if (!childrenStatus.isErrorOrFailure()) {
updateTimeAndChildrenStatus(Status.RUNNING_FAILURE);
return;
}
} else if (childStatus.isError()) {
if (!childrenStatus.isError()) {
updateTimeAndChildrenStatus(Status.RUNNING_ERROR);
return;
}
}
}
|
diff --git a/webapp/src/com/xenoage/zong/webapp/client/WebApp.java b/webapp/src/com/xenoage/zong/webapp/client/WebApp.java
index 4838a1bc..23df0412 100644
--- a/webapp/src/com/xenoage/zong/webapp/client/WebApp.java
+++ b/webapp/src/com/xenoage/zong/webapp/client/WebApp.java
@@ -1,43 +1,44 @@
package com.xenoage.zong.webapp.client;
import static com.xenoage.utils.math.Fraction._0;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.xenoage.zong.core.Score;
import com.xenoage.zong.core.music.util.Interval;
import com.xenoage.zong.core.position.MP;
import com.xenoage.zong.util.demo.ScoreRevolutionary;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class WebApp
implements EntryPoint {
/**
* This is the entry point method.
*/
@Override public void onModuleLoad() {
Score score = ScoreRevolutionary.createScore();
//String t = score.getClef(MP.atBeat(0, 1, 0, _0), Interval.BeforeOrAt).getType().toString() + " found";
//Clef clef = new Clef(ClefType.G);
//String t = clef.getType().toString();
//String t = new Point2f(5, 10).toString();
//Range r = Range.range(5);
//Label hello = new Label("Result: " + t); //"Aha "+r.getCount() + " " + Defaults.defaultFont.getSize() + " " + t);
RootPanel container = RootPanel.get("container");
+ container.add(new Label("If you see some text with musical data, it works:"));
container.add(new Label(findAClef(score, MP.atBeat(0, 1, 0, _0))));
container.add(new Label(findAClef(score, MP.atBeat(1, 1, 0, _0))));
MP mp = MP.atBeat(0, 1, 0, _0);
container.add(new Label("Voice at " + mp + ": " + score.getVoice(mp)));
}
private String findAClef(Score score, MP mp) {
return "Last clef at or before " + mp + ": " +
score.getClef(mp, Interval.BeforeOrAt).getType().toString();
}
}
| true | true | @Override public void onModuleLoad() {
Score score = ScoreRevolutionary.createScore();
//String t = score.getClef(MP.atBeat(0, 1, 0, _0), Interval.BeforeOrAt).getType().toString() + " found";
//Clef clef = new Clef(ClefType.G);
//String t = clef.getType().toString();
//String t = new Point2f(5, 10).toString();
//Range r = Range.range(5);
//Label hello = new Label("Result: " + t); //"Aha "+r.getCount() + " " + Defaults.defaultFont.getSize() + " " + t);
RootPanel container = RootPanel.get("container");
container.add(new Label(findAClef(score, MP.atBeat(0, 1, 0, _0))));
container.add(new Label(findAClef(score, MP.atBeat(1, 1, 0, _0))));
MP mp = MP.atBeat(0, 1, 0, _0);
container.add(new Label("Voice at " + mp + ": " + score.getVoice(mp)));
}
| @Override public void onModuleLoad() {
Score score = ScoreRevolutionary.createScore();
//String t = score.getClef(MP.atBeat(0, 1, 0, _0), Interval.BeforeOrAt).getType().toString() + " found";
//Clef clef = new Clef(ClefType.G);
//String t = clef.getType().toString();
//String t = new Point2f(5, 10).toString();
//Range r = Range.range(5);
//Label hello = new Label("Result: " + t); //"Aha "+r.getCount() + " " + Defaults.defaultFont.getSize() + " " + t);
RootPanel container = RootPanel.get("container");
container.add(new Label("If you see some text with musical data, it works:"));
container.add(new Label(findAClef(score, MP.atBeat(0, 1, 0, _0))));
container.add(new Label(findAClef(score, MP.atBeat(1, 1, 0, _0))));
MP mp = MP.atBeat(0, 1, 0, _0);
container.add(new Label("Voice at " + mp + ": " + score.getVoice(mp)));
}
|
diff --git a/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/core/search/indexing/core/SourceModulesRequest.java b/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/core/search/indexing/core/SourceModulesRequest.java
index abfcd7d33..44b1b41c9 100644
--- a/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/core/search/indexing/core/SourceModulesRequest.java
+++ b/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/core/search/indexing/core/SourceModulesRequest.java
@@ -1,118 +1,122 @@
/*******************************************************************************
* Copyright (c) 2008 xored software, Inc.
*
* 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:
* xored software, Inc. - initial API and Implementation (Alex Panchenko)
*******************************************************************************/
package org.eclipse.dltk.core.search.indexing.core;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.dltk.core.DLTKCore;
import org.eclipse.dltk.core.IDLTKLanguageToolkit;
import org.eclipse.dltk.core.IScriptProject;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.core.environment.EnvironmentManager;
import org.eclipse.dltk.core.search.index.Index;
import org.eclipse.dltk.core.search.indexing.IProjectIndexer;
import org.eclipse.dltk.core.search.indexing.ReadWriteMonitor;
class SourceModulesRequest extends IndexRequest {
private final IScriptProject project;
private final IDLTKLanguageToolkit toolkit;
private final Set modules;
/**
* @param project
* @param modules
*/
public SourceModulesRequest(IProjectIndexer indexer,
IScriptProject project, IDLTKLanguageToolkit toolkit, Set modules) {
super(indexer);
this.project = project;
this.toolkit = toolkit;
this.modules = modules;
}
protected String getName() {
return project.getElementName();
}
protected void run() throws CoreException, IOException {
final Index index = getIndexer().getProjectIndex(project);
+ if (index == null) {
+ DLTKCore.error("Index are null for:" + this.modules);
+ return;
+ }
final IPath containerPath = project.getPath();
final List changes = checkChanges(index, modules, containerPath,
EnvironmentManager.getEnvironment(project));
if (DEBUG) {
log("changes.size=" + changes.size()); //$NON-NLS-1$
}
if (changes.isEmpty()) {
return;
}
final ReadWriteMonitor imon = index.monitor;
imon.enterWrite();
try {
for (Iterator i = changes.iterator(); !isCancelled && i.hasNext();) {
final Object change = i.next();
if (change instanceof String) {
index.remove((String) change);
} else {
getIndexer().indexSourceModule(index, toolkit,
(ISourceModule) change, containerPath);
}
}
} finally {
try {
index.save();
} catch (IOException e) {
DLTKCore.error("error saving index", e); //$NON-NLS-1$
} finally {
imon.exitWrite();
}
}
}
public boolean belongsTo(String jobFamily) {
return jobFamily.equals(project.getProject().getName());
}
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((modules == null) ? 0 : modules.hashCode());
result = prime * result + ((project == null) ? 0 : project.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
SourceModulesRequest other = (SourceModulesRequest) obj;
if (modules == null) {
if (other.modules != null)
return false;
} else if (!modules.equals(other.modules))
return false;
if (project == null) {
if (other.project != null)
return false;
} else if (!project.equals(other.project))
return false;
return true;
}
}
| true | true | protected void run() throws CoreException, IOException {
final Index index = getIndexer().getProjectIndex(project);
final IPath containerPath = project.getPath();
final List changes = checkChanges(index, modules, containerPath,
EnvironmentManager.getEnvironment(project));
if (DEBUG) {
log("changes.size=" + changes.size()); //$NON-NLS-1$
}
if (changes.isEmpty()) {
return;
}
final ReadWriteMonitor imon = index.monitor;
imon.enterWrite();
try {
for (Iterator i = changes.iterator(); !isCancelled && i.hasNext();) {
final Object change = i.next();
if (change instanceof String) {
index.remove((String) change);
} else {
getIndexer().indexSourceModule(index, toolkit,
(ISourceModule) change, containerPath);
}
}
} finally {
try {
index.save();
} catch (IOException e) {
DLTKCore.error("error saving index", e); //$NON-NLS-1$
} finally {
imon.exitWrite();
}
}
}
| protected void run() throws CoreException, IOException {
final Index index = getIndexer().getProjectIndex(project);
if (index == null) {
DLTKCore.error("Index are null for:" + this.modules);
return;
}
final IPath containerPath = project.getPath();
final List changes = checkChanges(index, modules, containerPath,
EnvironmentManager.getEnvironment(project));
if (DEBUG) {
log("changes.size=" + changes.size()); //$NON-NLS-1$
}
if (changes.isEmpty()) {
return;
}
final ReadWriteMonitor imon = index.monitor;
imon.enterWrite();
try {
for (Iterator i = changes.iterator(); !isCancelled && i.hasNext();) {
final Object change = i.next();
if (change instanceof String) {
index.remove((String) change);
} else {
getIndexer().indexSourceModule(index, toolkit,
(ISourceModule) change, containerPath);
}
}
} finally {
try {
index.save();
} catch (IOException e) {
DLTKCore.error("error saving index", e); //$NON-NLS-1$
} finally {
imon.exitWrite();
}
}
}
|
diff --git a/src/com/sun/javanet/cvsnews/cli/AbstractIssueCommand.java b/src/com/sun/javanet/cvsnews/cli/AbstractIssueCommand.java
index b18d6e0..7db23a5 100644
--- a/src/com/sun/javanet/cvsnews/cli/AbstractIssueCommand.java
+++ b/src/com/sun/javanet/cvsnews/cli/AbstractIssueCommand.java
@@ -1,124 +1,124 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
*/
package com.sun.javanet.cvsnews.cli;
import com.sun.javanet.cvsnews.Commit;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Partial {@link Command} implementation that deals with issues in the issue tracker.
*
* @author Kohsuke Kawaguchi
*/
public abstract class AbstractIssueCommand extends AbstractCommand implements Command {
/**
* Discovers links to issues.
*/
protected final Set<Issue> parseIssues(Commit commit) {
Set<Issue> issues = new HashSet<Issue>();
// Matcher m = ISSUE_MARKER.matcher(commit.log);
// while(m.find())
// issues.add(new Issue(commit.project,m.group(1)));
//
// Matcher m = ISSUE_MARKER2.matcher(commit.log);
// while(m.find())
- issues.add(new Issue(commit.project,m.group(1)));
+// issues.add(new Issue(commit.project,m.group(1)));
Matcher m = ID_MARKER.matcher(commit.log);
while(m.find())
issues.add(new Issue(m.group(1),m.group(2)));
return issues;
}
/**
* Issue in an issue tracker.
*/
public static final class Issue {
public final String projectName;
public final int number;
public Issue(String projectName, int number) {
this.projectName = projectName.toLowerCase();
this.number = number;
}
public Issue(String projectName, String number) {
this(projectName,Integer.parseInt(number));
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UpdateCommand.Issue issue = (UpdateCommand.Issue) o;
return number == issue.number && projectName.equals(issue.projectName);
}
public int hashCode() {
int result;
result = projectName.hashCode();
result = 31 * result + number;
return result;
}
public String toString() {
return projectName+'-'+number;
}
}
/**
* Look for strings like "issue #350" and "issue 350"
*/
private static final Pattern ISSUE_MARKER = Pattern.compile("\\b[Ii]ssue #?(\\d+)\\b");
/**
* Looks for the line "Issue number: #350" which is the default commit message format on java.net
*/
private static final Pattern ISSUE_MARKER2 = Pattern.compile("\\bIssue number:\\s*#?(\\d+)\\b");
/**
* Look for full ID line like "JAXB-512"
*/
private static final Pattern ID_MARKER = Pattern.compile("\\b([A-Z-]+)-(\\d+)\\b");
}
| true | true | protected final Set<Issue> parseIssues(Commit commit) {
Set<Issue> issues = new HashSet<Issue>();
// Matcher m = ISSUE_MARKER.matcher(commit.log);
// while(m.find())
// issues.add(new Issue(commit.project,m.group(1)));
//
// Matcher m = ISSUE_MARKER2.matcher(commit.log);
// while(m.find())
issues.add(new Issue(commit.project,m.group(1)));
Matcher m = ID_MARKER.matcher(commit.log);
while(m.find())
issues.add(new Issue(m.group(1),m.group(2)));
return issues;
}
| protected final Set<Issue> parseIssues(Commit commit) {
Set<Issue> issues = new HashSet<Issue>();
// Matcher m = ISSUE_MARKER.matcher(commit.log);
// while(m.find())
// issues.add(new Issue(commit.project,m.group(1)));
//
// Matcher m = ISSUE_MARKER2.matcher(commit.log);
// while(m.find())
// issues.add(new Issue(commit.project,m.group(1)));
Matcher m = ID_MARKER.matcher(commit.log);
while(m.find())
issues.add(new Issue(m.group(1),m.group(2)));
return issues;
}
|
diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java
index 63e83df93..67c9ee0a0 100644
--- a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java
+++ b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java
@@ -1,214 +1,214 @@
package org.apache.solr.cloud;
/*
* 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 java.io.File;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.io.FileUtils;
import org.apache.solr.BaseDistributedSearchTestCase;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.servlet.SolrDispatchFilter;
import org.apache.zookeeper.KeeperException;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
public abstract class AbstractDistribZkTestBase extends BaseDistributedSearchTestCase {
protected static final String DEFAULT_COLLECTION = "collection1";
private static final boolean DEBUG = false;
protected ZkTestServer zkServer;
private AtomicInteger homeCount = new AtomicInteger();
@BeforeClass
public static void beforeThisClass() throws Exception {
// Only For Manual Testing: this will force an fs based dir factory
//useFactory(null);
}
@Before
@Override
public void setUp() throws Exception {
super.setUp();
createTempDir();
String zkDir = testDir.getAbsolutePath() + File.separator
+ "zookeeper/server1/data";
zkServer = new ZkTestServer(zkDir);
zkServer.run();
System.setProperty("zkHost", zkServer.getZkAddress());
System.setProperty("enable.update.log", "true");
System.setProperty("remove.version.field", "true");
AbstractZkTestCase.buildZooKeeper(zkServer.getZkHost(), zkServer.getZkAddress(), "solrconfig.xml", "schema.xml");
// set some system properties for use by tests
System.setProperty("solr.test.sys.prop1", "propone");
System.setProperty("solr.test.sys.prop2", "proptwo");
}
@Override
protected void createServers(int numShards) throws Exception {
// give everyone there own solrhome
File controlHome = new File(new File(getSolrHome()).getParentFile(), "control" + homeCount.incrementAndGet());
FileUtils.copyDirectory(new File(getSolrHome()), controlHome);
System.setProperty("collection", "control_collection");
controlJetty = createJetty(controlHome, null, "control_shard");
System.clearProperty("collection");
controlClient = createNewSolrServer(controlJetty.getLocalPort());
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= numShards; i++) {
if (sb.length() > 0) sb.append(',');
// give everyone there own solrhome
File jettyHome = new File(new File(getSolrHome()).getParentFile(), "jetty" + homeCount.incrementAndGet());
FileUtils.copyDirectory(new File(getSolrHome()), jettyHome);
JettySolrRunner j = createJetty(jettyHome, null, "shard" + (i + 2));
jettys.add(j);
clients.add(createNewSolrServer(j.getLocalPort()));
sb.append("127.0.0.1:").append(j.getLocalPort()).append(context);
}
shards = sb.toString();
// now wait till we see the leader for each shard
for (int i = 1; i <= numShards; i++) {
ZkStateReader zkStateReader = ((SolrDispatchFilter) jettys.get(0)
.getDispatchFilter().getFilter()).getCores().getZkController()
.getZkStateReader();
zkStateReader.getLeaderProps("collection1", "shard" + (i + 2), 15000);
}
}
protected void waitForRecoveriesToFinish(String collection, ZkStateReader zkStateReader, boolean verbose)
throws Exception {
waitForRecoveriesToFinish(collection, zkStateReader, verbose, true);
}
protected void waitForRecoveriesToFinish(String collection, ZkStateReader zkStateReader, boolean verbose, boolean failOnTimeout)
throws Exception {
waitForRecoveriesToFinish(collection, zkStateReader, verbose, failOnTimeout, 600 * (TEST_NIGHTLY ? 2 : 1) * RANDOM_MULTIPLIER);
}
protected void waitForRecoveriesToFinish(String collection,
ZkStateReader zkStateReader, boolean verbose, boolean failOnTimeout, int timeoutSeconds)
throws Exception {
log.info("Wait for recoveries to finish - collection: " + collection + " failOnTimeout:" + failOnTimeout + " timeout (sec):" + timeoutSeconds);
boolean cont = true;
int cnt = 0;
while (cont) {
if (verbose) System.out.println("-");
boolean sawLiveRecovering = false;
zkStateReader.updateClusterState(true);
ClusterState clusterState = zkStateReader.getClusterState();
Map<String,Slice> slices = clusterState.getSlices(collection);
assertNotNull("Could not find collection:" + collection, slices);
for (Map.Entry<String,Slice> entry : slices.entrySet()) {
Map<String,Replica> shards = entry.getValue().getReplicasMap();
for (Map.Entry<String,Replica> shard : shards.entrySet()) {
if (verbose) System.out.println("rstate:"
+ shard.getValue().getStr(ZkStateReader.STATE_PROP)
+ " live:"
+ clusterState.liveNodesContain(shard.getValue().getStr(
ZkStateReader.NODE_NAME_PROP)));
String state = shard.getValue().getStr(ZkStateReader.STATE_PROP);
if ((state.equals(ZkStateReader.RECOVERING) || state
.equals(ZkStateReader.SYNC) || state.equals(ZkStateReader.DOWN))
&& clusterState.liveNodesContain(shard.getValue().getStr(
ZkStateReader.NODE_NAME_PROP))) {
sawLiveRecovering = true;
}
}
}
if (!sawLiveRecovering || cnt == timeoutSeconds) {
if (!sawLiveRecovering) {
if (verbose) System.out.println("no one is recoverying");
} else {
+ if (verbose) System.out
+ .println("Gave up waiting for recovery to finish..");
if (failOnTimeout) {
- fail("There are still nodes recoverying");
+ fail("There are still nodes recoverying - waited for " + timeoutSeconds + " seconds");
printLayout();
return;
}
- if (verbose) System.out
- .println("gave up waiting for recovery to finish..");
}
cont = false;
} else {
Thread.sleep(1000);
}
cnt++;
}
}
protected void assertAllActive(String collection,ZkStateReader zkStateReader)
throws KeeperException, InterruptedException {
zkStateReader.updateClusterState(true);
ClusterState clusterState = zkStateReader.getClusterState();
Map<String,Slice> slices = clusterState.getSlices(collection);
if (slices == null) {
throw new IllegalArgumentException("Cannot find collection:" + collection);
}
for (Map.Entry<String,Slice> entry : slices.entrySet()) {
Map<String,Replica> shards = entry.getValue().getReplicasMap();
for (Map.Entry<String,Replica> shard : shards.entrySet()) {
String state = shard.getValue().getStr(ZkStateReader.STATE_PROP);
if (!state.equals(ZkStateReader.ACTIVE)) {
fail("Not all shards are ACTIVE - found a shard that is: " + state);
}
}
}
}
@Override
@After
public void tearDown() throws Exception {
if (DEBUG) {
printLayout();
}
zkServer.shutdown();
System.clearProperty("zkHost");
System.clearProperty("collection");
System.clearProperty("enable.update.log");
System.clearProperty("remove.version.field");
System.clearProperty("solr.directoryFactory");
System.clearProperty("solr.test.sys.prop1");
System.clearProperty("solr.test.sys.prop2");
resetExceptionIgnores();
super.tearDown();
}
protected void printLayout() throws Exception {
SolrZkClient zkClient = new SolrZkClient(zkServer.getZkHost(), AbstractZkTestCase.TIMEOUT);
zkClient.printLayoutToStdOut();
zkClient.close();
}
}
| false | true | protected void waitForRecoveriesToFinish(String collection,
ZkStateReader zkStateReader, boolean verbose, boolean failOnTimeout, int timeoutSeconds)
throws Exception {
log.info("Wait for recoveries to finish - collection: " + collection + " failOnTimeout:" + failOnTimeout + " timeout (sec):" + timeoutSeconds);
boolean cont = true;
int cnt = 0;
while (cont) {
if (verbose) System.out.println("-");
boolean sawLiveRecovering = false;
zkStateReader.updateClusterState(true);
ClusterState clusterState = zkStateReader.getClusterState();
Map<String,Slice> slices = clusterState.getSlices(collection);
assertNotNull("Could not find collection:" + collection, slices);
for (Map.Entry<String,Slice> entry : slices.entrySet()) {
Map<String,Replica> shards = entry.getValue().getReplicasMap();
for (Map.Entry<String,Replica> shard : shards.entrySet()) {
if (verbose) System.out.println("rstate:"
+ shard.getValue().getStr(ZkStateReader.STATE_PROP)
+ " live:"
+ clusterState.liveNodesContain(shard.getValue().getStr(
ZkStateReader.NODE_NAME_PROP)));
String state = shard.getValue().getStr(ZkStateReader.STATE_PROP);
if ((state.equals(ZkStateReader.RECOVERING) || state
.equals(ZkStateReader.SYNC) || state.equals(ZkStateReader.DOWN))
&& clusterState.liveNodesContain(shard.getValue().getStr(
ZkStateReader.NODE_NAME_PROP))) {
sawLiveRecovering = true;
}
}
}
if (!sawLiveRecovering || cnt == timeoutSeconds) {
if (!sawLiveRecovering) {
if (verbose) System.out.println("no one is recoverying");
} else {
if (failOnTimeout) {
fail("There are still nodes recoverying");
printLayout();
return;
}
if (verbose) System.out
.println("gave up waiting for recovery to finish..");
}
cont = false;
} else {
Thread.sleep(1000);
}
cnt++;
}
}
| protected void waitForRecoveriesToFinish(String collection,
ZkStateReader zkStateReader, boolean verbose, boolean failOnTimeout, int timeoutSeconds)
throws Exception {
log.info("Wait for recoveries to finish - collection: " + collection + " failOnTimeout:" + failOnTimeout + " timeout (sec):" + timeoutSeconds);
boolean cont = true;
int cnt = 0;
while (cont) {
if (verbose) System.out.println("-");
boolean sawLiveRecovering = false;
zkStateReader.updateClusterState(true);
ClusterState clusterState = zkStateReader.getClusterState();
Map<String,Slice> slices = clusterState.getSlices(collection);
assertNotNull("Could not find collection:" + collection, slices);
for (Map.Entry<String,Slice> entry : slices.entrySet()) {
Map<String,Replica> shards = entry.getValue().getReplicasMap();
for (Map.Entry<String,Replica> shard : shards.entrySet()) {
if (verbose) System.out.println("rstate:"
+ shard.getValue().getStr(ZkStateReader.STATE_PROP)
+ " live:"
+ clusterState.liveNodesContain(shard.getValue().getStr(
ZkStateReader.NODE_NAME_PROP)));
String state = shard.getValue().getStr(ZkStateReader.STATE_PROP);
if ((state.equals(ZkStateReader.RECOVERING) || state
.equals(ZkStateReader.SYNC) || state.equals(ZkStateReader.DOWN))
&& clusterState.liveNodesContain(shard.getValue().getStr(
ZkStateReader.NODE_NAME_PROP))) {
sawLiveRecovering = true;
}
}
}
if (!sawLiveRecovering || cnt == timeoutSeconds) {
if (!sawLiveRecovering) {
if (verbose) System.out.println("no one is recoverying");
} else {
if (verbose) System.out
.println("Gave up waiting for recovery to finish..");
if (failOnTimeout) {
fail("There are still nodes recoverying - waited for " + timeoutSeconds + " seconds");
printLayout();
return;
}
}
cont = false;
} else {
Thread.sleep(1000);
}
cnt++;
}
}
|
diff --git a/src/java/azkaban/execapp/JobRunner.java b/src/java/azkaban/execapp/JobRunner.java
index 701cc66b..16d80a54 100644
--- a/src/java/azkaban/execapp/JobRunner.java
+++ b/src/java/azkaban/execapp/JobRunner.java
@@ -1,450 +1,451 @@
package azkaban.execapp;
/*
* Copyright 2012 LinkedIn, 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.
*/
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
import java.util.Collections;
import org.apache.log4j.Appender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import azkaban.execapp.event.BlockingStatus;
import azkaban.execapp.event.Event;
import azkaban.execapp.event.Event.Type;
import azkaban.execapp.event.EventHandler;
import azkaban.execapp.event.FlowWatcher;
import azkaban.executor.ExecutableNode;
import azkaban.executor.ExecutorLoader;
import azkaban.executor.ExecutorManagerException;
import azkaban.executor.Status;
import azkaban.flow.CommonJobProperties;
import azkaban.jobExecutor.AbstractProcessJob;
import azkaban.jobExecutor.Job;
import azkaban.jobtype.JobTypeManager;
import azkaban.jobtype.JobTypeManagerException;
import azkaban.utils.Props;
public class JobRunner extends EventHandler implements Runnable {
private static final Layout DEFAULT_LAYOUT = new PatternLayout("%d{dd-MM-yyyy HH:mm:ss z} %c{1} %p - %m\n");
private ExecutorLoader loader;
private Props props;
private Props outputProps;
private ExecutableNode node;
private File workingDir;
private Logger logger = null;
private Layout loggerLayout = DEFAULT_LAYOUT;
private Logger flowLogger = null;
private Appender jobAppender;
private File logFile;
private Job job;
private int executionId = -1;
private static final Object logCreatorLock = new Object();
private Object syncObject = new Object();
private final JobTypeManager jobtypeManager;
// Used by the job to watch and block against another flow
private Integer pipelineLevel = null;
private FlowWatcher watcher = null;
private Set<String> pipelineJobs = new HashSet<String>();
private Set<String> proxyUsers = null;
private String jobLogChunkSize;
private int jobLogBackupIndex;
private long delayStartMs = 0;
private boolean cancelled = false;
public JobRunner(ExecutableNode node, Props props, File workingDir, ExecutorLoader loader, JobTypeManager jobtypeManager) {
this.props = props;
this.node = node;
this.workingDir = workingDir;
this.executionId = node.getExecutionId();
this.loader = loader;
this.jobtypeManager = jobtypeManager;
}
public void setValidatedProxyUsers(Set<String> proxyUsers) {
this.proxyUsers = proxyUsers;
}
public void setLogSettings(Logger flowLogger, String logFileChuckSize, int numLogBackup ) {
this.flowLogger = flowLogger;
this.jobLogChunkSize = logFileChuckSize;
this.jobLogBackupIndex = numLogBackup;
}
public Props getProps() {
return props;
}
public void setPipeline(FlowWatcher watcher, int pipelineLevel) {
this.watcher = watcher;
this.pipelineLevel = pipelineLevel;
if (this.pipelineLevel == 1) {
pipelineJobs.add(node.getJobId());
}
else if (this.pipelineLevel == 2) {
pipelineJobs.add(node.getJobId());
pipelineJobs.addAll(node.getOutNodes());
}
}
public void setDelayStart(long delayMS) {
delayStartMs = delayMS;
}
public long getDelayStart() {
return delayStartMs;
}
public ExecutableNode getNode() {
return node;
}
public String getLogFilePath() {
return logFile == null ? null : logFile.getPath();
}
private void createLogger() {
// Create logger
synchronized (logCreatorLock) {
String loggerName = System.currentTimeMillis() + "." + executionId + "." + node.getJobId();
logger = Logger.getLogger(loggerName);
// Create file appender
String logName = createLogFileName(node.getExecutionId(), node.getJobId(), node.getAttempt());
logFile = new File(workingDir, logName);
String absolutePath = logFile.getAbsolutePath();
jobAppender = null;
try {
RollingFileAppender fileAppender = new RollingFileAppender(loggerLayout, absolutePath, true);
fileAppender.setMaxBackupIndex(jobLogBackupIndex);
fileAppender.setMaxFileSize(jobLogChunkSize);
jobAppender = fileAppender;
logger.addAppender(jobAppender);
} catch (IOException e) {
flowLogger.error("Could not open log file in " + workingDir + " for job " + node.getJobId(), e);
}
}
}
private void closeLogger() {
if (jobAppender != null) {
logger.removeAppender(jobAppender);
jobAppender.close();
}
}
private void writeStatus() {
try {
node.setUpdateTime(System.currentTimeMillis());
loader.updateExecutableNode(node);
} catch (ExecutorManagerException e) {
flowLogger.error("Could not update job properties in db for " + node.getJobId(), e);
}
}
@Override
public void run() {
Thread.currentThread().setName("JobRunner-" + node.getJobId() + "-" + executionId);
if (node.getStatus() == Status.DISABLED) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setStatus(Status.SKIPPED);
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
} else if (this.cancelled) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setStatus(Status.FAILED);
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
} else if (node.getStatus() == Status.FAILED || node.getStatus() == Status.KILLED) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
else {
createLogger();
node.setUpdateTime(System.currentTimeMillis());
// For pipelining of jobs. Will watch other jobs.
if (!pipelineJobs.isEmpty()) {
String blockedList = "";
ArrayList<BlockingStatus> blockingStatus = new ArrayList<BlockingStatus>();
for (String waitingJobId : pipelineJobs) {
Status status = watcher.peekStatus(waitingJobId);
if (status != null && !Status.isStatusFinished(status)) {
BlockingStatus block = watcher.getBlockingStatus(waitingJobId);
blockingStatus.add(block);
blockedList += waitingJobId + ",";
}
}
if (!blockingStatus.isEmpty()) {
logger.info("Pipeline job " + node.getJobId() + " waiting on " + blockedList + " in execution " + watcher.getExecId());
for(BlockingStatus bStatus: blockingStatus) {
logger.info("Waiting on pipelined job " + bStatus.getJobId());
bStatus.blockOnFinishedStatus();
logger.info("Pipelined job " + bStatus.getJobId() + " finished.");
}
}
if (watcher.isWatchCancelled()) {
logger.info("Job was cancelled while waiting on pipeline. Quiting.");
node.setStartTime(System.currentTimeMillis());
node.setEndTime(System.currentTimeMillis());
+ node.setStatus(Status.FAILED);
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
}
long currentTime = System.currentTimeMillis();
if (delayStartMs > 0) {
logger.info("Delaying start of execution for " + delayStartMs + " milliseconds.");
synchronized(this) {
try {
this.wait(delayStartMs);
logger.info("Execution has been delayed for " + delayStartMs + " ms. Continuing with execution.");
} catch (InterruptedException e) {
logger.error("Job " + node.getJobId() + " was to be delayed for " + delayStartMs + ". Interrupted after " + (System.currentTimeMillis() - currentTime));
}
}
if (cancelled) {
logger.info("Job was cancelled while in delay. Quiting.");
node.setStartTime(System.currentTimeMillis());
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
}
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
try {
loader.uploadExecutableNode(node, props);
} catch (ExecutorManagerException e1) {
logger.error("Error writing initial node properties");
}
if (prepareJob()) {
writeStatus();
fireEvent(Event.create(this, Type.JOB_STATUS_CHANGED), false);
runJob();
}
else {
node.setStatus(Status.FAILED);
logError("Job run failed!");
}
node.setEndTime(System.currentTimeMillis());
logInfo("Finishing job " + node.getJobId() + " at " + node.getEndTime());
closeLogger();
writeStatus();
if (logFile != null) {
try {
File[] files = logFile.getParentFile().listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(logFile.getName());
}
}
);
Arrays.sort(files, Collections.reverseOrder());
loader.uploadLogFile(executionId, node.getJobId(), node.getAttempt(), files);
} catch (ExecutorManagerException e) {
flowLogger.error("Error writing out logs for job " + node.getJobId(), e);
}
}
else {
flowLogger.info("Log file for job " + node.getJobId() + " is null");
}
}
fireEvent(Event.create(this, Type.JOB_FINISHED));
}
private void fireEvent(Event event) {
fireEvent(event, true);
}
private void fireEvent(Event event, boolean updateTime) {
if (updateTime) {
node.setUpdateTime(System.currentTimeMillis());
}
this.fireEventListeners(event);
}
private boolean prepareJob() throws RuntimeException {
// Check pre conditions
if (props == null || cancelled) {
logError("Failing job. The job properties don't exist");
return false;
}
synchronized(syncObject) {
if (node.getStatus() == Status.FAILED || cancelled) {
return false;
}
if (node.getAttempt() > 0) {
logInfo("Starting job " + node.getJobId() + " attempt " + node.getAttempt() + " at " + node.getStartTime());
}
else {
logInfo("Starting job " + node.getJobId() + " at " + node.getStartTime());
}
props.put(CommonJobProperties.JOB_ATTEMPT, node.getAttempt());
node.setStatus(Status.RUNNING);
// Ability to specify working directory
if (!props.containsKey(AbstractProcessJob.WORKING_DIR)) {
props.put(AbstractProcessJob.WORKING_DIR, workingDir.getAbsolutePath());
}
if(props.containsKey("user.to.proxy")) {
String jobProxyUser = props.getString("user.to.proxy");
if(proxyUsers != null && !proxyUsers.contains(jobProxyUser)) {
logger.error("User " + jobProxyUser + " has no permission to execute this job " + node.getJobId() + "!");
return false;
}
}
//job = JobWrappingFactory.getJobWrappingFactory().buildJobExecutor(node.getJobId(), props, logger);
try {
job = jobtypeManager.buildJobExecutor(node.getJobId(), props, logger);
}
catch (JobTypeManagerException e) {
logger.error("Failed to build job type, skipping this job");
return false;
}
}
return true;
}
private void runJob() {
try {
job.run();
} catch (Exception e) {
e.printStackTrace();
node.setStatus(Status.FAILED);
logError("Job run failed!");
logError(e.getMessage() + e.getCause());
return;
}
node.setStatus(Status.SUCCEEDED);
if (job != null) {
outputProps = job.getJobGeneratedProperties();
node.setOutputProps(outputProps);
}
}
public void cancel() {
synchronized (syncObject) {
logError("Cancel has been called.");
this.cancelled = true;
// Cancel code here
if (job == null) {
logError("Job hasn't started yet.");
// Just in case we're waiting on the delay
synchronized(this) {
this.notify();
}
return;
}
try {
job.cancel();
} catch (Exception e) {
logError(e.getMessage());
logError("Failed trying to cancel job. Maybe it hasn't started running yet or just finished.");
}
}
}
public boolean isCancelled() {
return cancelled;
}
public Status getStatus() {
return node.getStatus();
}
public Props getOutputProps() {
return outputProps;
}
private void logError(String message) {
if (logger != null) {
logger.error(message);
}
}
private void logInfo(String message) {
if (logger != null) {
logger.info(message);
}
}
public File getLogFile() {
return logFile;
}
public int getRetries() {
return props.getInt("retries", 0);
}
public long getRetryBackoff() {
return props.getLong("retry.backoff", 0);
}
public static String createLogFileName(int executionId, String jobId, int attempt) {
return attempt > 0 ? "_job." + executionId + "." + attempt + "." + jobId + ".log" : "_job." + executionId + "." + jobId + ".log";
}
}
| true | true | public void run() {
Thread.currentThread().setName("JobRunner-" + node.getJobId() + "-" + executionId);
if (node.getStatus() == Status.DISABLED) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setStatus(Status.SKIPPED);
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
} else if (this.cancelled) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setStatus(Status.FAILED);
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
} else if (node.getStatus() == Status.FAILED || node.getStatus() == Status.KILLED) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
else {
createLogger();
node.setUpdateTime(System.currentTimeMillis());
// For pipelining of jobs. Will watch other jobs.
if (!pipelineJobs.isEmpty()) {
String blockedList = "";
ArrayList<BlockingStatus> blockingStatus = new ArrayList<BlockingStatus>();
for (String waitingJobId : pipelineJobs) {
Status status = watcher.peekStatus(waitingJobId);
if (status != null && !Status.isStatusFinished(status)) {
BlockingStatus block = watcher.getBlockingStatus(waitingJobId);
blockingStatus.add(block);
blockedList += waitingJobId + ",";
}
}
if (!blockingStatus.isEmpty()) {
logger.info("Pipeline job " + node.getJobId() + " waiting on " + blockedList + " in execution " + watcher.getExecId());
for(BlockingStatus bStatus: blockingStatus) {
logger.info("Waiting on pipelined job " + bStatus.getJobId());
bStatus.blockOnFinishedStatus();
logger.info("Pipelined job " + bStatus.getJobId() + " finished.");
}
}
if (watcher.isWatchCancelled()) {
logger.info("Job was cancelled while waiting on pipeline. Quiting.");
node.setStartTime(System.currentTimeMillis());
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
}
long currentTime = System.currentTimeMillis();
if (delayStartMs > 0) {
logger.info("Delaying start of execution for " + delayStartMs + " milliseconds.");
synchronized(this) {
try {
this.wait(delayStartMs);
logger.info("Execution has been delayed for " + delayStartMs + " ms. Continuing with execution.");
} catch (InterruptedException e) {
logger.error("Job " + node.getJobId() + " was to be delayed for " + delayStartMs + ". Interrupted after " + (System.currentTimeMillis() - currentTime));
}
}
if (cancelled) {
logger.info("Job was cancelled while in delay. Quiting.");
node.setStartTime(System.currentTimeMillis());
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
}
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
try {
loader.uploadExecutableNode(node, props);
} catch (ExecutorManagerException e1) {
logger.error("Error writing initial node properties");
}
if (prepareJob()) {
writeStatus();
fireEvent(Event.create(this, Type.JOB_STATUS_CHANGED), false);
runJob();
}
else {
node.setStatus(Status.FAILED);
logError("Job run failed!");
}
node.setEndTime(System.currentTimeMillis());
logInfo("Finishing job " + node.getJobId() + " at " + node.getEndTime());
closeLogger();
writeStatus();
if (logFile != null) {
try {
File[] files = logFile.getParentFile().listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(logFile.getName());
}
}
);
Arrays.sort(files, Collections.reverseOrder());
loader.uploadLogFile(executionId, node.getJobId(), node.getAttempt(), files);
} catch (ExecutorManagerException e) {
flowLogger.error("Error writing out logs for job " + node.getJobId(), e);
}
}
else {
flowLogger.info("Log file for job " + node.getJobId() + " is null");
}
}
fireEvent(Event.create(this, Type.JOB_FINISHED));
}
| public void run() {
Thread.currentThread().setName("JobRunner-" + node.getJobId() + "-" + executionId);
if (node.getStatus() == Status.DISABLED) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setStatus(Status.SKIPPED);
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
} else if (this.cancelled) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setStatus(Status.FAILED);
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
} else if (node.getStatus() == Status.FAILED || node.getStatus() == Status.KILLED) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
else {
createLogger();
node.setUpdateTime(System.currentTimeMillis());
// For pipelining of jobs. Will watch other jobs.
if (!pipelineJobs.isEmpty()) {
String blockedList = "";
ArrayList<BlockingStatus> blockingStatus = new ArrayList<BlockingStatus>();
for (String waitingJobId : pipelineJobs) {
Status status = watcher.peekStatus(waitingJobId);
if (status != null && !Status.isStatusFinished(status)) {
BlockingStatus block = watcher.getBlockingStatus(waitingJobId);
blockingStatus.add(block);
blockedList += waitingJobId + ",";
}
}
if (!blockingStatus.isEmpty()) {
logger.info("Pipeline job " + node.getJobId() + " waiting on " + blockedList + " in execution " + watcher.getExecId());
for(BlockingStatus bStatus: blockingStatus) {
logger.info("Waiting on pipelined job " + bStatus.getJobId());
bStatus.blockOnFinishedStatus();
logger.info("Pipelined job " + bStatus.getJobId() + " finished.");
}
}
if (watcher.isWatchCancelled()) {
logger.info("Job was cancelled while waiting on pipeline. Quiting.");
node.setStartTime(System.currentTimeMillis());
node.setEndTime(System.currentTimeMillis());
node.setStatus(Status.FAILED);
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
}
long currentTime = System.currentTimeMillis();
if (delayStartMs > 0) {
logger.info("Delaying start of execution for " + delayStartMs + " milliseconds.");
synchronized(this) {
try {
this.wait(delayStartMs);
logger.info("Execution has been delayed for " + delayStartMs + " ms. Continuing with execution.");
} catch (InterruptedException e) {
logger.error("Job " + node.getJobId() + " was to be delayed for " + delayStartMs + ". Interrupted after " + (System.currentTimeMillis() - currentTime));
}
}
if (cancelled) {
logger.info("Job was cancelled while in delay. Quiting.");
node.setStartTime(System.currentTimeMillis());
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
}
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
try {
loader.uploadExecutableNode(node, props);
} catch (ExecutorManagerException e1) {
logger.error("Error writing initial node properties");
}
if (prepareJob()) {
writeStatus();
fireEvent(Event.create(this, Type.JOB_STATUS_CHANGED), false);
runJob();
}
else {
node.setStatus(Status.FAILED);
logError("Job run failed!");
}
node.setEndTime(System.currentTimeMillis());
logInfo("Finishing job " + node.getJobId() + " at " + node.getEndTime());
closeLogger();
writeStatus();
if (logFile != null) {
try {
File[] files = logFile.getParentFile().listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(logFile.getName());
}
}
);
Arrays.sort(files, Collections.reverseOrder());
loader.uploadLogFile(executionId, node.getJobId(), node.getAttempt(), files);
} catch (ExecutorManagerException e) {
flowLogger.error("Error writing out logs for job " + node.getJobId(), e);
}
}
else {
flowLogger.info("Log file for job " + node.getJobId() + " is null");
}
}
fireEvent(Event.create(this, Type.JOB_FINISHED));
}
|
diff --git a/src/com/jidesoft/swing/JideScrollPaneLayout.java b/src/com/jidesoft/swing/JideScrollPaneLayout.java
index 5aab5d37..36c23f28 100644
--- a/src/com/jidesoft/swing/JideScrollPaneLayout.java
+++ b/src/com/jidesoft/swing/JideScrollPaneLayout.java
@@ -1,1007 +1,1007 @@
/*
* @(#)${NAME}.java
*
* Copyright 2002 - 2005 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.swing;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
/**
* The layout manager used by <code>JideScrollPane</code>.
* <code>JideScrollPaneLayout</code> is
* responsible for eleven components: a viewport, two scrollbars,
* a row header, a column header, a row footer, a column footer, and four "corner" components.
*/
class JideScrollPaneLayout extends ScrollPaneLayout implements JideScrollPaneConstants {
/**
* The row footer child. Default is <code>null</code>.
*
* @see JideScrollPane#setRowFooter
*/
protected JViewport _rowFoot;
/**
* The column footer child. Default is <code>null</code>.
*
* @see JideScrollPane#setColumnFooter
*/
protected JViewport _colFoot;
/**
* The component to the left of horizontal scroll bar.
*/
protected Component _hLeft;
/**
* The component to the right of horizontal scroll bar.
*/
protected Component _hRight;
/**
* The component to the top of vertical scroll bar.
*/
protected Component _vTop;
/**
* The component to the bottom of vertical scroll bar.
*/
protected Component _vBottom;
public void syncWithScrollPane(JScrollPane sp) {
super.syncWithScrollPane(sp);
if (sp instanceof JideScrollPane) {
_rowFoot = ((JideScrollPane) sp).getRowFooter();
_colFoot = ((JideScrollPane) sp).getColumnFooter();
_hLeft = ((JideScrollPane) sp).getScrollBarCorner(HORIZONTAL_LEFT);
_hRight = ((JideScrollPane) sp).getScrollBarCorner(HORIZONTAL_RIGHT);
_vTop = ((JideScrollPane) sp).getScrollBarCorner(VERTICAL_TOP);
_vBottom = ((JideScrollPane) sp).getScrollBarCorner(VERTICAL_BOTTOM);
}
}
protected boolean isHsbCoversWholeWidth(JScrollPane sp) {
if (sp instanceof JideScrollPane) {
return ((JideScrollPane) sp).isHorizontalScrollBarCoversWholeWidth();
}
else {
return false;
}
}
protected boolean isVsbCoversWholeHeight(JScrollPane sp) {
if (sp instanceof JideScrollPane) {
return ((JideScrollPane) sp).isVerticalScrollBarCoversWholeHeight();
}
else {
return false;
}
}
public void addLayoutComponent(String s, Component c) {
if (s.equals(ROW_FOOTER)) {
_rowFoot = (JViewport) addSingletonComponent(_rowFoot, c);
}
else if (s.equals(COLUMN_FOOTER)) {
_colFoot = (JViewport) addSingletonComponent(_colFoot, c);
}
else if (s.equals(HORIZONTAL_LEFT)) {
_hLeft = addSingletonComponent(_hLeft, c);
}
else if (s.equals(HORIZONTAL_RIGHT)) {
_hRight = addSingletonComponent(_hRight, c);
}
else if (s.equals(VERTICAL_TOP)) {
_vTop = addSingletonComponent(_vTop, c);
}
else if (s.equals(VERTICAL_BOTTOM)) {
_vBottom = addSingletonComponent(_vBottom, c);
}
else {
super.addLayoutComponent(s, c);
}
}
public void removeLayoutComponent(Component c) {
if (c == _rowFoot) {
_rowFoot = null;
}
else if (c == _colFoot) {
_colFoot = null;
}
else if (c == _hLeft) {
_hLeft = null;
}
else if (c == _hRight) {
_hRight = null;
}
else if (c == _vTop) {
_vTop = null;
}
else if (c == _vBottom) {
_vBottom = null;
}
else {
super.removeLayoutComponent(c);
}
}
/**
* Returns the <code>JViewport</code> object that is the row footer.
*
* @return the <code>JViewport</code> object that is the row footer
* @see JideScrollPane#getRowFooter
*/
public JViewport getRowFooter() {
return _rowFoot;
}
/**
* Returns the <code>JViewport</code> object that is the column footer.
*
* @return the <code>JViewport</code> object that is the column footer
* @see JideScrollPane#getColumnFooter
*/
public JViewport getColumnFooter() {
return _colFoot;
}
/**
* Returns the <code>Component</code> at the specified corner.
*
* @param key the <code>String</code> specifying the corner
* @return the <code>Component</code> at the specified corner, as defined in
* {@link ScrollPaneConstants}; if <code>key</code> is not one of the
* four corners, <code>null</code> is returned
* @see JScrollPane#getCorner
*/
public Component getScrollBarCorner(String key) {
if (key.equals(HORIZONTAL_LEFT)) {
return _hLeft;
}
else if (key.equals(HORIZONTAL_RIGHT)) {
return _hRight;
}
else if (key.equals(VERTICAL_BOTTOM)) {
return _vBottom;
}
else if (key.equals(VERTICAL_TOP)) {
return _vTop;
}
else {
return super.getCorner(key);
}
}
/**
* The preferred size of a <code>ScrollPane</code> is the size of the insets,
* plus the preferred size of the viewport, plus the preferred size of
* the visible headers, plus the preferred size of the scrollbars
* that will appear given the current view and the current
* scrollbar displayPolicies.
* <p>Note that the rowHeader is calculated as part of the preferred width
* and the colHeader is calculated as part of the preferred size.
*
* @param parent the <code>Container</code> that will be laid out
* @return a <code>Dimension</code> object specifying the preferred size of the
* viewport and any scrollbars
* @see ViewportLayout
* @see LayoutManager
*/
public Dimension preferredLayoutSize(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane) parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Insets insets = parent.getInsets();
int prefWidth = insets.left + insets.right;
int prefHeight = insets.top + insets.bottom;
/* Note that viewport.getViewSize() is equivalent to
* viewport.getView().getPreferredSize() modulo a null
* view or a view whose size was explicitly set.
*/
Dimension extentSize = null;
Dimension viewSize = null;
Component view = null;
if (viewport != null) {
extentSize = viewport.getPreferredSize();
viewSize = viewport.getViewSize();
view = viewport.getView();
}
/* If there's a viewport add its preferredSize.
*/
if (extentSize != null) {
prefWidth += extentSize.width;
prefHeight += extentSize.height;
}
/* If there's a JScrollPane.viewportBorder, add its insets.
*/
Border viewportBorder = scrollPane.getViewportBorder();
if (viewportBorder != null) {
Insets vpbInsets = viewportBorder.getBorderInsets(parent);
prefWidth += vpbInsets.left + vpbInsets.right;
prefHeight += vpbInsets.top + vpbInsets.bottom;
}
/* If a header exists and it's visible, factor its
* preferred size in.
*/
int rowHeaderWidth = 0;
if (rowHead != null && rowHead.isVisible()) {
rowHeaderWidth = rowHead.getPreferredSize().width;
}
if (upperLeft != null && upperLeft.isVisible()) {
rowHeaderWidth = Math.max(rowHeaderWidth, upperLeft.getPreferredSize().width);
}
if (lowerLeft != null && lowerLeft.isVisible()) {
rowHeaderWidth = Math.max(rowHeaderWidth, lowerLeft.getPreferredSize().width);
}
prefWidth += rowHeaderWidth;
int upperHeight = getUpperHeight();
prefHeight += upperHeight;
if ((_rowFoot != null) && _rowFoot.isVisible()) {
prefWidth += _rowFoot.getPreferredSize().width;
}
int lowerHeight = getLowerHeight();
prefHeight += lowerHeight;
/* If a scrollbar is going to appear, factor its preferred size in.
* If the scrollbars policy is AS_NEEDED, this can be a little
* tricky:
*
* - If the view is a Scrollable then scrollableTracksViewportWidth
* and scrollableTracksViewportHeight can be used to effectively
* disable scrolling (if they're true) in their respective dimensions.
*
* - Assuming that a scrollbar hasn't been disabled by the
* previous constraint, we need to decide if the scrollbar is going
* to appear to correctly compute the JScrollPanes preferred size.
* To do this we compare the preferredSize of the viewport (the
* extentSize) to the preferredSize of the view. Although we're
* not responsible for laying out the view we'll assume that the
* JViewport will always give it its preferredSize.
*/
if ((vsb != null) && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
prefWidth += vsb.getPreferredSize().width;
}
else if ((viewSize != null) && (extentSize != null)) {
boolean canScroll = true;
if (view instanceof Scrollable) {
canScroll = !((Scrollable) view).getScrollableTracksViewportHeight();
}
if (canScroll && (viewSize.height > extentSize.height)) {
prefWidth += vsb.getPreferredSize().width;
}
}
}
if ((hsb != null) && (hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER)) {
if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
prefHeight += hsb.getPreferredSize().height;
}
else if ((viewSize != null) && (extentSize != null)) {
boolean canScroll = true;
if (view instanceof Scrollable) {
canScroll = !((Scrollable) view).getScrollableTracksViewportWidth();
}
if (canScroll && (viewSize.width > extentSize.width)) {
prefHeight += hsb.getPreferredSize().height;
}
}
}
return new Dimension(prefWidth, prefHeight);
}
private int getUpperHeight() {
int upperHeight = 0;
if ((upperLeft != null) && upperLeft.isVisible()) {
upperHeight = upperLeft.getPreferredSize().height;
}
if ((upperRight != null) && upperRight.isVisible()) {
upperHeight = Math.max(upperRight.getPreferredSize().height, upperHeight);
}
if ((colHead != null) && colHead.isVisible()) {
upperHeight = Math.max(colHead.getPreferredSize().height, upperHeight);
}
return upperHeight;
}
private int getLowerHeight() {
int lowerHeight = 0;
if ((lowerLeft != null) && lowerLeft.isVisible()) {
lowerHeight = lowerLeft.getPreferredSize().height;
}
if ((lowerRight != null) && lowerRight.isVisible()) {
lowerHeight = Math.max(lowerRight.getPreferredSize().height, lowerHeight);
}
if ((_colFoot != null) && _colFoot.isVisible()) {
lowerHeight = Math.max(_colFoot.getPreferredSize().height, lowerHeight);
}
return lowerHeight;
}
/**
* The minimum size of a <code>ScrollPane</code> is the size of the insets
* plus minimum size of the viewport, plus the scrollpane's
* viewportBorder insets, plus the minimum size
* of the visible headers, plus the minimum size of the
* scrollbars whose displayPolicy isn't NEVER.
*
* @param parent the <code>Container</code> that will be laid out
* @return a <code>Dimension</code> object specifying the minimum size
*/
public Dimension minimumLayoutSize(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane) parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Insets insets = parent.getInsets();
int minWidth = insets.left + insets.right;
int minHeight = insets.top + insets.bottom;
/* If there's a viewport add its minimumSize.
*/
if (viewport != null) {
Dimension size = viewport.getMinimumSize();
minWidth += size.width;
minHeight += size.height;
}
/* If there's a JScrollPane.viewportBorder, add its insets.
*/
Border viewportBorder = scrollPane.getViewportBorder();
if (viewportBorder != null) {
Insets vpbInsets = viewportBorder.getBorderInsets(parent);
minWidth += vpbInsets.left + vpbInsets.right;
minHeight += vpbInsets.top + vpbInsets.bottom;
}
/* If a header exists and it's visible, factor its
* minimum size in.
*/
int rowHeaderWidth = 0;
if (rowHead != null && rowHead.isVisible()) {
Dimension size = rowHead.getMinimumSize();
rowHeaderWidth = size.width;
minHeight = Math.max(minHeight, size.height);
}
if (upperLeft != null && upperLeft.isVisible()) {
rowHeaderWidth = Math.max(rowHeaderWidth, upperLeft.getMinimumSize().width);
}
if (lowerLeft != null && lowerLeft.isVisible()) {
rowHeaderWidth = Math.max(rowHeaderWidth, lowerLeft.getMinimumSize().width);
}
minWidth += rowHeaderWidth;
int upperHeight = 0;
if ((upperLeft != null) && upperLeft.isVisible()) {
upperHeight = upperLeft.getMinimumSize().height;
}
if ((upperRight != null) && upperRight.isVisible()) {
upperHeight = Math.max(upperRight.getMinimumSize().height, upperHeight);
}
if ((colHead != null) && colHead.isVisible()) {
Dimension size = colHead.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
upperHeight = Math.max(size.height, upperHeight);
}
minHeight += upperHeight;
// JIDE: added for JideScrollPaneLayout
int lowerHeight = 0;
if ((lowerLeft != null) && lowerLeft.isVisible()) {
lowerHeight = lowerLeft.getMinimumSize().height;
}
if ((lowerRight != null) && lowerRight.isVisible()) {
lowerHeight = Math.max(lowerRight.getMinimumSize().height, lowerHeight);
}
if ((_colFoot != null) && _colFoot.isVisible()) {
Dimension size = _colFoot.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
lowerHeight = Math.max(size.height, lowerHeight);
}
minHeight += lowerHeight;
if ((_rowFoot != null) && _rowFoot.isVisible()) {
Dimension size = _rowFoot.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
minHeight += size.height;
}
// JIDE: End of added for JideScrollPaneLayout
/* If a scrollbar might appear, factor its minimum
* size in.
*/
if ((vsb != null) && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
Dimension size = vsb.getMinimumSize();
minWidth += size.width;
minHeight = Math.max(minHeight, size.height);
}
if ((hsb != null) && (hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER)) {
Dimension size = hsb.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
minHeight += size.height;
}
return new Dimension(minWidth, minHeight);
}
/**
* Lays out the scrollpane. The positioning of components depends on
* the following constraints:
* <ul>
* <li> The row header, if present and visible, gets its preferred
* width and the viewport's height.
* <p/>
* <li> The column header, if present and visible, gets its preferred
* height and the viewport's width.
* <p/>
* <li> If a vertical scrollbar is needed, i.e. if the viewport's extent
* height is smaller than its view height or if the <code>displayPolicy</code>
* is ALWAYS, it's treated like the row header with respect to its
* dimensions and is made visible.
* <p/>
* <li> If a horizontal scrollbar is needed, it is treated like the
* column header (see the paragraph above regarding the vertical scrollbar).
* <p/>
* <li> If the scrollpane has a non-<code>null</code>
* <code>viewportBorder</code>, then space is allocated for that.
* <p/>
* <li> The viewport gets the space available after accounting for
* the previous constraints.
* <p/>
* <li> The corner components, if provided, are aligned with the
* ends of the scrollbars and headers. If there is a vertical
* scrollbar, the right corners appear; if there is a horizontal
* scrollbar, the lower corners appear; a row header gets left
* corners, and a column header gets upper corners.
* </ul>
*
* @param parent the <code>Container</code> to lay out
*/
public void layoutContainer(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane) parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Rectangle availR = scrollPane.getBounds();
availR.x = availR.y = 0;
Insets insets = parent.getInsets();
availR.x = insets.left;
availR.y = insets.top;
availR.width -= insets.left + insets.right;
availR.height -= insets.top + insets.bottom;
/* Get the scrollPane's orientation.
*/
boolean leftToRight = scrollPane.getComponentOrientation().isLeftToRight();
/* If there's a visible column header remove the space it
* needs from the top of availR. The column header is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0);
int upperHeight = getUpperHeight();
if ((colHead != null) && (colHead.isVisible())) {
int colHeadHeight = Math.min(availR.height,
upperHeight);
colHeadR.height = colHeadHeight;
availR.y += colHeadHeight;
availR.height -= colHeadHeight;
}
/* If there's a visible row header remove the space it needs
* from the left or right of availR. The row header is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowHeadR = new Rectangle(0, 0, 0, 0);
if ((rowHead != null) && (rowHead.isVisible())) {
int rowHeadWidth = rowHead.getPreferredSize().width;
if (upperLeft != null && upperLeft.isVisible()) {
rowHeadWidth = Math.max(rowHeadWidth, upperLeft.getPreferredSize().width);
}
if (lowerLeft != null && lowerLeft.isVisible()) {
rowHeadWidth = Math.max(rowHeadWidth, lowerLeft.getPreferredSize().width);
}
rowHeadWidth = Math.min(availR.width, rowHeadWidth);
rowHeadR.width = rowHeadWidth;
availR.width -= rowHeadWidth;
if (leftToRight) {
rowHeadR.x = availR.x;
availR.x += rowHeadWidth;
}
else {
rowHeadR.x = availR.x + availR.width;
}
}
/* If there's a JScrollPane.viewportBorder, remove the
* space it occupies for availR.
*/
Border viewportBorder = scrollPane.getViewportBorder();
Insets vpbInsets;
if (viewportBorder != null) {
vpbInsets = viewportBorder.getBorderInsets(parent);
availR.x += vpbInsets.left;
availR.y += vpbInsets.top;
availR.width -= vpbInsets.left + vpbInsets.right;
availR.height -= vpbInsets.top + vpbInsets.bottom;
}
else {
vpbInsets = new Insets(0, 0, 0, 0);
}
/* If there's a visible row footer remove the space it needs
* from the left or right of availR. The row footer is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowFootR = new Rectangle(0, 0, 0, 0);
if ((_rowFoot != null) && (_rowFoot.isVisible())) {
int rowFootWidth = Math.min(availR.width,
_rowFoot.getPreferredSize().width);
rowFootR.width = rowFootWidth;
availR.width -= rowFootWidth;
if (leftToRight) {
rowFootR.x = availR.x + availR.width;
}
else {
rowFootR.x = availR.x;
availR.x += rowFootWidth;
}
}
/* If there's a visible column footer remove the space it
* needs from the top of availR. The column footer is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colFootR = new Rectangle(0, availR.y, 0, 0);
int lowerHeight = getLowerHeight();
if ((_colFoot != null) && (_colFoot.isVisible())) {
int colFootHeight = Math.min(availR.height,
lowerHeight);
colFootR.height = colFootHeight;
availR.height -= colFootHeight;
colFootR.y = availR.y + availR.height;
}
/* At this point availR is the space available for the viewport
* and scrollbars. rowHeadR is correct except for its height and y
* and colHeadR is correct except for its width and x. Once we're
* through computing the dimensions of these three parts we can
* go back and set the dimensions of rowHeadR.height, rowHeadR.y,
* colHeadR.width, colHeadR.x and the bounds for the corners.
*
* We'll decide about putting up scrollbars by comparing the
* viewport views preferred size with the viewports extent
* size (generally just its size). Using the preferredSize is
* reasonable because layout proceeds top down - so we expect
* the viewport to be laid out next. And we assume that the
* viewports layout manager will give the view it's preferred
* size. One exception to this is when the view implements
* Scrollable and Scrollable.getViewTracksViewport{Width,Height}
* methods return true. If the view is tracking the viewports
* width we don't bother with a horizontal scrollbar, similarly
* if view.getViewTracksViewport(Height) is true we don't bother
* with a vertical scrollbar.
*/
Component view = (viewport != null) ? viewport.getView() : null;
Dimension viewPrefSize = (view != null) ? view.getPreferredSize() : new Dimension(0, 0);
Dimension extentSize =
(viewport != null) ? viewport.toViewCoordinates(availR.getSize())
: new Dimension(0, 0);
boolean viewTracksViewportWidth = false;
boolean viewTracksViewportHeight = false;
boolean isEmpty = (availR.width < 0 || availR.height < 0);
Scrollable sv;
// Don't bother checking the Scrollable methods if there is no room
// for the viewport, we aren't going to show any scrollbars in this
// case anyway.
if (!isEmpty && view instanceof Scrollable) {
sv = (Scrollable) view;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
}
else {
sv = null;
}
/* If there's a vertical scrollbar and we need one, allocate
* space for it (we'll make it visible later). A vertical
* scrollbar is considered to be fixed width, arbitrary height.
*/
Rectangle vsbR = new Rectangle(0, isVsbCoversWholeHeight(scrollPane) ? -vpbInsets.top : availR.y - vpbInsets.top, 0, 0);
boolean vsbNeeded;
if (isEmpty) {
vsbNeeded = false;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
vsbNeeded = true;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_NEVER) {
vsbNeeded = false;
}
else { // vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED
- vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || rowHead.getView().getPreferredSize().height > extentSize.height);
+ vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView().getPreferredSize().height > extentSize.height));
}
if ((vsb != null) && vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight);
extentSize = viewport.toViewCoordinates(availR.getSize());
}
/* If there's a horizontal scrollbar and we need one, allocate
* space for it (we'll make it visible later). A horizontal
* scrollbar is considered to be fixed height, arbitrary width.
*/
Rectangle hsbR = new Rectangle(isHsbCoversWholeWidth(scrollPane) ? -vpbInsets.left : availR.x - vpbInsets.left, 0, 0, 0);
boolean hsbNeeded;
if (isEmpty) {
hsbNeeded = false;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
hsbNeeded = true;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_NEVER) {
hsbNeeded = false;
}
else { // hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED
- hsbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || colHead.getView().getPreferredSize().width > extentSize.width);
+ hsbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView().getPreferredSize().width > extentSize.width));
}
if ((hsb != null) && hsbNeeded) {
adjustForHSB(true, availR, hsbR, vpbInsets);
/* If we added the horizontal scrollbar then we've implicitly
* reduced the vertical space available to the viewport.
* As a consequence we may have to add the vertical scrollbar,
* if that hasn't been done so already. Of course we
* don't bother with any of this if the vsbPolicy is NEVER.
*/
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates(availR.getSize());
vsbNeeded = viewPrefSize.height > extentSize.height;
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight);
}
}
}
/* Set the size of the viewport first, and then recheck the Scrollable
* methods. Some components base their return values for the Scrollable
* methods on the size of the Viewport, so that if we don't
* ask after resetting the bounds we may have gotten the wrong
* answer.
*/
if (viewport != null) {
viewport.setBounds(availR);
if (sv != null) {
extentSize = viewport.toViewCoordinates(availR.getSize());
boolean oldHSBNeeded = hsbNeeded;
boolean oldVSBNeeded = vsbNeeded;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) {
- boolean newVSBNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || rowHead.getView().getPreferredSize().height > extentSize.height);
+ boolean newVSBNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView().getPreferredSize().height > extentSize.height));
if (newVSBNeeded != vsbNeeded) {
vsbNeeded = newVSBNeeded;
adjustForVSB(vsbNeeded, availR, vsbR, vpbInsets,
leftToRight);
extentSize = viewport.toViewCoordinates
(availR.getSize());
}
}
if (hsb != null && hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) {
- boolean newHSBbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || colHead.getView().getPreferredSize().width > extentSize.width);
+ boolean newHSBbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView().getPreferredSize().width > extentSize.width));
if (newHSBbNeeded != hsbNeeded) {
hsbNeeded = newHSBbNeeded;
adjustForHSB(hsbNeeded, availR, hsbR, vpbInsets);
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates
(availR.getSize());
vsbNeeded = viewPrefSize.height >
extentSize.height;
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets,
leftToRight);
}
}
if (_rowFoot != null && _rowFoot.isVisible()) {
vsbR.x += rowFootR.width;
}
}
}
if (oldHSBNeeded != hsbNeeded ||
oldVSBNeeded != vsbNeeded) {
viewport.setBounds(availR);
// You could argue that we should recheck the
// Scrollable methods again until they stop changing,
// but they might never stop changing, so we stop here
// and don't do any additional checks.
}
}
}
/* We now have the final size of the viewport: availR.
* Now fixup the header and scrollbar widths/heights.
*/
vsbR.height = isVsbCoversWholeHeight(scrollPane) ? scrollPane.getHeight() - 1 : availR.height + vpbInsets.top + vpbInsets.bottom;
hsbR.width = isHsbCoversWholeWidth(scrollPane) ? scrollPane.getWidth() - vsbR.width : availR.width + vpbInsets.left + vpbInsets.right;
rowHeadR.height = availR.height + vpbInsets.top + vpbInsets.bottom;
rowHeadR.y = availR.y - vpbInsets.top;
colHeadR.width = availR.width + vpbInsets.left + vpbInsets.right;
colHeadR.x = availR.x - vpbInsets.left;
colFootR.x = availR.x;
colFootR.y = rowHeadR.y + rowHeadR.height;
colFootR.width = availR.width;
rowFootR.x = availR.x + availR.width;
rowFootR.y = availR.y;
rowFootR.height = availR.height;
vsbR.x += rowFootR.width;
hsbR.y += colFootR.height;
/* Set the bounds of the remaining components. The scrollbars
* are made invisible if they're not needed.
*/
if (rowHead != null) {
rowHead.setBounds(rowHeadR);
}
if (_rowFoot != null) {
_rowFoot.setBounds(rowFootR);
}
if (colHead != null) {
int height = Math.min(colHeadR.height, colHead.getPreferredSize().height);
colHead.setBounds(new Rectangle(colHeadR.x, colHeadR.y + colHeadR.height - height, colHeadR.width, height));
}
if (_colFoot != null) {
int height = Math.min(colFootR.height, _colFoot.getPreferredSize().height);
_colFoot.setBounds(new Rectangle(colFootR.x, colFootR.y, colFootR.width, height));
}
if (vsb != null) {
if (vsbNeeded) {
vsb.setVisible(true);
if (_vTop == null && _vBottom == null)
vsb.setBounds(vsbR);
else {
Rectangle rect = new Rectangle(vsbR);
if (_vTop != null) {
Dimension dim = _vTop.getPreferredSize();
rect.y += dim.height;
rect.height -= dim.height;
_vTop.setVisible(true);
_vTop.setBounds(vsbR.x, vsbR.y, vsbR.width, dim.height);
}
if (_vBottom != null) {
Dimension dim = _vBottom.getPreferredSize();
rect.height -= dim.height;
_vBottom.setVisible(true);
_vBottom.setBounds(vsbR.x, vsbR.y + vsbR.height - dim.height, vsbR.width, dim.height);
}
vsb.setBounds(rect);
}
}
else {
if (viewPrefSize.height > extentSize.height) {
vsb.setVisible(true);
vsb.setBounds(vsbR.x, vsbR.y, 0, vsbR.height);
}
else {
vsb.setVisible(false);
}
if (_vTop != null)
_vTop.setVisible(false);
if (_vBottom != null)
_vBottom.setVisible(false);
}
}
if (hsb != null) {
if (hsbNeeded) {
hsb.setVisible(true);
if (_hLeft == null && _hRight == null)
hsb.setBounds(hsbR);
else {
Rectangle rect = new Rectangle(hsbR);
if (_hLeft != null) {
Dimension dim = _hLeft.getPreferredSize();
rect.x += dim.width;
rect.width -= dim.width;
_hLeft.setVisible(true);
_hLeft.setBounds(hsbR.x, hsbR.y, dim.width, hsbR.height);
_hLeft.doLayout();
}
if (_hRight != null) {
Dimension dim = _hRight.getPreferredSize();
rect.width -= dim.width;
_hRight.setVisible(true);
_hRight.setBounds(hsbR.x + hsbR.width - dim.width, hsbR.y, dim.width, hsbR.height);
}
hsb.setBounds(rect);
}
}
else {
if (viewPrefSize.width > extentSize.width) {
hsb.setVisible(true);
hsb.setBounds(hsbR.x, hsbR.y, hsbR.width, 0);
}
else {
hsb.setVisible(false);
}
if (_hLeft != null)
_hLeft.setVisible(false);
if (_hRight != null)
_hRight.setVisible(false);
}
}
if (lowerLeft != null && lowerLeft.isVisible()) {
int height = Math.min(lowerLeft.getPreferredSize().height, colFootR.height);
lowerLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x,
colFootR.y != 0 ? colFootR.y : hsbR.y,
leftToRight ? rowHeadR.width : vsbR.width,
height);
}
if (lowerRight != null && lowerRight.isVisible()) {
int height = Math.min(lowerRight.getPreferredSize().height, colFootR.height);
lowerRight.setBounds(leftToRight ? rowFootR.x : rowHeadR.x,
colFootR.y != 0 ? colFootR.y : hsbR.y,
leftToRight ? rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width) : rowHeadR.width,
height);
}
if (upperLeft != null && upperLeft.isVisible()) {
int height = Math.min(upperLeft.getPreferredSize().height, colHeadR.height);
upperLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x,
colHeadR.y + colHeadR.height - height,
leftToRight ? rowHeadR.width : vsbR.width,
height);
}
if (upperRight != null && upperRight.isVisible()) {
int height = Math.min(upperRight.getPreferredSize().height, colHeadR.height);
upperRight.setBounds(leftToRight ? rowFootR.x : rowHeadR.x,
colHeadR.y + colHeadR.height - height,
leftToRight ? rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width) : rowHeadR.width,
height);
}
}
/**
* Adjusts the <code>Rectangle</code> <code>available</code> based on if
* the vertical scrollbar is needed (<code>wantsVSB</code>).
* The location of the vsb is updated in <code>vsbR</code>, and
* the viewport border insets (<code>vpbInsets</code>) are used to offset
* the vsb. This is only called when <code>wantsVSB</code> has
* changed, eg you shouldn't invoke adjustForVSB(true) twice.
*/
private void adjustForVSB(boolean wantsVSB, Rectangle available,
Rectangle vsbR, Insets vpbInsets,
boolean leftToRight) {
int oldWidth = vsbR.width;
if (wantsVSB) {
int vsbWidth = Math.max(0, Math.min(vsb.getPreferredSize().width,
available.width));
available.width -= vsbWidth;
vsbR.width = vsbWidth;
if (leftToRight) {
vsbR.x = available.x + available.width + vpbInsets.right;
}
else {
vsbR.x = available.x - vpbInsets.left;
available.x += vsbWidth;
}
}
else {
available.width += oldWidth;
}
}
/**
* Adjusts the <code>Rectangle</code> <code>available</code> based on if
* the horizontal scrollbar is needed (<code>wantsHSB</code>).
* The location of the hsb is updated in <code>hsbR</code>, and
* the viewport border insets (<code>vpbInsets</code>) are used to offset
* the hsb. This is only called when <code>wantsHSB</code> has
* changed, eg you shouldn't invoked adjustForHSB(true) twice.
*/
private void adjustForHSB(boolean wantsHSB, Rectangle available,
Rectangle hsbR, Insets vpbInsets) {
int oldHeight = hsbR.height;
if (wantsHSB) {
int hsbHeight = Math.max(0, Math.min(available.height,
hsb.getPreferredSize().height));
available.height -= hsbHeight;
hsbR.y = available.y + available.height + vpbInsets.bottom;
hsbR.height = hsbHeight;
}
else {
available.height += oldHeight;
}
}
/**
* The UI resource version of <code>ScrollPaneLayout</code>.
*/
static class UIResource extends JideScrollPaneLayout implements javax.swing.plaf.UIResource {
}
}
| false | true | public void layoutContainer(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane) parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Rectangle availR = scrollPane.getBounds();
availR.x = availR.y = 0;
Insets insets = parent.getInsets();
availR.x = insets.left;
availR.y = insets.top;
availR.width -= insets.left + insets.right;
availR.height -= insets.top + insets.bottom;
/* Get the scrollPane's orientation.
*/
boolean leftToRight = scrollPane.getComponentOrientation().isLeftToRight();
/* If there's a visible column header remove the space it
* needs from the top of availR. The column header is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0);
int upperHeight = getUpperHeight();
if ((colHead != null) && (colHead.isVisible())) {
int colHeadHeight = Math.min(availR.height,
upperHeight);
colHeadR.height = colHeadHeight;
availR.y += colHeadHeight;
availR.height -= colHeadHeight;
}
/* If there's a visible row header remove the space it needs
* from the left or right of availR. The row header is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowHeadR = new Rectangle(0, 0, 0, 0);
if ((rowHead != null) && (rowHead.isVisible())) {
int rowHeadWidth = rowHead.getPreferredSize().width;
if (upperLeft != null && upperLeft.isVisible()) {
rowHeadWidth = Math.max(rowHeadWidth, upperLeft.getPreferredSize().width);
}
if (lowerLeft != null && lowerLeft.isVisible()) {
rowHeadWidth = Math.max(rowHeadWidth, lowerLeft.getPreferredSize().width);
}
rowHeadWidth = Math.min(availR.width, rowHeadWidth);
rowHeadR.width = rowHeadWidth;
availR.width -= rowHeadWidth;
if (leftToRight) {
rowHeadR.x = availR.x;
availR.x += rowHeadWidth;
}
else {
rowHeadR.x = availR.x + availR.width;
}
}
/* If there's a JScrollPane.viewportBorder, remove the
* space it occupies for availR.
*/
Border viewportBorder = scrollPane.getViewportBorder();
Insets vpbInsets;
if (viewportBorder != null) {
vpbInsets = viewportBorder.getBorderInsets(parent);
availR.x += vpbInsets.left;
availR.y += vpbInsets.top;
availR.width -= vpbInsets.left + vpbInsets.right;
availR.height -= vpbInsets.top + vpbInsets.bottom;
}
else {
vpbInsets = new Insets(0, 0, 0, 0);
}
/* If there's a visible row footer remove the space it needs
* from the left or right of availR. The row footer is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowFootR = new Rectangle(0, 0, 0, 0);
if ((_rowFoot != null) && (_rowFoot.isVisible())) {
int rowFootWidth = Math.min(availR.width,
_rowFoot.getPreferredSize().width);
rowFootR.width = rowFootWidth;
availR.width -= rowFootWidth;
if (leftToRight) {
rowFootR.x = availR.x + availR.width;
}
else {
rowFootR.x = availR.x;
availR.x += rowFootWidth;
}
}
/* If there's a visible column footer remove the space it
* needs from the top of availR. The column footer is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colFootR = new Rectangle(0, availR.y, 0, 0);
int lowerHeight = getLowerHeight();
if ((_colFoot != null) && (_colFoot.isVisible())) {
int colFootHeight = Math.min(availR.height,
lowerHeight);
colFootR.height = colFootHeight;
availR.height -= colFootHeight;
colFootR.y = availR.y + availR.height;
}
/* At this point availR is the space available for the viewport
* and scrollbars. rowHeadR is correct except for its height and y
* and colHeadR is correct except for its width and x. Once we're
* through computing the dimensions of these three parts we can
* go back and set the dimensions of rowHeadR.height, rowHeadR.y,
* colHeadR.width, colHeadR.x and the bounds for the corners.
*
* We'll decide about putting up scrollbars by comparing the
* viewport views preferred size with the viewports extent
* size (generally just its size). Using the preferredSize is
* reasonable because layout proceeds top down - so we expect
* the viewport to be laid out next. And we assume that the
* viewports layout manager will give the view it's preferred
* size. One exception to this is when the view implements
* Scrollable and Scrollable.getViewTracksViewport{Width,Height}
* methods return true. If the view is tracking the viewports
* width we don't bother with a horizontal scrollbar, similarly
* if view.getViewTracksViewport(Height) is true we don't bother
* with a vertical scrollbar.
*/
Component view = (viewport != null) ? viewport.getView() : null;
Dimension viewPrefSize = (view != null) ? view.getPreferredSize() : new Dimension(0, 0);
Dimension extentSize =
(viewport != null) ? viewport.toViewCoordinates(availR.getSize())
: new Dimension(0, 0);
boolean viewTracksViewportWidth = false;
boolean viewTracksViewportHeight = false;
boolean isEmpty = (availR.width < 0 || availR.height < 0);
Scrollable sv;
// Don't bother checking the Scrollable methods if there is no room
// for the viewport, we aren't going to show any scrollbars in this
// case anyway.
if (!isEmpty && view instanceof Scrollable) {
sv = (Scrollable) view;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
}
else {
sv = null;
}
/* If there's a vertical scrollbar and we need one, allocate
* space for it (we'll make it visible later). A vertical
* scrollbar is considered to be fixed width, arbitrary height.
*/
Rectangle vsbR = new Rectangle(0, isVsbCoversWholeHeight(scrollPane) ? -vpbInsets.top : availR.y - vpbInsets.top, 0, 0);
boolean vsbNeeded;
if (isEmpty) {
vsbNeeded = false;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
vsbNeeded = true;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_NEVER) {
vsbNeeded = false;
}
else { // vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED
vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || rowHead.getView().getPreferredSize().height > extentSize.height);
}
if ((vsb != null) && vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight);
extentSize = viewport.toViewCoordinates(availR.getSize());
}
/* If there's a horizontal scrollbar and we need one, allocate
* space for it (we'll make it visible later). A horizontal
* scrollbar is considered to be fixed height, arbitrary width.
*/
Rectangle hsbR = new Rectangle(isHsbCoversWholeWidth(scrollPane) ? -vpbInsets.left : availR.x - vpbInsets.left, 0, 0, 0);
boolean hsbNeeded;
if (isEmpty) {
hsbNeeded = false;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
hsbNeeded = true;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_NEVER) {
hsbNeeded = false;
}
else { // hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED
hsbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || colHead.getView().getPreferredSize().width > extentSize.width);
}
if ((hsb != null) && hsbNeeded) {
adjustForHSB(true, availR, hsbR, vpbInsets);
/* If we added the horizontal scrollbar then we've implicitly
* reduced the vertical space available to the viewport.
* As a consequence we may have to add the vertical scrollbar,
* if that hasn't been done so already. Of course we
* don't bother with any of this if the vsbPolicy is NEVER.
*/
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates(availR.getSize());
vsbNeeded = viewPrefSize.height > extentSize.height;
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight);
}
}
}
/* Set the size of the viewport first, and then recheck the Scrollable
* methods. Some components base their return values for the Scrollable
* methods on the size of the Viewport, so that if we don't
* ask after resetting the bounds we may have gotten the wrong
* answer.
*/
if (viewport != null) {
viewport.setBounds(availR);
if (sv != null) {
extentSize = viewport.toViewCoordinates(availR.getSize());
boolean oldHSBNeeded = hsbNeeded;
boolean oldVSBNeeded = vsbNeeded;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) {
boolean newVSBNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || rowHead.getView().getPreferredSize().height > extentSize.height);
if (newVSBNeeded != vsbNeeded) {
vsbNeeded = newVSBNeeded;
adjustForVSB(vsbNeeded, availR, vsbR, vpbInsets,
leftToRight);
extentSize = viewport.toViewCoordinates
(availR.getSize());
}
}
if (hsb != null && hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) {
boolean newHSBbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || colHead.getView().getPreferredSize().width > extentSize.width);
if (newHSBbNeeded != hsbNeeded) {
hsbNeeded = newHSBbNeeded;
adjustForHSB(hsbNeeded, availR, hsbR, vpbInsets);
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates
(availR.getSize());
vsbNeeded = viewPrefSize.height >
extentSize.height;
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets,
leftToRight);
}
}
if (_rowFoot != null && _rowFoot.isVisible()) {
vsbR.x += rowFootR.width;
}
}
}
if (oldHSBNeeded != hsbNeeded ||
oldVSBNeeded != vsbNeeded) {
viewport.setBounds(availR);
// You could argue that we should recheck the
// Scrollable methods again until they stop changing,
// but they might never stop changing, so we stop here
// and don't do any additional checks.
}
}
}
/* We now have the final size of the viewport: availR.
* Now fixup the header and scrollbar widths/heights.
*/
vsbR.height = isVsbCoversWholeHeight(scrollPane) ? scrollPane.getHeight() - 1 : availR.height + vpbInsets.top + vpbInsets.bottom;
hsbR.width = isHsbCoversWholeWidth(scrollPane) ? scrollPane.getWidth() - vsbR.width : availR.width + vpbInsets.left + vpbInsets.right;
rowHeadR.height = availR.height + vpbInsets.top + vpbInsets.bottom;
rowHeadR.y = availR.y - vpbInsets.top;
colHeadR.width = availR.width + vpbInsets.left + vpbInsets.right;
colHeadR.x = availR.x - vpbInsets.left;
colFootR.x = availR.x;
colFootR.y = rowHeadR.y + rowHeadR.height;
colFootR.width = availR.width;
rowFootR.x = availR.x + availR.width;
rowFootR.y = availR.y;
rowFootR.height = availR.height;
vsbR.x += rowFootR.width;
hsbR.y += colFootR.height;
/* Set the bounds of the remaining components. The scrollbars
* are made invisible if they're not needed.
*/
if (rowHead != null) {
rowHead.setBounds(rowHeadR);
}
if (_rowFoot != null) {
_rowFoot.setBounds(rowFootR);
}
if (colHead != null) {
int height = Math.min(colHeadR.height, colHead.getPreferredSize().height);
colHead.setBounds(new Rectangle(colHeadR.x, colHeadR.y + colHeadR.height - height, colHeadR.width, height));
}
if (_colFoot != null) {
int height = Math.min(colFootR.height, _colFoot.getPreferredSize().height);
_colFoot.setBounds(new Rectangle(colFootR.x, colFootR.y, colFootR.width, height));
}
if (vsb != null) {
if (vsbNeeded) {
vsb.setVisible(true);
if (_vTop == null && _vBottom == null)
vsb.setBounds(vsbR);
else {
Rectangle rect = new Rectangle(vsbR);
if (_vTop != null) {
Dimension dim = _vTop.getPreferredSize();
rect.y += dim.height;
rect.height -= dim.height;
_vTop.setVisible(true);
_vTop.setBounds(vsbR.x, vsbR.y, vsbR.width, dim.height);
}
if (_vBottom != null) {
Dimension dim = _vBottom.getPreferredSize();
rect.height -= dim.height;
_vBottom.setVisible(true);
_vBottom.setBounds(vsbR.x, vsbR.y + vsbR.height - dim.height, vsbR.width, dim.height);
}
vsb.setBounds(rect);
}
}
else {
if (viewPrefSize.height > extentSize.height) {
vsb.setVisible(true);
vsb.setBounds(vsbR.x, vsbR.y, 0, vsbR.height);
}
else {
vsb.setVisible(false);
}
if (_vTop != null)
_vTop.setVisible(false);
if (_vBottom != null)
_vBottom.setVisible(false);
}
}
if (hsb != null) {
if (hsbNeeded) {
hsb.setVisible(true);
if (_hLeft == null && _hRight == null)
hsb.setBounds(hsbR);
else {
Rectangle rect = new Rectangle(hsbR);
if (_hLeft != null) {
Dimension dim = _hLeft.getPreferredSize();
rect.x += dim.width;
rect.width -= dim.width;
_hLeft.setVisible(true);
_hLeft.setBounds(hsbR.x, hsbR.y, dim.width, hsbR.height);
_hLeft.doLayout();
}
if (_hRight != null) {
Dimension dim = _hRight.getPreferredSize();
rect.width -= dim.width;
_hRight.setVisible(true);
_hRight.setBounds(hsbR.x + hsbR.width - dim.width, hsbR.y, dim.width, hsbR.height);
}
hsb.setBounds(rect);
}
}
else {
if (viewPrefSize.width > extentSize.width) {
hsb.setVisible(true);
hsb.setBounds(hsbR.x, hsbR.y, hsbR.width, 0);
}
else {
hsb.setVisible(false);
}
if (_hLeft != null)
_hLeft.setVisible(false);
if (_hRight != null)
_hRight.setVisible(false);
}
}
if (lowerLeft != null && lowerLeft.isVisible()) {
int height = Math.min(lowerLeft.getPreferredSize().height, colFootR.height);
lowerLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x,
colFootR.y != 0 ? colFootR.y : hsbR.y,
leftToRight ? rowHeadR.width : vsbR.width,
height);
}
if (lowerRight != null && lowerRight.isVisible()) {
int height = Math.min(lowerRight.getPreferredSize().height, colFootR.height);
lowerRight.setBounds(leftToRight ? rowFootR.x : rowHeadR.x,
colFootR.y != 0 ? colFootR.y : hsbR.y,
leftToRight ? rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width) : rowHeadR.width,
height);
}
if (upperLeft != null && upperLeft.isVisible()) {
int height = Math.min(upperLeft.getPreferredSize().height, colHeadR.height);
upperLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x,
colHeadR.y + colHeadR.height - height,
leftToRight ? rowHeadR.width : vsbR.width,
height);
}
if (upperRight != null && upperRight.isVisible()) {
int height = Math.min(upperRight.getPreferredSize().height, colHeadR.height);
upperRight.setBounds(leftToRight ? rowFootR.x : rowHeadR.x,
colHeadR.y + colHeadR.height - height,
leftToRight ? rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width) : rowHeadR.width,
height);
}
}
| public void layoutContainer(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane) parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Rectangle availR = scrollPane.getBounds();
availR.x = availR.y = 0;
Insets insets = parent.getInsets();
availR.x = insets.left;
availR.y = insets.top;
availR.width -= insets.left + insets.right;
availR.height -= insets.top + insets.bottom;
/* Get the scrollPane's orientation.
*/
boolean leftToRight = scrollPane.getComponentOrientation().isLeftToRight();
/* If there's a visible column header remove the space it
* needs from the top of availR. The column header is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0);
int upperHeight = getUpperHeight();
if ((colHead != null) && (colHead.isVisible())) {
int colHeadHeight = Math.min(availR.height,
upperHeight);
colHeadR.height = colHeadHeight;
availR.y += colHeadHeight;
availR.height -= colHeadHeight;
}
/* If there's a visible row header remove the space it needs
* from the left or right of availR. The row header is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowHeadR = new Rectangle(0, 0, 0, 0);
if ((rowHead != null) && (rowHead.isVisible())) {
int rowHeadWidth = rowHead.getPreferredSize().width;
if (upperLeft != null && upperLeft.isVisible()) {
rowHeadWidth = Math.max(rowHeadWidth, upperLeft.getPreferredSize().width);
}
if (lowerLeft != null && lowerLeft.isVisible()) {
rowHeadWidth = Math.max(rowHeadWidth, lowerLeft.getPreferredSize().width);
}
rowHeadWidth = Math.min(availR.width, rowHeadWidth);
rowHeadR.width = rowHeadWidth;
availR.width -= rowHeadWidth;
if (leftToRight) {
rowHeadR.x = availR.x;
availR.x += rowHeadWidth;
}
else {
rowHeadR.x = availR.x + availR.width;
}
}
/* If there's a JScrollPane.viewportBorder, remove the
* space it occupies for availR.
*/
Border viewportBorder = scrollPane.getViewportBorder();
Insets vpbInsets;
if (viewportBorder != null) {
vpbInsets = viewportBorder.getBorderInsets(parent);
availR.x += vpbInsets.left;
availR.y += vpbInsets.top;
availR.width -= vpbInsets.left + vpbInsets.right;
availR.height -= vpbInsets.top + vpbInsets.bottom;
}
else {
vpbInsets = new Insets(0, 0, 0, 0);
}
/* If there's a visible row footer remove the space it needs
* from the left or right of availR. The row footer is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowFootR = new Rectangle(0, 0, 0, 0);
if ((_rowFoot != null) && (_rowFoot.isVisible())) {
int rowFootWidth = Math.min(availR.width,
_rowFoot.getPreferredSize().width);
rowFootR.width = rowFootWidth;
availR.width -= rowFootWidth;
if (leftToRight) {
rowFootR.x = availR.x + availR.width;
}
else {
rowFootR.x = availR.x;
availR.x += rowFootWidth;
}
}
/* If there's a visible column footer remove the space it
* needs from the top of availR. The column footer is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colFootR = new Rectangle(0, availR.y, 0, 0);
int lowerHeight = getLowerHeight();
if ((_colFoot != null) && (_colFoot.isVisible())) {
int colFootHeight = Math.min(availR.height,
lowerHeight);
colFootR.height = colFootHeight;
availR.height -= colFootHeight;
colFootR.y = availR.y + availR.height;
}
/* At this point availR is the space available for the viewport
* and scrollbars. rowHeadR is correct except for its height and y
* and colHeadR is correct except for its width and x. Once we're
* through computing the dimensions of these three parts we can
* go back and set the dimensions of rowHeadR.height, rowHeadR.y,
* colHeadR.width, colHeadR.x and the bounds for the corners.
*
* We'll decide about putting up scrollbars by comparing the
* viewport views preferred size with the viewports extent
* size (generally just its size). Using the preferredSize is
* reasonable because layout proceeds top down - so we expect
* the viewport to be laid out next. And we assume that the
* viewports layout manager will give the view it's preferred
* size. One exception to this is when the view implements
* Scrollable and Scrollable.getViewTracksViewport{Width,Height}
* methods return true. If the view is tracking the viewports
* width we don't bother with a horizontal scrollbar, similarly
* if view.getViewTracksViewport(Height) is true we don't bother
* with a vertical scrollbar.
*/
Component view = (viewport != null) ? viewport.getView() : null;
Dimension viewPrefSize = (view != null) ? view.getPreferredSize() : new Dimension(0, 0);
Dimension extentSize =
(viewport != null) ? viewport.toViewCoordinates(availR.getSize())
: new Dimension(0, 0);
boolean viewTracksViewportWidth = false;
boolean viewTracksViewportHeight = false;
boolean isEmpty = (availR.width < 0 || availR.height < 0);
Scrollable sv;
// Don't bother checking the Scrollable methods if there is no room
// for the viewport, we aren't going to show any scrollbars in this
// case anyway.
if (!isEmpty && view instanceof Scrollable) {
sv = (Scrollable) view;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
}
else {
sv = null;
}
/* If there's a vertical scrollbar and we need one, allocate
* space for it (we'll make it visible later). A vertical
* scrollbar is considered to be fixed width, arbitrary height.
*/
Rectangle vsbR = new Rectangle(0, isVsbCoversWholeHeight(scrollPane) ? -vpbInsets.top : availR.y - vpbInsets.top, 0, 0);
boolean vsbNeeded;
if (isEmpty) {
vsbNeeded = false;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
vsbNeeded = true;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_NEVER) {
vsbNeeded = false;
}
else { // vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED
vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView().getPreferredSize().height > extentSize.height));
}
if ((vsb != null) && vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight);
extentSize = viewport.toViewCoordinates(availR.getSize());
}
/* If there's a horizontal scrollbar and we need one, allocate
* space for it (we'll make it visible later). A horizontal
* scrollbar is considered to be fixed height, arbitrary width.
*/
Rectangle hsbR = new Rectangle(isHsbCoversWholeWidth(scrollPane) ? -vpbInsets.left : availR.x - vpbInsets.left, 0, 0, 0);
boolean hsbNeeded;
if (isEmpty) {
hsbNeeded = false;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
hsbNeeded = true;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_NEVER) {
hsbNeeded = false;
}
else { // hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED
hsbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView().getPreferredSize().width > extentSize.width));
}
if ((hsb != null) && hsbNeeded) {
adjustForHSB(true, availR, hsbR, vpbInsets);
/* If we added the horizontal scrollbar then we've implicitly
* reduced the vertical space available to the viewport.
* As a consequence we may have to add the vertical scrollbar,
* if that hasn't been done so already. Of course we
* don't bother with any of this if the vsbPolicy is NEVER.
*/
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates(availR.getSize());
vsbNeeded = viewPrefSize.height > extentSize.height;
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight);
}
}
}
/* Set the size of the viewport first, and then recheck the Scrollable
* methods. Some components base their return values for the Scrollable
* methods on the size of the Viewport, so that if we don't
* ask after resetting the bounds we may have gotten the wrong
* answer.
*/
if (viewport != null) {
viewport.setBounds(availR);
if (sv != null) {
extentSize = viewport.toViewCoordinates(availR.getSize());
boolean oldHSBNeeded = hsbNeeded;
boolean oldVSBNeeded = vsbNeeded;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) {
boolean newVSBNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView().getPreferredSize().height > extentSize.height));
if (newVSBNeeded != vsbNeeded) {
vsbNeeded = newVSBNeeded;
adjustForVSB(vsbNeeded, availR, vsbR, vpbInsets,
leftToRight);
extentSize = viewport.toViewCoordinates
(availR.getSize());
}
}
if (hsb != null && hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) {
boolean newHSBbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView().getPreferredSize().width > extentSize.width));
if (newHSBbNeeded != hsbNeeded) {
hsbNeeded = newHSBbNeeded;
adjustForHSB(hsbNeeded, availR, hsbR, vpbInsets);
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates
(availR.getSize());
vsbNeeded = viewPrefSize.height >
extentSize.height;
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets,
leftToRight);
}
}
if (_rowFoot != null && _rowFoot.isVisible()) {
vsbR.x += rowFootR.width;
}
}
}
if (oldHSBNeeded != hsbNeeded ||
oldVSBNeeded != vsbNeeded) {
viewport.setBounds(availR);
// You could argue that we should recheck the
// Scrollable methods again until they stop changing,
// but they might never stop changing, so we stop here
// and don't do any additional checks.
}
}
}
/* We now have the final size of the viewport: availR.
* Now fixup the header and scrollbar widths/heights.
*/
vsbR.height = isVsbCoversWholeHeight(scrollPane) ? scrollPane.getHeight() - 1 : availR.height + vpbInsets.top + vpbInsets.bottom;
hsbR.width = isHsbCoversWholeWidth(scrollPane) ? scrollPane.getWidth() - vsbR.width : availR.width + vpbInsets.left + vpbInsets.right;
rowHeadR.height = availR.height + vpbInsets.top + vpbInsets.bottom;
rowHeadR.y = availR.y - vpbInsets.top;
colHeadR.width = availR.width + vpbInsets.left + vpbInsets.right;
colHeadR.x = availR.x - vpbInsets.left;
colFootR.x = availR.x;
colFootR.y = rowHeadR.y + rowHeadR.height;
colFootR.width = availR.width;
rowFootR.x = availR.x + availR.width;
rowFootR.y = availR.y;
rowFootR.height = availR.height;
vsbR.x += rowFootR.width;
hsbR.y += colFootR.height;
/* Set the bounds of the remaining components. The scrollbars
* are made invisible if they're not needed.
*/
if (rowHead != null) {
rowHead.setBounds(rowHeadR);
}
if (_rowFoot != null) {
_rowFoot.setBounds(rowFootR);
}
if (colHead != null) {
int height = Math.min(colHeadR.height, colHead.getPreferredSize().height);
colHead.setBounds(new Rectangle(colHeadR.x, colHeadR.y + colHeadR.height - height, colHeadR.width, height));
}
if (_colFoot != null) {
int height = Math.min(colFootR.height, _colFoot.getPreferredSize().height);
_colFoot.setBounds(new Rectangle(colFootR.x, colFootR.y, colFootR.width, height));
}
if (vsb != null) {
if (vsbNeeded) {
vsb.setVisible(true);
if (_vTop == null && _vBottom == null)
vsb.setBounds(vsbR);
else {
Rectangle rect = new Rectangle(vsbR);
if (_vTop != null) {
Dimension dim = _vTop.getPreferredSize();
rect.y += dim.height;
rect.height -= dim.height;
_vTop.setVisible(true);
_vTop.setBounds(vsbR.x, vsbR.y, vsbR.width, dim.height);
}
if (_vBottom != null) {
Dimension dim = _vBottom.getPreferredSize();
rect.height -= dim.height;
_vBottom.setVisible(true);
_vBottom.setBounds(vsbR.x, vsbR.y + vsbR.height - dim.height, vsbR.width, dim.height);
}
vsb.setBounds(rect);
}
}
else {
if (viewPrefSize.height > extentSize.height) {
vsb.setVisible(true);
vsb.setBounds(vsbR.x, vsbR.y, 0, vsbR.height);
}
else {
vsb.setVisible(false);
}
if (_vTop != null)
_vTop.setVisible(false);
if (_vBottom != null)
_vBottom.setVisible(false);
}
}
if (hsb != null) {
if (hsbNeeded) {
hsb.setVisible(true);
if (_hLeft == null && _hRight == null)
hsb.setBounds(hsbR);
else {
Rectangle rect = new Rectangle(hsbR);
if (_hLeft != null) {
Dimension dim = _hLeft.getPreferredSize();
rect.x += dim.width;
rect.width -= dim.width;
_hLeft.setVisible(true);
_hLeft.setBounds(hsbR.x, hsbR.y, dim.width, hsbR.height);
_hLeft.doLayout();
}
if (_hRight != null) {
Dimension dim = _hRight.getPreferredSize();
rect.width -= dim.width;
_hRight.setVisible(true);
_hRight.setBounds(hsbR.x + hsbR.width - dim.width, hsbR.y, dim.width, hsbR.height);
}
hsb.setBounds(rect);
}
}
else {
if (viewPrefSize.width > extentSize.width) {
hsb.setVisible(true);
hsb.setBounds(hsbR.x, hsbR.y, hsbR.width, 0);
}
else {
hsb.setVisible(false);
}
if (_hLeft != null)
_hLeft.setVisible(false);
if (_hRight != null)
_hRight.setVisible(false);
}
}
if (lowerLeft != null && lowerLeft.isVisible()) {
int height = Math.min(lowerLeft.getPreferredSize().height, colFootR.height);
lowerLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x,
colFootR.y != 0 ? colFootR.y : hsbR.y,
leftToRight ? rowHeadR.width : vsbR.width,
height);
}
if (lowerRight != null && lowerRight.isVisible()) {
int height = Math.min(lowerRight.getPreferredSize().height, colFootR.height);
lowerRight.setBounds(leftToRight ? rowFootR.x : rowHeadR.x,
colFootR.y != 0 ? colFootR.y : hsbR.y,
leftToRight ? rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width) : rowHeadR.width,
height);
}
if (upperLeft != null && upperLeft.isVisible()) {
int height = Math.min(upperLeft.getPreferredSize().height, colHeadR.height);
upperLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x,
colHeadR.y + colHeadR.height - height,
leftToRight ? rowHeadR.width : vsbR.width,
height);
}
if (upperRight != null && upperRight.isVisible()) {
int height = Math.min(upperRight.getPreferredSize().height, colHeadR.height);
upperRight.setBounds(leftToRight ? rowFootR.x : rowHeadR.x,
colHeadR.y + colHeadR.height - height,
leftToRight ? rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width) : rowHeadR.width,
height);
}
}
|
diff --git a/src/org/wescheme/servlet/LoadProjectServlet.java b/src/org/wescheme/servlet/LoadProjectServlet.java
index ca17cc79..da44416a 100644
--- a/src/org/wescheme/servlet/LoadProjectServlet.java
+++ b/src/org/wescheme/servlet/LoadProjectServlet.java
@@ -1,90 +1,92 @@
package org.wescheme.servlet;
import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jdom.output.XMLOutputter;
import org.wescheme.project.Program;
import org.wescheme.user.Session;
import org.wescheme.user.SessionManager;
import org.wescheme.util.PMF;
import org.wescheme.util.Queries;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import java.util.logging.Logger;
public class LoadProjectServlet extends HttpServlet {
/**
* Returns program XML if either pid or publicId is provided.
*/
private static final long serialVersionUID = 1165047992267892812L;
private static final Logger log = Logger.getLogger(LoadProjectServlet.class.getName());
private boolean isOwner(Session userSession, Program prog) {
return (userSession != null &&
prog != null &&
prog.getOwner().equals(userSession.getName()));
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
Session userSession;
SessionManager sm = new SessionManager();
userSession = sm.authenticate(req, resp);
if (req.getParameter("pid") != null) {
Program prog = getProgramByPid(pm, req.getParameter("pid"));
if( null != userSession ){
if (isOwner(userSession, prog) || userSession.isAdmin()) {
XMLOutputter outputter = new XMLOutputter();
resp.setContentType("text/xml");
resp.getWriter().print(outputter.outputString(prog.toXML(pm)));
} else {
log.warning(userSession.getName() + " does not own " + req.getParameter("pid"));
- throw new RuntimeException("Not owner");
+ resp.sendError(401, "Not owner");
+ return;
}
} else {
resp.sendError(403);
}
} else if (req.getParameter("publicId") != null) {
Program prog = getProgramByPublicId(pm, req.getParameter("publicId"));
if (isOwner(userSession, prog) || prog.getIsSourcePublic()) {
XMLOutputter outputter = new XMLOutputter();
resp.setContentType("text/xml");
resp.getWriter().print(outputter.outputString(prog.toXML(pm)));
} else {
// Show the record, but without source.
XMLOutputter outputter = new XMLOutputter();
resp.setContentType("text/xml");
resp.getWriter().print(outputter.outputString(prog.toXML(false, pm)));
}
} else {
- throw new RuntimeException("pid or publicId parameter missing");
+ resp.sendError(400, "pid or publicId parameter missing");
+ return;
}
} finally {
pm.close();
}
}
private Program getProgramByPid(PersistenceManager pm, String pid) {
Long id = (Long) Long.parseLong(pid);
Key k = KeyFactory.createKey("Program", id);
Program prog = pm.getObjectById(Program.class, k);
return prog;
}
private Program getProgramByPublicId(PersistenceManager pm, String publicId) {
Program program = Queries.getProgramByPublicId(pm, publicId);
if (program == null) {
throw new RuntimeException("Could not find unique program with publicId=" + publicId);
}
return program;
}
}
| false | true | public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
Session userSession;
SessionManager sm = new SessionManager();
userSession = sm.authenticate(req, resp);
if (req.getParameter("pid") != null) {
Program prog = getProgramByPid(pm, req.getParameter("pid"));
if( null != userSession ){
if (isOwner(userSession, prog) || userSession.isAdmin()) {
XMLOutputter outputter = new XMLOutputter();
resp.setContentType("text/xml");
resp.getWriter().print(outputter.outputString(prog.toXML(pm)));
} else {
log.warning(userSession.getName() + " does not own " + req.getParameter("pid"));
throw new RuntimeException("Not owner");
}
} else {
resp.sendError(403);
}
} else if (req.getParameter("publicId") != null) {
Program prog = getProgramByPublicId(pm, req.getParameter("publicId"));
if (isOwner(userSession, prog) || prog.getIsSourcePublic()) {
XMLOutputter outputter = new XMLOutputter();
resp.setContentType("text/xml");
resp.getWriter().print(outputter.outputString(prog.toXML(pm)));
} else {
// Show the record, but without source.
XMLOutputter outputter = new XMLOutputter();
resp.setContentType("text/xml");
resp.getWriter().print(outputter.outputString(prog.toXML(false, pm)));
}
} else {
throw new RuntimeException("pid or publicId parameter missing");
}
} finally {
pm.close();
}
}
| public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
Session userSession;
SessionManager sm = new SessionManager();
userSession = sm.authenticate(req, resp);
if (req.getParameter("pid") != null) {
Program prog = getProgramByPid(pm, req.getParameter("pid"));
if( null != userSession ){
if (isOwner(userSession, prog) || userSession.isAdmin()) {
XMLOutputter outputter = new XMLOutputter();
resp.setContentType("text/xml");
resp.getWriter().print(outputter.outputString(prog.toXML(pm)));
} else {
log.warning(userSession.getName() + " does not own " + req.getParameter("pid"));
resp.sendError(401, "Not owner");
return;
}
} else {
resp.sendError(403);
}
} else if (req.getParameter("publicId") != null) {
Program prog = getProgramByPublicId(pm, req.getParameter("publicId"));
if (isOwner(userSession, prog) || prog.getIsSourcePublic()) {
XMLOutputter outputter = new XMLOutputter();
resp.setContentType("text/xml");
resp.getWriter().print(outputter.outputString(prog.toXML(pm)));
} else {
// Show the record, but without source.
XMLOutputter outputter = new XMLOutputter();
resp.setContentType("text/xml");
resp.getWriter().print(outputter.outputString(prog.toXML(false, pm)));
}
} else {
resp.sendError(400, "pid or publicId parameter missing");
return;
}
} finally {
pm.close();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.