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/java/davmail/smtp/SmtpConnection.java b/src/java/davmail/smtp/SmtpConnection.java
index 7cd1d76..2f6e17c 100644
--- a/src/java/davmail/smtp/SmtpConnection.java
+++ b/src/java/davmail/smtp/SmtpConnection.java
@@ -1,157 +1,158 @@
package davmail.smtp;
import davmail.AbstractConnection;
import davmail.tray.DavGatewayTray;
import davmail.exchange.ExchangeSession;
import sun.misc.BASE64Decoder;
import java.io.IOException;
import java.net.Socket;
import java.util.Date;
import java.util.StringTokenizer;
/**
* Dav Gateway smtp connection implementation
*/
public class SmtpConnection extends AbstractConnection {
protected static final int INITIAL = 0;
protected static final int AUTHENTICATED = 1;
protected static final int STARTMAIL = 2;
protected static final int RECIPIENT = 3;
protected static final int MAILDATA = 4;
// Initialize the streams and start the thread
public SmtpConnection(Socket clientSocket) {
super(clientSocket);
}
public void run() {
String line;
StringTokenizer tokens;
try {
ExchangeSession.checkConfig();
sendClient("220 DavMail SMTP ready at " + new Date());
for (; ;) {
line = readClient();
// unable to read line, connection closed ?
if (line == null) {
break;
}
tokens = new StringTokenizer(line);
if (tokens.hasMoreTokens()) {
String command = tokens.nextToken();
if ("QUIT".equalsIgnoreCase(command)) {
sendClient("221 Closing connection");
break;
} else if ("EHLO".equals(command)) {
+ sendClient("250-" + tokens.nextToken());
// inform server that AUTH is supported
// actually it is mandatory (only way to get credentials)
sendClient("250-AUTH LOGIN PLAIN");
sendClient("250 Hello");
} else if ("HELO".equals(command)) {
sendClient("250 Hello");
} else if ("AUTH".equals(command)) {
if (tokens.hasMoreElements()) {
String authType = tokens.nextToken();
if ("PLAIN".equals(authType) && tokens.hasMoreElements()) {
decodeCredentials(tokens.nextToken());
session = new ExchangeSession();
try {
session.login(userName, password);
sendClient("235 OK Authenticated");
state = AUTHENTICATED;
} catch (Exception e) {
String message = e.getMessage();
if (message == null) {
message = e.toString();
}
DavGatewayTray.error(message);
message = message.replaceAll("\\n", " ");
sendClient("554 Authenticated failed " + message);
state = INITIAL;
}
} else {
sendClient("451 Error : unknown authentication type");
}
} else {
sendClient("451 Error : authentication type not specified");
}
} else if ("MAIL".equals(command)) {
if (state == AUTHENTICATED) {
state = STARTMAIL;
sendClient("250 Sender OK");
} else {
state = INITIAL;
sendClient("503 Bad sequence of commands");
}
} else if ("RCPT".equals(command)) {
if (state == STARTMAIL || state == RECIPIENT) {
state = RECIPIENT;
sendClient("250 Recipient OK");
} else {
state = AUTHENTICATED;
sendClient("503 Bad sequence of commands");
}
} else if ("DATA".equals(command)) {
if (state == RECIPIENT) {
state = MAILDATA;
sendClient("354 Start mail input; end with <CRLF>.<CRLF>");
try {
session.sendMessage(in);
state = AUTHENTICATED;
sendClient("250 Queued mail for delivery");
} catch (Exception e) {
DavGatewayTray.error("Authentication failed", e);
state = AUTHENTICATED;
sendClient("451 Error : " + e + " " + e.getMessage());
}
} else {
state = AUTHENTICATED;
sendClient("503 Bad sequence of commands");
}
}
} else {
sendClient("500 Unrecognized command");
}
os.flush();
}
} catch (IOException e) {
DavGatewayTray.error(e.getMessage());
try {
sendClient("500 " + e.getMessage());
} catch (IOException e2) {
DavGatewayTray.debug("Exception sending error to client", e2);
}
} finally {
close();
}
DavGatewayTray.resetIcon();
}
/**
* Decode SMTP credentials
*
* @param encodedCredentials smtp encoded credentials
* @throws java.io.IOException if invalid credentials
*/
protected void decodeCredentials(String encodedCredentials) throws IOException {
BASE64Decoder decoder = new BASE64Decoder();
String decodedCredentials = new String(decoder.decodeBuffer(encodedCredentials));
int index = decodedCredentials.indexOf((char) 0, 1);
if (index > 0) {
userName = decodedCredentials.substring(1, index);
password = decodedCredentials.substring(index + 1);
} else {
throw new IOException("Invalid credentials");
}
}
}
| true | true | public void run() {
String line;
StringTokenizer tokens;
try {
ExchangeSession.checkConfig();
sendClient("220 DavMail SMTP ready at " + new Date());
for (; ;) {
line = readClient();
// unable to read line, connection closed ?
if (line == null) {
break;
}
tokens = new StringTokenizer(line);
if (tokens.hasMoreTokens()) {
String command = tokens.nextToken();
if ("QUIT".equalsIgnoreCase(command)) {
sendClient("221 Closing connection");
break;
} else if ("EHLO".equals(command)) {
// inform server that AUTH is supported
// actually it is mandatory (only way to get credentials)
sendClient("250-AUTH LOGIN PLAIN");
sendClient("250 Hello");
} else if ("HELO".equals(command)) {
sendClient("250 Hello");
} else if ("AUTH".equals(command)) {
if (tokens.hasMoreElements()) {
String authType = tokens.nextToken();
if ("PLAIN".equals(authType) && tokens.hasMoreElements()) {
decodeCredentials(tokens.nextToken());
session = new ExchangeSession();
try {
session.login(userName, password);
sendClient("235 OK Authenticated");
state = AUTHENTICATED;
} catch (Exception e) {
String message = e.getMessage();
if (message == null) {
message = e.toString();
}
DavGatewayTray.error(message);
message = message.replaceAll("\\n", " ");
sendClient("554 Authenticated failed " + message);
state = INITIAL;
}
} else {
sendClient("451 Error : unknown authentication type");
}
} else {
sendClient("451 Error : authentication type not specified");
}
} else if ("MAIL".equals(command)) {
if (state == AUTHENTICATED) {
state = STARTMAIL;
sendClient("250 Sender OK");
} else {
state = INITIAL;
sendClient("503 Bad sequence of commands");
}
} else if ("RCPT".equals(command)) {
if (state == STARTMAIL || state == RECIPIENT) {
state = RECIPIENT;
sendClient("250 Recipient OK");
} else {
state = AUTHENTICATED;
sendClient("503 Bad sequence of commands");
}
} else if ("DATA".equals(command)) {
if (state == RECIPIENT) {
state = MAILDATA;
sendClient("354 Start mail input; end with <CRLF>.<CRLF>");
try {
session.sendMessage(in);
state = AUTHENTICATED;
sendClient("250 Queued mail for delivery");
} catch (Exception e) {
DavGatewayTray.error("Authentication failed", e);
state = AUTHENTICATED;
sendClient("451 Error : " + e + " " + e.getMessage());
}
} else {
state = AUTHENTICATED;
sendClient("503 Bad sequence of commands");
}
}
} else {
sendClient("500 Unrecognized command");
}
os.flush();
}
} catch (IOException e) {
DavGatewayTray.error(e.getMessage());
try {
sendClient("500 " + e.getMessage());
} catch (IOException e2) {
DavGatewayTray.debug("Exception sending error to client", e2);
}
} finally {
close();
}
DavGatewayTray.resetIcon();
}
| public void run() {
String line;
StringTokenizer tokens;
try {
ExchangeSession.checkConfig();
sendClient("220 DavMail SMTP ready at " + new Date());
for (; ;) {
line = readClient();
// unable to read line, connection closed ?
if (line == null) {
break;
}
tokens = new StringTokenizer(line);
if (tokens.hasMoreTokens()) {
String command = tokens.nextToken();
if ("QUIT".equalsIgnoreCase(command)) {
sendClient("221 Closing connection");
break;
} else if ("EHLO".equals(command)) {
sendClient("250-" + tokens.nextToken());
// inform server that AUTH is supported
// actually it is mandatory (only way to get credentials)
sendClient("250-AUTH LOGIN PLAIN");
sendClient("250 Hello");
} else if ("HELO".equals(command)) {
sendClient("250 Hello");
} else if ("AUTH".equals(command)) {
if (tokens.hasMoreElements()) {
String authType = tokens.nextToken();
if ("PLAIN".equals(authType) && tokens.hasMoreElements()) {
decodeCredentials(tokens.nextToken());
session = new ExchangeSession();
try {
session.login(userName, password);
sendClient("235 OK Authenticated");
state = AUTHENTICATED;
} catch (Exception e) {
String message = e.getMessage();
if (message == null) {
message = e.toString();
}
DavGatewayTray.error(message);
message = message.replaceAll("\\n", " ");
sendClient("554 Authenticated failed " + message);
state = INITIAL;
}
} else {
sendClient("451 Error : unknown authentication type");
}
} else {
sendClient("451 Error : authentication type not specified");
}
} else if ("MAIL".equals(command)) {
if (state == AUTHENTICATED) {
state = STARTMAIL;
sendClient("250 Sender OK");
} else {
state = INITIAL;
sendClient("503 Bad sequence of commands");
}
} else if ("RCPT".equals(command)) {
if (state == STARTMAIL || state == RECIPIENT) {
state = RECIPIENT;
sendClient("250 Recipient OK");
} else {
state = AUTHENTICATED;
sendClient("503 Bad sequence of commands");
}
} else if ("DATA".equals(command)) {
if (state == RECIPIENT) {
state = MAILDATA;
sendClient("354 Start mail input; end with <CRLF>.<CRLF>");
try {
session.sendMessage(in);
state = AUTHENTICATED;
sendClient("250 Queued mail for delivery");
} catch (Exception e) {
DavGatewayTray.error("Authentication failed", e);
state = AUTHENTICATED;
sendClient("451 Error : " + e + " " + e.getMessage());
}
} else {
state = AUTHENTICATED;
sendClient("503 Bad sequence of commands");
}
}
} else {
sendClient("500 Unrecognized command");
}
os.flush();
}
} catch (IOException e) {
DavGatewayTray.error(e.getMessage());
try {
sendClient("500 " + e.getMessage());
} catch (IOException e2) {
DavGatewayTray.debug("Exception sending error to client", e2);
}
} finally {
close();
}
DavGatewayTray.resetIcon();
}
|
diff --git a/src/com/android/browser/PhoneUi.java b/src/com/android/browser/PhoneUi.java
index 009989bc..f5a76b92 100644
--- a/src/com/android/browser/PhoneUi.java
+++ b/src/com/android/browser/PhoneUi.java
@@ -1,478 +1,488 @@
/*
* Copyright (C) 2010 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.browser;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.Log;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.DecelerateInterpolator;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.android.browser.UrlInputView.StateListener;
/**
* Ui for regular phone screen sizes
*/
public class PhoneUi extends BaseUi {
private static final String LOGTAG = "PhoneUi";
private PieControlPhone mPieControl;
private NavScreen mNavScreen;
private NavigationBarPhone mNavigationBar;
boolean mExtendedMenuOpen;
boolean mOptionsMenuOpen;
boolean mAnimating;
/**
* @param browser
* @param controller
*/
public PhoneUi(Activity browser, UiController controller) {
super(browser, controller);
mActivity.getActionBar().hide();
setUseQuickControls(BrowserSettings.getInstance().useQuickControls());
mNavigationBar = (NavigationBarPhone) mTitleBar.getNavigationBar();
}
@Override
public void onDestroy() {
hideTitleBar();
}
@Override
public void editUrl(boolean clearInput) {
if (mUseQuickControls) {
mTitleBar.setShowProgressOnly(false);
}
super.editUrl(clearInput);
}
@Override
public boolean onBackKey() {
if (mNavScreen != null) {
mNavScreen.close();
return true;
}
return super.onBackKey();
}
@Override
public boolean dispatchKey(int code, KeyEvent event) {
return false;
}
@Override
public void onProgressChanged(Tab tab) {
if (tab.inForeground()) {
int progress = tab.getLoadProgress();
mTitleBar.setProgress(progress);
if (progress == 100) {
if (!mOptionsMenuOpen || !mExtendedMenuOpen) {
suggestHideTitleBar();
if (mUseQuickControls) {
mTitleBar.setShowProgressOnly(false);
}
}
} else {
if (!mOptionsMenuOpen || mExtendedMenuOpen) {
if (mUseQuickControls && !mTitleBar.isEditingUrl()) {
mTitleBar.setShowProgressOnly(true);
setTitleGravity(Gravity.TOP);
}
showTitleBar();
}
}
}
}
@Override
public void setActiveTab(final Tab tab) {
mTitleBar.cancelTitleBarAnimation(true);
mTitleBar.setSkipTitleBarAnimations(true);
super.setActiveTab(tab);
BrowserWebView view = (BrowserWebView) tab.getWebView();
// TabControl.setCurrentTab has been called before this,
// so the tab is guaranteed to have a webview
if (view == null) {
Log.e(LOGTAG, "active tab with no webview detected");
return;
}
// Request focus on the top window.
if (mUseQuickControls) {
mPieControl.forceToTop(mContentView);
} else {
// check if title bar is already attached by animation
if (mTitleBar.getParent() == null) {
view.setEmbeddedTitleBar(mTitleBar);
}
}
if (tab.isInVoiceSearchMode()) {
showVoiceTitleBar(tab.getVoiceDisplayTitle(), tab.getVoiceSearchResults());
} else {
revertVoiceTitleBar(tab);
}
// update nav bar state
mNavigationBar.onStateChanged(StateListener.STATE_NORMAL);
updateLockIconToLatest(tab);
tab.getTopWindow().requestFocus();
mTitleBar.setSkipTitleBarAnimations(false);
}
// menu handling callbacks
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
updateMenuState(mActiveTab, menu);
return true;
}
@Override
public void updateMenuState(Tab tab, Menu menu) {
menu.setGroupVisible(R.id.NAV_MENU, (mNavScreen == null));
MenuItem bm = menu.findItem(R.id.bookmarks_menu_id);
if (bm != null) {
bm.setVisible(mNavScreen == null);
}
MenuItem nt = menu.findItem(R.id.new_tab_menu_id);
if (nt != null) {
nt.setVisible(mNavScreen == null);
}
MenuItem abm = menu.findItem(R.id.add_bookmark_menu_id);
if (abm != null) {
abm.setVisible((tab != null) && !tab.isSnapshot());
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mNavScreen != null) {
hideNavScreen(false);
}
return false;
}
@Override
public void onContextMenuCreated(Menu menu) {
hideTitleBar();
}
@Override
public void onContextMenuClosed(Menu menu, boolean inLoad) {
if (inLoad) {
showTitleBar();
}
}
// action mode callbacks
@Override
public void onActionModeStarted(ActionMode mode) {
if (!isEditingUrl()) {
hideTitleBar();
}
}
@Override
public void onActionModeFinished(boolean inLoad) {
if (inLoad) {
if (mUseQuickControls) {
mTitleBar.setShowProgressOnly(true);
}
showTitleBar();
}
mActivity.getActionBar().hide();
}
@Override
protected void setTitleGravity(int gravity) {
if (mUseQuickControls) {
FrameLayout.LayoutParams lp =
(FrameLayout.LayoutParams) mTitleBar.getLayoutParams();
lp.gravity = gravity;
mTitleBar.setLayoutParams(lp);
} else {
super.setTitleGravity(gravity);
}
}
@Override
public void setUseQuickControls(boolean useQuickControls) {
mUseQuickControls = useQuickControls;
mTitleBar.setUseQuickControls(mUseQuickControls);
if (useQuickControls) {
mPieControl = new PieControlPhone(mActivity, mUiController, this);
mPieControl.attachToContainer(mContentView);
WebView web = getWebView();
if (web != null) {
web.setEmbeddedTitleBar(null);
}
} else {
if (mPieControl != null) {
mPieControl.removeFromContainer(mContentView);
}
WebView web = getWebView();
if (web != null) {
// make sure we can re-parent titlebar
if ((mTitleBar != null) && (mTitleBar.getParent() != null)) {
((ViewGroup) mTitleBar.getParent()).removeView(mTitleBar);
}
web.setEmbeddedTitleBar(mTitleBar);
}
setTitleGravity(Gravity.NO_GRAVITY);
}
updateUrlBarAutoShowManagerTarget();
}
@Override
public boolean isWebShowing() {
return super.isWebShowing() && mNavScreen == null;
}
@Override
public void showWeb(boolean animate) {
super.showWeb(animate);
hideNavScreen(animate);
}
void showNavScreen() {
mUiController.setBlockEvents(true);
mNavScreen = new NavScreen(mActivity, mUiController, this);
mActiveTab.capture();
// Add the custom view to its container
mCustomViewContainer.addView(mNavScreen, COVER_SCREEN_PARAMS);
AnimScreen ascreen = new AnimScreen(mActivity, getTitleBar(), getWebView());
final View animView = ascreen.mMain;
mCustomViewContainer.addView(animView, COVER_SCREEN_PARAMS);
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
View target = ((NavTabView) mNavScreen.mScroller.getSelectedView()).mImage;
int fromLeft = 0;
int fromTop = getTitleBar().getHeight();
int fromRight = mContentView.getWidth();
int fromBottom = mContentView.getHeight();
int width = target.getWidth();
int height = target.getHeight();
int toLeft = (mContentView.getWidth() - width) / 2;
int toTop = fromTop + (mContentView.getHeight() - fromTop - height) / 2;
int toRight = toLeft + width;
int toBottom = toTop + height;
float scaleFactor = width / (float) mContentView.getWidth();
detachTab(mActiveTab);
mContentView.setVisibility(View.GONE);
AnimatorSet inanim = new AnimatorSet();
ObjectAnimator tx = ObjectAnimator.ofInt(ascreen.mContent, "left",
fromLeft, toLeft);
ObjectAnimator ty = ObjectAnimator.ofInt(ascreen.mContent, "top",
fromTop, toTop);
ObjectAnimator tr = ObjectAnimator.ofInt(ascreen.mContent, "right",
fromRight, toRight);
ObjectAnimator tb = ObjectAnimator.ofInt(ascreen.mContent, "bottom",
fromBottom, toBottom);
ObjectAnimator title = ObjectAnimator.ofFloat(ascreen.mTitle, "alpha",
1f, 0f);
ObjectAnimator content = ObjectAnimator.ofFloat(ascreen.mContent, "alpha",
1f, 0f);
ObjectAnimator sx = ObjectAnimator.ofFloat(ascreen, "scaleFactor",
1f, scaleFactor);
inanim.playTogether(tx, ty, tr, tb, title, content, sx);
inanim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
mCustomViewContainer.removeView(animView);
finishAnimationIn();
mUiController.setBlockEvents(false);
}
});
inanim.setInterpolator(new DecelerateInterpolator(2f));
inanim.setDuration(300);
inanim.start();
}
private void finishAnimationIn() {
if (mNavScreen != null) {
// notify accessibility manager about the screen change
mNavScreen.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
mTabControl.setOnThumbnailUpdatedListener(mNavScreen);
}
}
void hideNavScreen(boolean animate) {
if (mNavScreen == null) return;
final Tab tab = mNavScreen.getSelectedTab();
if ((tab == null) || !animate) {
+ if (tab != null) {
+ setActiveTab(tab);
+ } else if (mTabControl.getTabCount() > 0) {
+ // use a fallback tab
+ setActiveTab(mTabControl.getCurrentTab());
+ }
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
NavTabView tabview = (NavTabView) mNavScreen.getSelectedTabView();
if (tabview == null) {
+ if (mTabControl.getTabCount() > 0) {
+ // use a fallback tab
+ setActiveTab(mTabControl.getCurrentTab());
+ }
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
mUiController.setBlockEvents(true);
mUiController.setActiveTab(tab);
mContentView.setVisibility(View.VISIBLE);
final AnimScreen screen = new AnimScreen(mActivity, tab.getScreenshot());
View target = ((NavTabView) mNavScreen.mScroller.getSelectedView()).mImage;
int toLeft = 0;
int toTop = getTitleBar().getHeight();
int toRight = mContentView.getWidth();
int width = target.getWidth();
int height = target.getHeight();
int[] pos = new int[2];
tabview.mImage.getLocationInWindow(pos);
int fromLeft = pos[0];
int fromTop = pos[1];
int fromRight = fromLeft + width;
int fromBottom = fromTop + height;
float scaleFactor = mContentView.getWidth() / (float) width;
int toBottom = (int) (height * scaleFactor);
screen.mMain.setAlpha(0f);
mCustomViewContainer.addView(screen.mMain, COVER_SCREEN_PARAMS);
AnimatorSet animSet = new AnimatorSet();
ObjectAnimator l = ObjectAnimator.ofInt(screen.mContent, "left",
fromLeft, toLeft);
ObjectAnimator t = ObjectAnimator.ofInt(screen.mContent, "top",
fromTop, toTop);
ObjectAnimator r = ObjectAnimator.ofInt(screen.mContent, "right",
fromRight, toRight);
ObjectAnimator b = ObjectAnimator.ofInt(screen.mContent, "bottom",
fromBottom, toBottom);
ObjectAnimator scale = ObjectAnimator.ofFloat(screen, "scaleFactor",
1f, scaleFactor);
ObjectAnimator alpha = ObjectAnimator.ofFloat(screen.mMain, "alpha", 1f, 1f);
ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
alpha.setStartDelay(100);
animSet.playTogether(l, t, r, b, scale, alpha, otheralpha);
animSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
mCustomViewContainer.removeView(screen.mMain);
finishAnimateOut();
mUiController.setBlockEvents(false);
}
});
animSet.setDuration(250);
animSet.start();
}
private void finishAnimateOut() {
mTabControl.setOnThumbnailUpdatedListener(null);
mCustomViewContainer.removeView(mNavScreen);
mCustomViewContainer.setAlpha(1f);
mNavScreen = null;
mCustomViewContainer.setVisibility(View.GONE);
}
@Override
public boolean needsRestoreAllTabs() {
return false;
}
public void toggleNavScreen() {
if (mNavScreen == null) {
showNavScreen();
} else {
hideNavScreen(false);
}
}
@Override
public boolean shouldCaptureThumbnails() {
return true;
}
static class AnimScreen {
private View mMain;
private ImageView mTitle;
private ImageView mContent;
private float mScale;
public AnimScreen(Context ctx, TitleBar tbar, WebView web) {
mMain = LayoutInflater.from(ctx).inflate(R.layout.anim_screen,
null);
mContent = (ImageView) mMain.findViewById(R.id.content);
mContent.setTop(tbar.getHeight());
mTitle = (ImageView) mMain.findViewById(R.id.title);
Bitmap bm1 = Bitmap.createBitmap(tbar.getWidth(), tbar.getHeight(),
Bitmap.Config.RGB_565);
Canvas c1 = new Canvas(bm1);
tbar.draw(c1);
mTitle.setImageBitmap(bm1);
int h = web.getHeight() - tbar.getHeight();
Bitmap bm2 = Bitmap.createBitmap(web.getWidth(), h,
Bitmap.Config.RGB_565);
Canvas c2 = new Canvas(bm2);
int tx = web.getScrollX();
int ty = web.getScrollY();
c2.translate(-tx, -ty - tbar.getHeight());
web.draw(c2);
mContent.setImageBitmap(bm2);
mContent.setScaleType(ImageView.ScaleType.MATRIX);
mContent.setImageMatrix(new Matrix());
mScale = 1.0f;
setScaleFactor(getScaleFactor());
}
public AnimScreen(Context ctx, Bitmap image) {
mMain = LayoutInflater.from(ctx).inflate(R.layout.anim_screen,
null);
mContent = (ImageView) mMain.findViewById(R.id.content);
mContent.setImageBitmap(image);
mContent.setScaleType(ImageView.ScaleType.MATRIX);
mContent.setImageMatrix(new Matrix());
mScale = 1.0f;
setScaleFactor(getScaleFactor());
}
public void setScaleFactor(float sf) {
mScale = sf;
Matrix m = new Matrix();
m.postScale(sf,sf);
mContent.setImageMatrix(m);
}
public float getScaleFactor() {
return mScale;
}
}
}
| false | true | void hideNavScreen(boolean animate) {
if (mNavScreen == null) return;
final Tab tab = mNavScreen.getSelectedTab();
if ((tab == null) || !animate) {
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
NavTabView tabview = (NavTabView) mNavScreen.getSelectedTabView();
if (tabview == null) {
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
mUiController.setBlockEvents(true);
mUiController.setActiveTab(tab);
mContentView.setVisibility(View.VISIBLE);
final AnimScreen screen = new AnimScreen(mActivity, tab.getScreenshot());
View target = ((NavTabView) mNavScreen.mScroller.getSelectedView()).mImage;
int toLeft = 0;
int toTop = getTitleBar().getHeight();
int toRight = mContentView.getWidth();
int width = target.getWidth();
int height = target.getHeight();
int[] pos = new int[2];
tabview.mImage.getLocationInWindow(pos);
int fromLeft = pos[0];
int fromTop = pos[1];
int fromRight = fromLeft + width;
int fromBottom = fromTop + height;
float scaleFactor = mContentView.getWidth() / (float) width;
int toBottom = (int) (height * scaleFactor);
screen.mMain.setAlpha(0f);
mCustomViewContainer.addView(screen.mMain, COVER_SCREEN_PARAMS);
AnimatorSet animSet = new AnimatorSet();
ObjectAnimator l = ObjectAnimator.ofInt(screen.mContent, "left",
fromLeft, toLeft);
ObjectAnimator t = ObjectAnimator.ofInt(screen.mContent, "top",
fromTop, toTop);
ObjectAnimator r = ObjectAnimator.ofInt(screen.mContent, "right",
fromRight, toRight);
ObjectAnimator b = ObjectAnimator.ofInt(screen.mContent, "bottom",
fromBottom, toBottom);
ObjectAnimator scale = ObjectAnimator.ofFloat(screen, "scaleFactor",
1f, scaleFactor);
ObjectAnimator alpha = ObjectAnimator.ofFloat(screen.mMain, "alpha", 1f, 1f);
ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
alpha.setStartDelay(100);
animSet.playTogether(l, t, r, b, scale, alpha, otheralpha);
animSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
mCustomViewContainer.removeView(screen.mMain);
finishAnimateOut();
mUiController.setBlockEvents(false);
}
});
animSet.setDuration(250);
animSet.start();
}
| void hideNavScreen(boolean animate) {
if (mNavScreen == null) return;
final Tab tab = mNavScreen.getSelectedTab();
if ((tab == null) || !animate) {
if (tab != null) {
setActiveTab(tab);
} else if (mTabControl.getTabCount() > 0) {
// use a fallback tab
setActiveTab(mTabControl.getCurrentTab());
}
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
NavTabView tabview = (NavTabView) mNavScreen.getSelectedTabView();
if (tabview == null) {
if (mTabControl.getTabCount() > 0) {
// use a fallback tab
setActiveTab(mTabControl.getCurrentTab());
}
mContentView.setVisibility(View.VISIBLE);
finishAnimateOut();
return;
}
mUiController.setBlockEvents(true);
mUiController.setActiveTab(tab);
mContentView.setVisibility(View.VISIBLE);
final AnimScreen screen = new AnimScreen(mActivity, tab.getScreenshot());
View target = ((NavTabView) mNavScreen.mScroller.getSelectedView()).mImage;
int toLeft = 0;
int toTop = getTitleBar().getHeight();
int toRight = mContentView.getWidth();
int width = target.getWidth();
int height = target.getHeight();
int[] pos = new int[2];
tabview.mImage.getLocationInWindow(pos);
int fromLeft = pos[0];
int fromTop = pos[1];
int fromRight = fromLeft + width;
int fromBottom = fromTop + height;
float scaleFactor = mContentView.getWidth() / (float) width;
int toBottom = (int) (height * scaleFactor);
screen.mMain.setAlpha(0f);
mCustomViewContainer.addView(screen.mMain, COVER_SCREEN_PARAMS);
AnimatorSet animSet = new AnimatorSet();
ObjectAnimator l = ObjectAnimator.ofInt(screen.mContent, "left",
fromLeft, toLeft);
ObjectAnimator t = ObjectAnimator.ofInt(screen.mContent, "top",
fromTop, toTop);
ObjectAnimator r = ObjectAnimator.ofInt(screen.mContent, "right",
fromRight, toRight);
ObjectAnimator b = ObjectAnimator.ofInt(screen.mContent, "bottom",
fromBottom, toBottom);
ObjectAnimator scale = ObjectAnimator.ofFloat(screen, "scaleFactor",
1f, scaleFactor);
ObjectAnimator alpha = ObjectAnimator.ofFloat(screen.mMain, "alpha", 1f, 1f);
ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
alpha.setStartDelay(100);
animSet.playTogether(l, t, r, b, scale, alpha, otheralpha);
animSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator anim) {
mCustomViewContainer.removeView(screen.mMain);
finishAnimateOut();
mUiController.setBlockEvents(false);
}
});
animSet.setDuration(250);
animSet.start();
}
|
diff --git a/src/com/behindthemirrors/minecraft/sRPG/DamageEventListener.java b/src/com/behindthemirrors/minecraft/sRPG/DamageEventListener.java
index 60d0335..989b44a 100644
--- a/src/com/behindthemirrors/minecraft/sRPG/DamageEventListener.java
+++ b/src/com/behindthemirrors/minecraft/sRPG/DamageEventListener.java
@@ -1,148 +1,146 @@
// thanks to
package com.behindthemirrors.minecraft.sRPG;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByProjectileEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.Material;
public class DamageEventListener extends EntityListener{
public boolean debug = false;
public static HashMap<String,Integer> damageTableMonsters;
public static HashMap<String,Integer> xpTableCreatures;
public static HashMap<String,Integer> damageTableTools;
public static int damageFists;
public static int damageBow;
public static double critChance;
public static double critMultiplier;
public static double missChance;
public static double missMultiplier;
public static boolean increaseDamageWithDepth;
public static ArrayList<int[]> depthTiers;
private HashMap<Integer,Player> damageTracking = new HashMap<Integer,Player>();
@Override
public void onEntityDamage(EntityDamageEvent event) {
String sourcename = "";
Entity source = null;
Player player = null;
Entity target = event.getEntity();
if (event.getCause() == DamageCause.FALL) {
if (target instanceof Player) {
PassiveAbility.trigger((Player)target, event);
}
} else if (event.getCause() == DamageCause.ENTITY_ATTACK) {
- // substring(5) to strip off the "Craft" in front of entity classes
- // distinction to account for different slime sizes and wolf states
if (event instanceof EntityDamageByEntityEvent) {
- source = (Player)((EntityDamageByEntityEvent)event).getDamager();
+ source = (Entity)((EntityDamageByEntityEvent)event).getDamager();
//} else if (event instanceof EntityDamageByProjectileEvent) {
// entity = ((EntityDamageByProjectileEvent)event).getDamager();
}
if (source != null) {
sourcename = Utility.getEntityName(source);
}
CombatInstance combat = new CombatInstance(event);
// damage from monsters
if (Settings.MONSTERS.contains(sourcename)) {
// for now no distinction between arrow hits and normal hits
combat.basedamage = damageTableMonsters.get(sourcename);
// depth modifier
if (increaseDamageWithDepth) {
for (int[] depth : depthTiers) {
if (((EntityDamageByEntityEvent)event).getDamager().getLocation().getY() < (double)depth[0]) {
combat.modifier += depth[1];
}
}
}
// damage from players
} else if (sourcename.equalsIgnoreCase("player") && event instanceof EntityDamageByEntityEvent) {
player = (Player)(((EntityDamageByEntityEvent)event).getDamager());
// debug message, displays remaining health of target before damage from this attack is applied
if (event.getEntity() instanceof Creature) {
if (debug) {
SRPG.output("Target of attack has "+((Creature)event.getEntity()).getHealth() + " health.");
}
}
// select damage value from config depending on what item is held
if (event instanceof EntityDamageByEntityEvent) {
Material material = player.getItemInHand().getType();
String toolName = Settings.TOOL_MATERIAL_TO_STRING.get(material);
if (toolName != null) {
combat.basedamage = damageTableTools.get(toolName);
// award charge tick
SRPG.playerDataManager.get(player).addChargeTick(Settings.TOOL_MATERIAL_TO_TOOL_GROUP.get(material));
//TODO: maybe move saving to the data class
SRPG.playerDataManager.save(player,"chargedata");
} else if (event instanceof EntityDamageByProjectileEvent) {
combat.basedamage = damageBow;
} else {
combat.basedamage = damageFists;
}
}
}
target = event.getEntity();
// check passive abilities
if (player != null) {
PassiveAbility.trigger(player, combat, true);
}
if (target instanceof Player) {
PassiveAbility.trigger((Player)target, combat, false);
}
// resolve combat
if (event instanceof EntityDamageByEntityEvent) {
combat.resolve(player);
}
// track entity if damage source was player, for xp gain on kill
int id = target.getEntityId();
if (!(target instanceof Player)) {
if (player != null) {
if (debug) {
SRPG.output("id of damaged entity: "+event.getEntity().getEntityId());
}
damageTracking.put(id, player);
} else if (damageTracking.containsKey(id)) {
damageTracking.remove(id);
}
}
}
}
// check if entity was tracked, and if yes give the player who killed it xp
public void onEntityDeath (EntityDeathEvent event) {
Entity entity = event.getEntity();
int id = entity.getEntityId();
if (debug) {
SRPG.output("entity with id "+id+" died");
}
if (damageTracking.containsKey(id)) {
String monster = Utility.getEntityName(entity);
SRPG.playerDataManager.get(damageTracking.get(id)).addXP(xpTableCreatures.get(monster));
//TODO: maybe move saving to the data class
SRPG.playerDataManager.save(damageTracking.get(id),"xp");
damageTracking.remove(id);
}
}
}
| false | true | public void onEntityDamage(EntityDamageEvent event) {
String sourcename = "";
Entity source = null;
Player player = null;
Entity target = event.getEntity();
if (event.getCause() == DamageCause.FALL) {
if (target instanceof Player) {
PassiveAbility.trigger((Player)target, event);
}
} else if (event.getCause() == DamageCause.ENTITY_ATTACK) {
// substring(5) to strip off the "Craft" in front of entity classes
// distinction to account for different slime sizes and wolf states
if (event instanceof EntityDamageByEntityEvent) {
source = (Player)((EntityDamageByEntityEvent)event).getDamager();
//} else if (event instanceof EntityDamageByProjectileEvent) {
// entity = ((EntityDamageByProjectileEvent)event).getDamager();
}
if (source != null) {
sourcename = Utility.getEntityName(source);
}
CombatInstance combat = new CombatInstance(event);
// damage from monsters
if (Settings.MONSTERS.contains(sourcename)) {
// for now no distinction between arrow hits and normal hits
combat.basedamage = damageTableMonsters.get(sourcename);
// depth modifier
if (increaseDamageWithDepth) {
for (int[] depth : depthTiers) {
if (((EntityDamageByEntityEvent)event).getDamager().getLocation().getY() < (double)depth[0]) {
combat.modifier += depth[1];
}
}
}
// damage from players
} else if (sourcename.equalsIgnoreCase("player") && event instanceof EntityDamageByEntityEvent) {
player = (Player)(((EntityDamageByEntityEvent)event).getDamager());
// debug message, displays remaining health of target before damage from this attack is applied
if (event.getEntity() instanceof Creature) {
if (debug) {
SRPG.output("Target of attack has "+((Creature)event.getEntity()).getHealth() + " health.");
}
}
// select damage value from config depending on what item is held
if (event instanceof EntityDamageByEntityEvent) {
Material material = player.getItemInHand().getType();
String toolName = Settings.TOOL_MATERIAL_TO_STRING.get(material);
if (toolName != null) {
combat.basedamage = damageTableTools.get(toolName);
// award charge tick
SRPG.playerDataManager.get(player).addChargeTick(Settings.TOOL_MATERIAL_TO_TOOL_GROUP.get(material));
//TODO: maybe move saving to the data class
SRPG.playerDataManager.save(player,"chargedata");
} else if (event instanceof EntityDamageByProjectileEvent) {
combat.basedamage = damageBow;
} else {
combat.basedamage = damageFists;
}
}
}
target = event.getEntity();
// check passive abilities
if (player != null) {
PassiveAbility.trigger(player, combat, true);
}
if (target instanceof Player) {
PassiveAbility.trigger((Player)target, combat, false);
}
// resolve combat
if (event instanceof EntityDamageByEntityEvent) {
combat.resolve(player);
}
// track entity if damage source was player, for xp gain on kill
int id = target.getEntityId();
if (!(target instanceof Player)) {
if (player != null) {
if (debug) {
SRPG.output("id of damaged entity: "+event.getEntity().getEntityId());
}
damageTracking.put(id, player);
} else if (damageTracking.containsKey(id)) {
damageTracking.remove(id);
}
}
}
}
| public void onEntityDamage(EntityDamageEvent event) {
String sourcename = "";
Entity source = null;
Player player = null;
Entity target = event.getEntity();
if (event.getCause() == DamageCause.FALL) {
if (target instanceof Player) {
PassiveAbility.trigger((Player)target, event);
}
} else if (event.getCause() == DamageCause.ENTITY_ATTACK) {
if (event instanceof EntityDamageByEntityEvent) {
source = (Entity)((EntityDamageByEntityEvent)event).getDamager();
//} else if (event instanceof EntityDamageByProjectileEvent) {
// entity = ((EntityDamageByProjectileEvent)event).getDamager();
}
if (source != null) {
sourcename = Utility.getEntityName(source);
}
CombatInstance combat = new CombatInstance(event);
// damage from monsters
if (Settings.MONSTERS.contains(sourcename)) {
// for now no distinction between arrow hits and normal hits
combat.basedamage = damageTableMonsters.get(sourcename);
// depth modifier
if (increaseDamageWithDepth) {
for (int[] depth : depthTiers) {
if (((EntityDamageByEntityEvent)event).getDamager().getLocation().getY() < (double)depth[0]) {
combat.modifier += depth[1];
}
}
}
// damage from players
} else if (sourcename.equalsIgnoreCase("player") && event instanceof EntityDamageByEntityEvent) {
player = (Player)(((EntityDamageByEntityEvent)event).getDamager());
// debug message, displays remaining health of target before damage from this attack is applied
if (event.getEntity() instanceof Creature) {
if (debug) {
SRPG.output("Target of attack has "+((Creature)event.getEntity()).getHealth() + " health.");
}
}
// select damage value from config depending on what item is held
if (event instanceof EntityDamageByEntityEvent) {
Material material = player.getItemInHand().getType();
String toolName = Settings.TOOL_MATERIAL_TO_STRING.get(material);
if (toolName != null) {
combat.basedamage = damageTableTools.get(toolName);
// award charge tick
SRPG.playerDataManager.get(player).addChargeTick(Settings.TOOL_MATERIAL_TO_TOOL_GROUP.get(material));
//TODO: maybe move saving to the data class
SRPG.playerDataManager.save(player,"chargedata");
} else if (event instanceof EntityDamageByProjectileEvent) {
combat.basedamage = damageBow;
} else {
combat.basedamage = damageFists;
}
}
}
target = event.getEntity();
// check passive abilities
if (player != null) {
PassiveAbility.trigger(player, combat, true);
}
if (target instanceof Player) {
PassiveAbility.trigger((Player)target, combat, false);
}
// resolve combat
if (event instanceof EntityDamageByEntityEvent) {
combat.resolve(player);
}
// track entity if damage source was player, for xp gain on kill
int id = target.getEntityId();
if (!(target instanceof Player)) {
if (player != null) {
if (debug) {
SRPG.output("id of damaged entity: "+event.getEntity().getEntityId());
}
damageTracking.put(id, player);
} else if (damageTracking.containsKey(id)) {
damageTracking.remove(id);
}
}
}
}
|
diff --git a/src/org/latte/LatteServlet.java b/src/org/latte/LatteServlet.java
index 64c0161..f29a923 100644
--- a/src/org/latte/LatteServlet.java
+++ b/src/org/latte/LatteServlet.java
@@ -1,95 +1,96 @@
package org.latte;
import org.latte.scripting.hostobjects.RequestProxy;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Logger;
import java.util.logging.Level;
import org.latte.scripting.PrimitiveWrapFactory;
import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.JavaScriptException;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.latte.scripting.Javascript;
import org.latte.scripting.ScriptLoader;
public class LatteServlet extends HttpServlet {
private static final Logger LOG = Logger.getLogger(LatteServlet.class.getName());
final private Scriptable parent;
private Callable fn;
private class Session extends ScriptableObject implements Serializable {
@Override
public String getClassName() {
return "Session";
}
}
public LatteServlet() throws Exception {
ScriptLoader loader = new ScriptLoader();
this.parent = loader.getRoot();
loader.register("httpserver", new Callable() {
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] params) {
fn = (Callable)params[1];
return null;
}
});
((Javascript)loader.get("init.js")).eval(null);
}
public LatteServlet(Scriptable parent, Callable fn) {
this.parent = parent;
this.fn = fn;
}
/**
*
*/
private static final long serialVersionUID = 5876743891237403945L;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Context cx = ContextFactory.getGlobal().enterContext();
Session session;
if((session = (Session)request.getSession().getAttribute("latte.session")) == null) {
session = new Session();
+ request.getSession().setAttribute("latte.session", session);
}
Scriptable scope = cx.newObject(parent);
scope.setParentScope(parent);
cx.setWrapFactory(new PrimitiveWrapFactory());
fn.call(cx, scope, scope, new Object[] {
new RequestProxy(request),
response,
session
});
} catch(Exception e) {
LOG.log(Level.SEVERE, "", e);
response.sendError(500);
} finally {
Context.exit();
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
| true | true | public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Context cx = ContextFactory.getGlobal().enterContext();
Session session;
if((session = (Session)request.getSession().getAttribute("latte.session")) == null) {
session = new Session();
}
Scriptable scope = cx.newObject(parent);
scope.setParentScope(parent);
cx.setWrapFactory(new PrimitiveWrapFactory());
fn.call(cx, scope, scope, new Object[] {
new RequestProxy(request),
response,
session
});
} catch(Exception e) {
LOG.log(Level.SEVERE, "", e);
response.sendError(500);
} finally {
Context.exit();
}
}
| public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Context cx = ContextFactory.getGlobal().enterContext();
Session session;
if((session = (Session)request.getSession().getAttribute("latte.session")) == null) {
session = new Session();
request.getSession().setAttribute("latte.session", session);
}
Scriptable scope = cx.newObject(parent);
scope.setParentScope(parent);
cx.setWrapFactory(new PrimitiveWrapFactory());
fn.call(cx, scope, scope, new Object[] {
new RequestProxy(request),
response,
session
});
} catch(Exception e) {
LOG.log(Level.SEVERE, "", e);
response.sendError(500);
} finally {
Context.exit();
}
}
|
diff --git a/src/com/athena/asm/util/SmthSupport.java b/src/com/athena/asm/util/SmthSupport.java
index e00b4ff..e27ee7d 100644
--- a/src/com/athena/asm/util/SmthSupport.java
+++ b/src/com/athena/asm/util/SmthSupport.java
@@ -1,1568 +1,1568 @@
package com.athena.asm.util;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.text.Html;
import android.util.Log;
import com.athena.asm.aSMApplication;
import com.athena.asm.data.Attachment;
import com.athena.asm.data.Board;
import com.athena.asm.data.Mail;
import com.athena.asm.data.MailBox;
import com.athena.asm.data.Post;
import com.athena.asm.data.Profile;
import com.athena.asm.data.Subject;
import com.athena.asm.fragment.SubjectListFragment;
import com.athena.asm.viewmodel.MailViewModel;
public class SmthSupport {
public String userid;
private String passwd;
private boolean loginned;
SmthCrawler crawler;
private static class Holder {
private static SmthSupport instance = new SmthSupport();
}
public static SmthSupport getInstance() {
return Holder.instance;
}
private SmthSupport() {
crawler = SmthCrawler.getIntance();
}
public void restore() {
if (crawler.isDestroy()) {
crawler.init();
}
}
public boolean getLoginStatus() {
return loginned;
}
/**
* 登录.
*/
public int login() {
loginned = true;
return crawler.login(userid, passwd);
}
/**
* 退出登录.
*/
public void logout() {
if (loginned) {
crawler.getUrlContent("http://www.newsmth.net/bbslogout.php");
loginned = false;
}
}
/**
* 退出登录,并关闭httpclient
*/
public void destory() {
logout();
crawler.destroy();
}
public boolean uploadAttachFile(File file) {
return crawler.uploadAttachFile(file);
}
public boolean sendMail(String mailUrl, String mailTitle, String userid,
String num, String dir, String file, String signature,
String mailContent) {
return crawler.sendMail(mailUrl, mailTitle, userid, num, dir, file,
signature, mailContent);
}
public boolean sendPost(String postUrl, String postTitle,
String postContent, String signature, boolean isEdit) {
return crawler.sendPost(postUrl, postTitle, postContent, signature,
isEdit);
}
public String getUrlContent(String urlString) {
return crawler.getUrlContent(urlString);
}
/**
* 获得首页导读.
*
* @return
*/
public Object[] getGuidance() {
String content = crawler
.getUrlContent("http://www.newsmth.net/mainpage.html");
Pattern hp = Pattern.compile(
"<table [^<>]+class=\"HotTable\"[^<>]+>(.*?)</table>",
Pattern.DOTALL);
if (content == null) {
return new Object[] { Collections.emptyList(),
Collections.emptyList() };
}
Matcher hm = hp.matcher(content);
List<String> sectionList = new ArrayList<String>();
List<List<Subject>> subjectList = new ArrayList<List<Subject>>();
if (hm.find()) {
sectionList.add("水木十大");
String hc = hm.group(1);
Pattern boardNamePattern = Pattern
.compile("<a href=\"bbsdoc.php\\?board=\\w+\">([^<>]+)</a>");
Matcher boardNameMatcher = boardNamePattern.matcher(hc);
Pattern hip = Pattern
.compile("<a href=\"bbstcon.php\\?board=(\\w+)&gid=(\\d+)\">([^<>]+)</a>");
Matcher him = hip.matcher(hc);
Pattern hIdPattern = Pattern
.compile("<a href=\"bbsqry.php\\?userid=(\\w+)\">");
Matcher hIdMatcher = hIdPattern.matcher(hc);
List<Subject> list = new ArrayList<Subject>();
while (him.find() && hIdMatcher.find()) {
Subject subject = new Subject();
if (boardNameMatcher.find()) {
subject.setBoardChsName(boardNameMatcher.group(1));
}
subject.setBoardEngName(him.group(1));
subject.setSubjectID(him.group(2));
subject.setTitle(him.group(3));
subject.setAuthor(hIdMatcher.group(1));
list.add(subject);
}
subjectList.add(list);
}
Pattern sp = Pattern
.compile(
"<span class=\"SectionName\"><a[^<>]+>([^<>]+)</a></span>(.*?)class=\"SecLine\"></td>",
Pattern.DOTALL);
Matcher sm = sp.matcher(content);
while (sm.find()) {
String sectionName = sm.group(1);
sectionList.add(sectionName);
String sc = sm.group(2);
// System.out.println(sectionName);
Pattern boardNamePattern = Pattern
.compile("\"SectionItem\">.<a href=\"bbsdoc.php\\?board=\\w+\">([^<>]+)</a>");
Matcher boardNameMatcher = boardNamePattern.matcher(sc);
Pattern sip = Pattern
.compile("<a href=\"bbstcon.php\\?board=(\\w+)&gid=(\\d+)\">([^<>]+)</a>");
Matcher sim = sip.matcher(sc);
List<Subject> list = new ArrayList<Subject>();
while (sim.find()) {
Subject subject = new Subject();
if (boardNameMatcher.find()) {
subject.setBoardChsName(boardNameMatcher.group(1));
}
subject.setBoardEngName(sim.group(1));
subject.setSubjectID(sim.group(2));
subject.setTitle(sim.group(3));
list.add(subject);
}
subjectList.add(list);
}
return new Object[] { sectionList, subjectList };
}
/**
* 获取版面收藏列表. type用来区别版面自己是不是目录
*
* @return
*/
public void getFavorite(String id, List<Board> boardList, int type) {
String url;
if (type == 0) {
url = "http://www.newsmth.net/bbsfav.php?select=" + id;
} else {
url = "http://www.newsmth.net/bbsdoc.php?board=" + id;
}
String content = crawler.getUrlContent(url);
if (content == null) {
return;
}
// 先提取目录
String patternStr = "o\\.f\\((\\d+),'([^']+)',\\d+,''\\);";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(content);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
list.add(matcher.group(1));
Board board = new Board();
board.setDirectory(true);
board.setDirectoryName(matcher.group(2));
board.setCategoryName("目录");
boardList.add(board);
}
for (int i = 0; i < list.size(); i++) {
getFavorite(list.get(i), boardList.get(i).getChildBoards(), 0);
}
// o.o(false,1,998,22156,'[站务]','Ask','新用户疑难解答','haning BJH',733,997,0);
patternStr = "o\\.o\\(\\w+,\\d+,(\\d+),\\d+,'([^']+)','([^']+)','([^']+)','([^']*)',\\d+,\\d+,\\d+\\)";
pattern = Pattern.compile(patternStr);
matcher = pattern.matcher(content);
while (matcher.find()) {
String boardID = matcher.group(1);
String category = matcher.group(2);
String engName = matcher.group(3);
String chsName = matcher.group(4);
String moderator = matcher.group(5);
if (moderator.length() > 25) {
moderator = moderator.substring(0, 21) + "...";
}
Board board = new Board();
board.setDirectory(false);
board.setBoardID(boardID);
board.setCategoryName(category);
board.setEngName(engName);
board.setChsName(chsName);
board.setModerator(moderator);
if (moderator.contains("[目录]")) {
board.setDirectory(true);
board.setDirectoryName(chsName);
getFavorite(engName, board.getChildBoards(), 1);
}
boardList.add(board);
}
}
public String checkNewReplyOrAt() {
String result = null;
String content = crawler
.getUrlContentFromMobile("http://m.newsmth.net/");
if (content != null) {
if (content.contains(">@我(")) {
result = "新@";
} else if (content.contains(">回我(")) {
result = "新回复";
}
}
return result;
}
public boolean checkNewMail() {
String content = crawler
.getUrlContentFromMobile("http://m.newsmth.net/");
if (content == null) {
return false;
}
if (content.contains("邮箱(新)")) {
return true;
} else {
return false;
}
}
public void markAllMessageRead(int type) {
String url = "";
if (type == 0) {
url = "http://m.newsmth.net/refer/at/read?index=all";
} else {
url = "http://m.newsmth.net/refer/reply/read?index=all";
}
crawler.getUrlContentFromMobile(url);
}
/**
* 获取邮箱信息
*
* @return
*/
public MailBox getMailBoxInfo() {
MailBox mailBox = new MailBox();
String content = crawler
.getUrlContent("http://www.newsmth.net/bbsmail.php");
if (content == null) {
return null;
}
if (content.contains("您有未读邮件")) {
mailBox.setHavingNewMail(true);
} else {
mailBox.setHavingNewMail(false);
}
Pattern inboxPattern = Pattern
.compile("<td><a href=\"bbsmailbox.php\\?path=\\.DIR&title=%CA%D5%BC%FE%CF%E4\" class=\"ts2\">[^<>]+</a></td>\\s<td>(\\d+)</td>");
Matcher inboxMatcher = inboxPattern.matcher(content);
while (inboxMatcher.find()) {
mailBox.setInboxNumber(Integer.parseInt(inboxMatcher.group(1)));
}
Pattern outboxPattern = Pattern
.compile("<td><a href=\"bbsmailbox.php\\?path=\\.SENT&title=%B7%A2%BC%FE%CF%E4\" class=\"ts2\">[^<>]+</a></td>\\s<td>(\\d+)</td>");
Matcher outboxMatcher = outboxPattern.matcher(content);
while (outboxMatcher.find()) {
mailBox.setOutboxNumber(Integer.parseInt(outboxMatcher.group(1)));
}
Pattern trashboxPattern = Pattern
.compile("<td><a href=\"bbsmailbox.php\\?path=\\.DELETED&title=%C0%AC%BB%F8%CF%E4\" class=\"ts2\">[^<>]+</a></td>\\s<td>(\\d+)</td>");
Matcher trashboxMatcher = trashboxPattern.matcher(content);
while (trashboxMatcher.find()) {
mailBox.setTrashboxNumber(Integer.parseInt(trashboxMatcher.group(1)));
}
content = crawler
.getUrlContentFromMobile("http://m.newsmth.net/refer/at");
if (content != null) {
if (content.contains(">@我(")) {
mailBox.setHavingNewAt(true);
} else if (content.contains(">回我(")) {
mailBox.setHavingNewReply(true);
}
}
return mailBox;
}
/**
* 取得邮件标题列表
*
* @param boxType
* @param startNumber
* @return
*/
public List<Mail> getMailList(int boxType, int startNumber) {
String urlString = "http://www.newsmth.net/bbsmailbox.php?";
String boxString = "";
String boxDirString = "";
String startString = "";
if (startNumber != -1) {
startString += "&start=" + startNumber;
}
switch (boxType) {
case 0:
urlString += "path=.DIR" + startString
+ "&title=%CA%D5%BC%FE%CF%E4";
boxString = "%CA%D5%BC%FE%CF%E4";
boxDirString = ".DIR";
break;
case 1:
urlString += "path=.SENT" + startString
+ "&title=%B7%A2%BC%FE%CF%E4";
boxString = "%B7%A2%BC%FE%CF%E4";
boxDirString = ".SENT";
break;
case 2:
urlString += "path=.DELETED" + startString
+ "&title=%C0%AC%BB%F8%CF%E4";
boxString = "%C0%AC%BB%F8%CF%E4";
boxDirString = ".DELETED";
break;
default:
break;
}
List<Mail> mailList = new ArrayList<Mail>();
String result = crawler.getUrlContent(urlString);
if (result == null) {
return Collections.emptyList();
}
int counter = 0;
String matchString = "";
String numberAndDatePatternString = "<td class=\"mt3\">([^<>]+)</td>";
Pattern numberAndDatePattern = Pattern
.compile(numberAndDatePatternString);
Matcher numberAndDateMatcher = numberAndDatePattern.matcher(result);
while (numberAndDateMatcher.find()) {
matchString = numberAndDateMatcher.group(1);
int number = Integer.parseInt(matchString) - 1;
numberAndDateMatcher.find();
matchString = numberAndDateMatcher.group(1);
Mail mail = new Mail();
mail.setBoxString(boxString);
mail.setBoxType(boxType);
mail.setBoxDirString(boxDirString);
mail.setNumber(number);
mail.setDateString(matchString.replaceAll(" ", " ").trim());
mailList.add(mail);
}
String isUnreadPatternString = "<img src='images/(\\w+).gif'[^<>]+>";
Pattern isUnreadPattern = Pattern.compile(isUnreadPatternString);
Matcher isUnreadMatcher = isUnreadPattern.matcher(result);
while (isUnreadMatcher.find()) {
matchString = isUnreadMatcher.group(1);
Mail mail = mailList.get(counter);
if (matchString.contains("omail")) {
mail.setUnread(false);
} else {
mail.setUnread(true);
}
counter++;
}
counter = 0;
String valuePatternString = "<input type=\"checkbox\"[^<>]+value=\"([^<>]+)\">";
Pattern valuePattern = Pattern.compile(valuePatternString);
Matcher valueMatcher = valuePattern.matcher(result);
while (valueMatcher.find()) {
matchString = valueMatcher.group(1);
Mail mail = mailList.get(counter);
mail.setValueString(matchString);
counter++;
}
counter = 0;
String statusPatternString = "<td class=\"mt4\"><nobr>([^<>]+)</nobr></td>";
Pattern statusPattern = Pattern.compile(statusPatternString);
Matcher statusMatcher = statusPattern.matcher(result);
while (statusMatcher.find()) {
matchString = statusMatcher.group(1);
Mail mail = mailList.get(counter);
mail.setStatus(matchString.replaceAll(" ", "").trim());
counter++;
}
counter = 0;
String senderPatternString = "<td class=\"mt3\"><a href=\"bbsqry.php\\?userid=([^<>]+)\">[^<>]+</a></td>";
Pattern senderPattern = Pattern.compile(senderPatternString);
Matcher senderMatcher = senderPattern.matcher(result);
while (senderMatcher.find()) {
matchString = senderMatcher.group(1);
Mail mail = mailList.get(counter);
mail.setSenderID(matchString);
counter++;
}
counter = 0;
String titlePatternString = "<td class=\"mt5\"> <a[^<>]+>([^<>]+)</a></td>";
Pattern titlePattern = Pattern.compile(titlePatternString);
Matcher titleMatcher = titlePattern.matcher(result);
while (titleMatcher.find()) {
matchString = titleMatcher.group(1);
Mail mail = mailList.get(counter);
mail.setTitle(matchString.trim());
counter++;
}
counter = 0;
String sizePatternString = "<td class=\"mt3\" style=[^<>]+>(\\d+)</td>";
Pattern sizePattern = Pattern.compile(sizePatternString);
Matcher sizeMatcher = sizePattern.matcher(result);
while (sizeMatcher.find()) {
matchString = sizeMatcher.group(1);
Mail mail = mailList.get(counter);
mail.setSizeString(matchString);
counter++;
}
return mailList;
}
public List<Mail> getReplyOrAtList(MailViewModel mailViewModel,
int boxType, int startNumber) {
String urlString = "";
switch (boxType) {
case 4:
urlString = "http://m.newsmth.net/refer/at";
break;
case 5:
urlString = "http://m.newsmth.net/refer/reply";
break;
default:
break;
}
if (startNumber != -1) {
urlString += "?p=" + startNumber;
}
List<Mail> mailList = new ArrayList<Mail>();
String result = crawler.getUrlContentFromMobile(urlString);
if (result == null) {
return Collections.emptyList();
}
// <div><a href="/refer/reply/read?index=
Pattern itemPattern;
if (boxType == 4) {
itemPattern = Pattern
.compile("<div><a href=\"/refer/at/read\\?index=(\\d+)\"([^<>]*)>([^<>]+)");
} else {
itemPattern = Pattern
.compile("<div><a href=\"/refer/reply/read\\?index=(\\d+)\"([^<>]*)>([^<>]+)");
}
Matcher itemMatcher = itemPattern.matcher(result);
while (itemMatcher.find()) {
Mail mail = new Mail();
mail.setBoxType(boxType);
int number = Integer.parseInt(itemMatcher.group(1));
mail.setNumber(number);
if (itemMatcher.groupCount() == 2) {
mail.setUnread(false);
mail.setTitle(itemMatcher.group(2));
} else {
String type = itemMatcher.group(2);
if (type.contains("top")) {
mail.setUnread(true);
} else {
mail.setUnread(false);
}
mail.setTitle(itemMatcher.group(3));
}
mailList.add(mail);
}
// 2012-05-28<a href="/user/query/
Pattern userIDPattern = Pattern
.compile("([^<>]+)<a href=\"/user/query/([^<>]+)\"");
Matcher userIDMatcher = userIDPattern.matcher(result);
int index = 0;
while (userIDMatcher.find()) {
String dateString = userIDMatcher.group(1).trim();
mailList.get(index).setDateString(dateString.replace(" ", ""));
mailList.get(index).setSenderID(userIDMatcher.group(2));
index++;
}
// / <a class="plant">1/1272</a>
Pattern pagePattern = Pattern
.compile("<a class=\"plant\">(\\d+)/(\\d+)");
Matcher pageMatcher = pagePattern.matcher(result);
if (pageMatcher.find()) {
mailViewModel.setCurrentPageNo(Integer.parseInt(pageMatcher
.group(1)));
mailViewModel
.setTotalPageNo(Integer.parseInt(pageMatcher.group(2)));
}
return mailList;
}
public void getMailContent(Mail mail) {
String boxTypeString = "";
switch (mail.getBoxType()) {
case 0:
boxTypeString = ".DIR";
break;
case 1:
boxTypeString = ".SENT";
break;
case 2:
boxTypeString = ".DELETED";
break;
default:
break;
}
String url = "http://www.newsmth.net/bbsmailcon.php?dir="
+ boxTypeString + "&num=" + mail.getNumber() + "&title="
+ mail.getBoxString();
String result = crawler.getUrlContent(url);
if (result == null) {
mail.setContent("加载失败");
mail.setDate(new Date());
} else {
Pattern contentPattern = Pattern.compile("prints\\('(.*?)'\\);",
Pattern.DOTALL);
Matcher contentMatcher = contentPattern.matcher(result);
if (contentMatcher.find()) {
String contentString = contentMatcher.group(1);
Object[] objects = StringUtility
.parsePostContent(contentString);
mail.setContent((String) objects[0]);
mail.setDate((java.util.Date) objects[1]);
}
}
}
/**
* 获取分类讨论区列表
*
* @return
*/
public void getCategory(String id, List<Board> boardList, boolean isFolder) {
// http://www.newsmth.net/bbsfav.php?x
// there are three kinds of items in category: folder, group, board
// 1. folder
// o.f(1,'系统 水木社区系统版面 ',0,'NewSMTH.net');
// http://www.newsmth.net/bbsfav.php?select=1&x
// 2. group
// o.o(true,1,502,356446,'[站务]','BBSData','社区系统数据','[目录]',10,501,0);
// http://www.newsmth.net/bbsboa.php?group=0&group2=502
// 3. board
// o.o(false,1,104,27745,'[出国]','AdvancedEdu','飞跃重洋','LSAT madonion
// Mperson',22553,103,25);
// http://www.newsmth.net/bbsdoc.php?board=AdvancedEdu
String url;
if (id.equals("TOP")) {
url = "http://www.newsmth.net/bbsfav.php?x";
} else if (isFolder) {
// 1. folder
url = "http://www.newsmth.net/bbsfav.php?select=" + id + "&x";
} else {
// 2. group
url = "http://www.newsmth.net/bbsboa.php?group=0&group2=" + id;
}
String content = crawler.getUrlContent(url);
if (content == null) {
return;
}
// 先提取folder
String patternStr = "o\\.f\\((\\d+),'([^']+)',\\d+,'([^']+)'\\);";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
// Log.d("Find folder", matcher.group(2));
getCategory(matcher.group(1), boardList, true);
}
// 再寻找board和group
patternStr = "o\\.o\\((\\w+),\\d+,(\\d+),\\d+,'([^']+)','([^']+)','([^']+)','([^']*)',\\d+,\\d+,\\d+\\)";
pattern = Pattern.compile(patternStr);
matcher = pattern.matcher(content);
while (matcher.find()) {
String isGroup = matcher.group(1);
String boardID = matcher.group(2);
String category = matcher.group(3);
String engName = matcher.group(4);
String chsName = matcher.group(5);
String moderator = matcher.group(6);
if (moderator.length() > 25) {
moderator = moderator.substring(0, 21) + "...";
}
if (isGroup.equals("true")) {
// find group, add its child boards recursively
// Log.d("find Group", engName);
getCategory(boardID, boardList, false);
} else {
// Log.d("find Board", engName);
Board board = new Board();
board.setBoardID(boardID);
board.setCategoryName(category);
board.setEngName(engName);
board.setChsName(chsName);
board.setModerator(moderator);
boardList.add(board);
}
}
}
/**
* 获取经过过滤的主题列表.
*
* @return
*/
public List<Subject> getSearchSubjectList(String boardName, String boardID,
String queryString) {
String url = "http://www.newsmth.net/bbsbfind.php?q=1&" + queryString;
String result = crawler.getUrlContent(url);
if (result == null) {
return Collections.emptyList();
}
String patternStr = "ta\\.r\\('[^']+','([^']+)','<a href=\"bbsqry.php\\?userid=(\\w+)\">\\w+</a>','([^']+)','<a href=\"bbscon.php\\?bid=(\\d+)&id=(\\d+)\">([^<>]+)</a>'\\);";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(result);
List<Subject> subjectList = new ArrayList<Subject>();
while (matcher.find()) {
String type = matcher.group(1).trim();
String author = matcher.group(2);
String dateStr = matcher.group(3).replace(" ", " ");
// SimpleDateFormat formatter = new SimpleDateFormat("MMM dd",
// Locale.US);
// Date date;
// try {
// date = formatter.parse(dateStr);
// } catch (ParseException e) {
// date = new Date();
// }
String boardid = matcher.group(4);
String subjectid = matcher.group(5);
String title = matcher.group(6);
Subject subject = new Subject();
subject.setAuthor(author);
subject.setBoardID(boardID);
subject.setBoardEngName(boardName);
subject.setBoardID(boardid);
subject.setSubjectID(subjectid);
subject.setTitle(title);
subject.setType(type);
subject.setDateString(dateStr);
subjectList.add(subject);
}
return subjectList;
}
/**
* 获取版面主题列表.
*
* @return
*/
public List<Subject> getSubjectListFromMobile(Board board, int boardType,
boolean isReloadPageNo, ArrayList<String> blackList) {
String boardname = board.getEngName();
int pageno = board.getCurrentPageNo();
if (isReloadPageNo) {
pageno = 0;
}
String result = getMainSubjectListFromMobile(boardname, pageno,
boardType);
if (result == null) {
return Collections.emptyList();
}
List<Subject> subjectList = new ArrayList<Subject>();
// <a class="plant">1/1272</a> 当前页/总共页
Pattern pagePattern = Pattern
.compile("<a class=\"plant\">(\\d+)/(\\d+)");
Matcher pageMatcher = pagePattern.matcher(result);
if (pageMatcher.find()) {
board.setCurrentPageNo(Integer.parseInt(pageMatcher.group(1)));
board.setTotalPageNo(Integer.parseInt(pageMatcher.group(2)));
}
// 同主题模式, 主题后面有(NNN), 两个作者
// <div><a href="/article/DC/423562"
// class="m">如了个3D相机,FUJI-REAL3D-W3</a>(1)</div><div>2013-02-06 <a
// href="/user/query/penwall">penwall</a>|2013-02-06 <a
// href="/user/query/DRAGON9">DRAGON9</a></div>
// 其他模式
// <div><a
// href="/article/DC/single/2515/1">● 如了个3D相机,FUJI-REAL3D-W3</a></div><div>2515 2013-02-06 <a
// href="/user/query/penwall">penwall</a></div>
// 置顶的帖子, class="top"
// <div><a href="/article/DC/419129"
// class="top">审核通过DC版治版方针</a>(0)</div><div>2012-12-22 <a
// href="/user/query/SYSOP">SYSOP</a>|2012-12-22 <a
// href="/user/query/SYSOP">SYSOP</a></div>
// 2013-02-06 <a href="/user/query/penwall">penwall</a>
Pattern userIDPattern = Pattern
.compile("([^<>]+)<a href=\"/user/query/([^<>]+)\"");
Matcher userIDMatcher = userIDPattern.matcher(result);
int index = 1;
while (userIDMatcher.find()) {
// subject mode has two author info per subject
index = 1 - index;
if (boardType == SubjectListFragment.BOARD_TYPE_SUBJECT
&& index == 1)
continue;
Subject subject = new Subject();
String dateString = userIDMatcher.group(1).trim();
String[] dates = dateString.split(" ");
if (dates.length < 2) {
subject.setDateString(dates[0]);
} else {
subject.setDateString(dates[1]);
}
// subject.setDateString(dateString.replace(" ", ""));
subject.setAuthor(userIDMatcher.group(2));
subject.setBoardID(board.getBoardID());
subject.setBoardEngName(boardname);
subject.setCurrentPageNo(1);
subject.setType(" ");
subjectList.add(subject);
}
// <div><a href="/article/DC/423562"
// class="m">如了个3D相机,FUJI-REAL3D-W3</a>(1)</div>
// <div><a
// href="/article/DC/single/2515/1">● 如了个3D相机,FUJI-REAL3D-W3</a></div>
String subPattern1 = "";
String subPattern2 = "";
if (boardType != SubjectListFragment.BOARD_TYPE_SUBJECT) {
boardname = boardname + "/single";
}
if (boardType == SubjectListFragment.BOARD_TYPE_NORMAL) {
subPattern1 = "/0";
} else if (boardType == SubjectListFragment.BOARD_TYPE_DIGEST) {
subPattern1 = "/1";
} else if (boardType == SubjectListFragment.BOARD_TYPE_MARK) {
subPattern1 = "/3";
}
if (boardType == SubjectListFragment.BOARD_TYPE_SUBJECT) {
subPattern2 = "\\((\\d+)\\)";
}
Pattern subjectPattern = Pattern.compile("<div><a href=\"/article/"
+ boardname + "/(\\d+)" + subPattern1
+ "\"([^<>]*)>([^<>]+)</a>" + subPattern2);
// Log.d("getSubjectListFromMobile RE", subjectPattern.pattern());
Matcher subjectMatcher = subjectPattern.matcher(result);
index = 0;
while (subjectMatcher.find()) {
// Log.d("getSubjectListFromMobile result",
// subjectMatcher.group(0));
if (subjectMatcher.groupCount() == 2) {
subjectList.get(index).setSubjectID(subjectMatcher.group(1));
subjectList.get(index).setTitle(subjectMatcher.group(2));
} else {
String type = subjectMatcher.group(2);
if (type.contains("top")) {
// 置顶的帖子
subjectList.get(index).setType(Subject.TYPE_BOTTOM);
}
subjectList.get(index).setSubjectID(subjectMatcher.group(1));
// add replied number after subject title in SUBJECT mode
String subjectTitle = "null";
if (boardType == SubjectListFragment.BOARD_TYPE_SUBJECT)
subjectTitle = subjectMatcher.group(3) + " ("
+ subjectMatcher.group(4) + ")";
else
subjectTitle = subjectMatcher.group(3);
subjectList.get(index).setTitle(subjectTitle);
}
index++;
if (index > subjectList.size()) {
break;
}
}
if (aSMApplication.getCurrentApplication().isHidePinSubject()) {
for (Iterator<Subject> iterator = subjectList.iterator(); iterator
.hasNext();) {
Subject subject = (Subject) iterator.next();
if (subject.getType().equals(Subject.TYPE_BOTTOM)) {
iterator.remove();
}
}
}
return subjectList;
}
/**
*
*
* @return
*/
public List<Post> getSinglePostListFromMobileUrl(Subject subject, String url) {
String result = crawler.getUrlContentFromMobile(url);
if (result == null || result.contains("指定的文章不存在或链接错误")
|| result.contains("您无权阅读此版面")) {
return null;
}
List<Post> postList = new ArrayList<Post>();
Post post = new Post();
// <a href="/article/NewSoftware/single/68557">楼主
Pattern infoPattern = Pattern
.compile("<a href=\"/article/([^<>]+)/single/(\\d+)\">楼主");
Matcher infoMatcher = infoPattern.matcher(result);
if (infoMatcher.find()) {
subject.setBoardEngName(infoMatcher.group(1));
subject.setTopicSubjectID(infoMatcher.group(2));
subject.setCurrentPageNo(1);
subject.setType(" ");
}
// subject.setBoardID(board.getBoardID());
// <a userid href="/user/query/
Pattern userIDPattern = Pattern
.compile("<a href=\"/user/query/([^<>]+)\"");
Matcher userIDMatcher = userIDPattern.matcher(result);
if (userIDMatcher.find()) {
post.setTopicSubjectID(subject.getTopicSubjectID());
post.setBoardID(subject.getBoardID());
post.setBoard(subject.getBoardEngName());
String author = userIDMatcher.group(1);
post.setAuthor(author);
subject.setAuthor(author);
}
// <a href="/article/NewExpress/post/11111">回复
Pattern subjectPattern = Pattern.compile("<a href=\"/article/"
+ subject.getBoardEngName() + "/post/(\\d+)\\?s=1\"");
Matcher subjectMatcher = subjectPattern.matcher(result);
if (subjectMatcher.find()) {
post.setSubjectID(subjectMatcher.group(1));
subject.setSubjectID(post.getSubjectID());
}
// <a class="plant">2012-02-23 00:16:41</a>
Pattern datePattern = Pattern
.compile("<a class=\"plant\">(\\d)([^<>]+)</a>");
Matcher dateMatcher = datePattern.matcher(result);
if (dateMatcher.find()) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
post.setDate((java.util.Date) sdf.parse(dateMatcher.group(1)
+ dateMatcher.group(2)));
subject.setDateString(dateMatcher.group(1)
+ dateMatcher.group(2));
} catch (ParseException e) {
e.printStackTrace();
}
}
// <li class="f">title</li>
Pattern titlePattern = Pattern.compile("<li class=\"f\">([^<>]+)</li>");
Matcher titleMatcher = titlePattern.matcher(result);
String titleString = "";
if (titleMatcher.find()) {
titleString = Html.fromHtml(titleMatcher.group(1)).toString();
post.setTitle(titleString);
subject.setTitle(titleString);
}
// post content
Pattern contentPattern = Pattern
.compile("<div class=\"sp\">(.*?)</div>");
Matcher contentMatcher = contentPattern.matcher(result);
if (contentMatcher.find()) {
String contentString = contentMatcher.group(1);
Object[] objects = StringUtility
.parseMobilePostContent(contentString);
post.setContent((String) objects[0]);
ArrayList<Attachment> attachFiles = new ArrayList<Attachment>();
ArrayList<String> attachList = (ArrayList<String>) objects[1];
for (Iterator<String> iterator = attachList.iterator(); iterator
.hasNext();) {
String attach = (String) iterator.next();
Attachment innerAtt = new Attachment();
if (attach.contains("<img")) {
Pattern urlPattern = Pattern
.compile("<a target=\"_blank\" href=\"([^<>]+)\"");
Matcher urlMatcher = urlPattern.matcher(attach);
if (urlMatcher.find()) {
String urlString = urlMatcher.group(1);
innerAtt.setMobileUrlString(urlString);
innerAtt.setName(urlString.substring(urlString
.lastIndexOf("/") + 1) + ".jpg");
}
} else {
Pattern urlPattern = Pattern
.compile("<a href=\"([^<>]+)\">([^<>]+)</a>");
Matcher urlMatcher = urlPattern.matcher(attach);
if (urlMatcher.find()) {
innerAtt.setMobileUrlString(urlMatcher.group(1));
innerAtt.setName(urlMatcher.group(2));
}
}
innerAtt.setMobileType(true);
attachFiles.add(innerAtt);
}
post.setAttachFiles(attachFiles);
}
postList.add(post);
return postList;
}
/**
* 获取单贴内容
*
* @param subject
* @return
*/
public List<Post> getSinglePostList(Subject subject) {
// String result = getPostContent(subject.getBoardID(),
// subject.getSubjectID());
List<Post> postList = new ArrayList<Post>();
Post post = new Post();
post.setAuthor(subject.getAuthor());
post.setSubjectID(subject.getSubjectID());
post.setBoardID(subject.getBoardID());
post.setBoard(subject.getBoardEngName());
postList.add(post);
crawler.getPostList(postList);
subject.setTopicSubjectID(post.getTopicSubjectID());
return postList;
}
public List<Post> getTopicPostList(Subject subject, int action) {
List<Post> postList = new ArrayList<Post>();
String url = "http://www.newsmth.net/bbscon.php?bid="
+ subject.getBoardID() + "&id=";
if (action == 1) {
url += subject.getTopicSubjectID();
} else {
url += subject.getSubjectID();
if (action == 2) {
url += "&p=tp";
} else {
url += "&p=tn";
}
}
String content = crawler.getUrlContent(url);
if (content == null) {
return null;
}
Post post = new Post();
post.setBoardID(subject.getBoardID());
post.setBoard(subject.getBoardEngName());
Pattern contentPattern = Pattern.compile("prints\\('(.*?)'\\);",
Pattern.DOTALL);
Pattern infoPattern = Pattern
.compile("conWriter\\(\\d+, '[^']+', \\d+, (\\d+), (\\d+), (\\d+), '[^']+', (\\d+), \\d+,'([^']+)'\\);");
Matcher contentMatcher = contentPattern.matcher(content);
if (contentMatcher.find()) {
String contentString = contentMatcher.group(1);
Object[] objects = StringUtility.parsePostContent(contentString);
post.setContent((String) objects[0]);
post.setDate((java.util.Date) objects[1]);
int index1 = contentString.indexOf("发信人:");
int index2 = contentString.indexOf("(");
String authorString = contentString.substring(index1 + 4,
index2 - 1).trim();
post.setAuthor(authorString);
}
Matcher infoMatcher = infoPattern.matcher(content);
if (infoMatcher.find()) {
post.setSubjectID(infoMatcher.group(1));
post.setTopicSubjectID(infoMatcher.group(2));
post.setTitle(infoMatcher.group(5));
}
String bid = null, id = null, ftype = null, num = null, cacheable = null;
Matcher attachPartOneMatcher = Pattern.compile(
"attWriter\\((\\d+),(\\d+),(\\d+),(\\d+),(\\d+)").matcher(
content);
if (attachPartOneMatcher.find()) {
bid = attachPartOneMatcher.group(1);
id = attachPartOneMatcher.group(2);
ftype = attachPartOneMatcher.group(3);
num = attachPartOneMatcher.group(4);
cacheable = attachPartOneMatcher.group(5);
}
ArrayList<Attachment> attachFiles = new ArrayList<Attachment>();
Matcher attachPartTwoMatcher = Pattern.compile(
"attach\\('([^']+)', (\\d+), (\\d+)\\)").matcher(content);
while (attachPartTwoMatcher.find()) {
Attachment innerAtt = new Attachment();
innerAtt.setBid(bid);
innerAtt.setId(id);
innerAtt.setFtype(ftype);
innerAtt.setNum(num);
innerAtt.setCacheable(cacheable);
String name = attachPartTwoMatcher.group(1);
String len = attachPartTwoMatcher.group(2);
String pos = attachPartTwoMatcher.group(3);
innerAtt.setName(name);
innerAtt.setLen(len);
innerAtt.setPos(pos);
attachFiles.add(innerAtt);
}
post.setAttachFiles(attachFiles);
postList.add(post);
subject.setSubjectID(post.getSubjectID());
subject.setTopicSubjectID(post.getTopicSubjectID());
subject.setAuthor(post.getAuthor());
subject.setDateString(post.getDate().toLocaleString());
return postList;
}
/**
* 获取同主题帖子列表.
*
* @param board
* @param mainSubjectid
* @param pageno
* @return
*/
public List<Post> getPostList(Subject subject, ArrayList<String> blackList,
int startNumber) {
// String result = getPostListContent(subject.getBoardEngName(),
// subject.getSubjectID(), subject.getCurrentPageNo(), startNumber);
String url = "http://www.newsmth.net/bbstcon.php?board="
+ subject.getBoardEngName() + "&gid=" + subject.getSubjectID();
if (subject.getCurrentPageNo() > 0) {
url += "&pno=" + subject.getCurrentPageNo();
}
if (startNumber > 0) { // 对应web的"从此处展开"
url += "&start=" + startNumber;
}
String result = crawler.getUrlContent(url);
if (result == null) {
return Collections.emptyList();
}
Matcher bidMatcher = Pattern
.compile(
"tconWriter\\('[^']+',(\\d+),\\d+,\\d+,(\\d+),(\\d+),\\d+,\\d+,\\d+")
.matcher(result);
String boardid = "";
if (bidMatcher.find()) {
boardid = bidMatcher.group(1);
int totalPage = Integer.parseInt(bidMatcher.group(2));
subject.setTotalPageNo(totalPage);
Log.d("asm : totalpageno", totalPage + "");
int page = Integer.parseInt(bidMatcher.group(3));
subject.setCurrentPageNo(page);
}
String patternStr = "\\[(\\d+),'([^']+)'\\]";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(result);
List<Post> postList = new ArrayList<Post>();
boolean flag = true;
while (matcher.find()) {
String subjectid = matcher.group(1);
String author = matcher.group(2);
if (blackList.contains(author)) {
continue;
}
if (flag) {
flag = false;
if (!StringUtility.isEmpty(author)
&& StringUtility.isEmpty(subject.getAuthor())) {
subject.setAuthor(author);
}
}
Post post = new Post();
post.setAuthor(author);
post.setSubjectID(subjectid);
post.setBoardID(boardid);
post.setBoard(subject.getBoardEngName());
postList.add(post);
}
crawler.getPostList(postList);
return postList;
}
/**
* 获取移动版水木帖子列表.
*
* @param board
* @param mainSubjectid
* @param pageno
* @return
*/
@SuppressWarnings("unchecked")
public List<Post> getPostListFromMobile(Subject subject,
ArrayList<String> blackList, int boardType) {
String url = "";
int currentPageNo = subject.getCurrentPageNo();
boolean isInSubject = false;
if (boardType == SubjectListFragment.BOARD_TYPE_SUBJECT) {
url = "http://m.newsmth.net/article/" + subject.getBoardEngName()
+ "/" + subject.getSubjectID();
if (currentPageNo > 0) {
url += "?p=" + currentPageNo;
}
isInSubject = true;
} else if (boardType == SubjectListFragment.BOARD_TYPE_DIGEST) {
url = "http://m.newsmth.net/article/" + subject.getBoardEngName()
+ "/single/" + subject.getSubjectID() + "/1";
} else if (boardType == SubjectListFragment.BOARD_TYPE_MARK) {
url = "http://m.newsmth.net/article/" + subject.getBoardEngName()
+ "/single/" + subject.getSubjectID() + "/3";
}
String result = crawler.getUrlContentFromMobile(url);
if (result == null || result.contains("指定的文章不存在或链接错误")
|| result.contains("您无权阅读此版面")) {
return null;
}
List<Post> postList = new ArrayList<Post>();
boolean flag = true;
// <a userid href="/user/query/
Pattern userIDPattern = Pattern
.compile("<a href=\"/user/query/([^<>]+)\"");
Matcher userIDMatcher = userIDPattern.matcher(result);
while (userIDMatcher.find()) {
Post post = new Post();
post.setTopicSubjectID(subject.getTopicSubjectID());
post.setBoardID(subject.getBoardID());
post.setBoard(subject.getBoardEngName());
String author = userIDMatcher.group(1);
post.setAuthor(author);
if (flag) {
flag = false;
if (!StringUtility.isEmpty(author)
&& StringUtility.isEmpty(subject.getAuthor())) {
subject.setAuthor(author);
}
}
postList.add(post);
}
// <a href="/article/NewExpress/post/11111">回复
Pattern subjectPattern = Pattern.compile("<a href=\"/article/"
+ subject.getBoardEngName() + "/post/(\\d+)\"");
Matcher subjectMatcher = subjectPattern.matcher(result);
int index = 0;
while (subjectMatcher.find()) {
postList.get(index).setSubjectID(subjectMatcher.group(1));
++index;
}
// <a class="plant">2012-02-23 00:16:41</a>
Pattern datePattern = Pattern
.compile("<a class=\"plant\">(\\d)([^<>]+)</a>");
Matcher dateMatcher = datePattern.matcher(result);
index = 0;
boolean isOdd = !isInSubject;
flag = true;
while (dateMatcher.find()) {
if (isOdd) {
if (currentPageNo > 1) {
dateMatcher.group(1);
currentPageNo = 0;
continue;
}
isOdd = false;
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
try {
postList.get(index).setDate(
(java.util.Date) sdf.parse(dateMatcher.group(1)
+ dateMatcher.group(2)));
} catch (ParseException e) {
e.printStackTrace();
}
if (!isInSubject) {
break;
}
++index;
} else {
if (flag) {
flag = false;
String pageString = dateMatcher.group(1)
+ dateMatcher.group(2);
int splitIndex = pageString.indexOf("/");
int totalPage = Integer.parseInt(pageString
.substring(splitIndex + 1));
subject.setTotalPageNo(totalPage);
int page = Integer.parseInt(pageString.substring(0,
splitIndex));
subject.setCurrentPageNo(page);
}
isOdd = true;
continue;
}
}
// <li class="f">title</li>
index = 0;
Pattern titlePattern = Pattern.compile("<li class=\"f\">([^<>]+)</li>");
Matcher titleMatcher = titlePattern.matcher(result);
String titleString = "";
if (titleMatcher.find()) {
titleString = Html.fromHtml(titleMatcher.group(1)).toString();
postList.get(index).setTitle(titleString);
}
titleString = "Re: " + titleString;
if (aSMApplication.getCurrentApplication().isWeiboStyle()) {
titleString = null;
}
for (int i = 1; i < postList.size(); i++) {
postList.get(i).setTitle(titleString);
}
// post content
index = 0;
Pattern contentPattern = Pattern
.compile("<div class=\"sp\">(.*?)</div>");
Matcher contentMatcher = contentPattern.matcher(result);
while (contentMatcher.find()) {
String contentString = contentMatcher.group(1);
if (aSMApplication.getCurrentApplication().isWeiboStyle()) {
contentString = contentString
.replaceAll(
"(\\<br\\/\\>)+【 在 (\\S+?) .*?的大作中提到: 】<br\\/>:(.{1,20}).*?FROM",
"//<font color=\"#0099ff\">@$2<\\/font>: $3 <br \\/>FROM");
contentString = contentString.replaceAll("--\\<br \\/\\>FROM",
"<br \\/>FROM");
contentString = contentString.replaceAll(
"FROM: (\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\*)\\]",
"<br \\/>");
}
if (aSMApplication.getCurrentApplication().isShowIp()) {
Pattern myipPattern = Pattern
- .compile("FROM (\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\S+)");
+ .compile("FROM (\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.)\\S+");
Matcher myipMatcher = myipPattern.matcher(contentString);
while (myipMatcher.find()) {
String ipl = myipMatcher.group(1);
- if (ipl.length() > 7) {
- ipl = "<font color=\"#c0c0c0\">FROM $1("
+ if (ipl.length() > 5) {
+ ipl = "<font color=\"#c0c0c0\">FROM $1\\*("
+ aSMApplication.db
- .getLocation(Dot2LongIP(ipl))
+ .getLocation(Dot2LongIP(ipl + "1"))
+ ")<\\/font>";
} else {
- ipl = "<font color=\"#c0c0c0\">FROM $1<\\/font>";
+ ipl = "<font color=\"#c0c0c0\">FROM $1\\*<\\/font>";
}
contentString = myipMatcher.replaceAll(ipl);
}
}
Object[] objects = StringUtility
.parseMobilePostContent(contentString);
postList.get(index).setContent((String) objects[0]);
ArrayList<Attachment> attachFiles = new ArrayList<Attachment>();
ArrayList<String> attachList = (ArrayList<String>) objects[1];
for (Iterator<String> iterator = attachList.iterator(); iterator
.hasNext();) {
String attach = (String) iterator.next();
Attachment innerAtt = new Attachment();
if (attach.contains("<img")) {
Pattern urlPattern = Pattern
.compile("<a target=\"_blank\" href=\"([^<>]+)\"");
Matcher urlMatcher = urlPattern.matcher(attach);
if (urlMatcher.find()) {
String urlString = urlMatcher.group(1);
innerAtt.setMobileUrlString(urlString);
innerAtt.setName(urlString.substring(urlString
.lastIndexOf("/") + 1) + ".jpg");
}
} else {
Pattern urlPattern = Pattern
.compile("<a href=\"([^<>]+)\">([^<>]+)</a>");
Matcher urlMatcher = urlPattern.matcher(attach);
if (urlMatcher.find()) {
innerAtt.setMobileUrlString(urlMatcher.group(1));
innerAtt.setName(urlMatcher.group(2));
}
}
innerAtt.setMobileType(true);
attachFiles.add(innerAtt);
}
postList.get(index).setAttachFiles(attachFiles);
++index;
}
return postList;
}
private Boolean forwardGroupPostTo(Post post, String to) {
String url = "http://www.newsmth.net/bbstfwd.php?do";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("board", post.getBoard()));
params.add(new BasicNameValuePair("gid", post.getSubjectID()));
params.add(new BasicNameValuePair("start", post.getSubjectID()));
params.add(new BasicNameValuePair("noansi", "1"));
params.add(new BasicNameValuePair("target", to));
String content = crawler.getPostRequestResult(url, params);
if (content != null && content.contains("操作成功")) {
return true;
} else {
return false;
}
}
private Boolean forwardPostTo(Post post, String to) {
String url = "http://www.newsmth.net/bbsfwd.php?do";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("board", post.getBoard()));
params.add(new BasicNameValuePair("id", post.getSubjectID()));
params.add(new BasicNameValuePair("noansi", "1"));
params.add(new BasicNameValuePair("target", to));
String content = crawler.getPostRequestResult(url, params);
if (content != null && content.contains("操作成功")) {
return true;
} else {
return false;
}
}
public Boolean forwardGroupPostToExternalMail(Post post, String emailAddress) {
return forwardGroupPostTo(post, emailAddress);
}
public Boolean forwardGroupPostToMailBox(Post post) {
return forwardPostTo(post, userid);
}
public Boolean forwardPostToExternalMail(Post post, String emailAddress) {
return forwardPostTo(post, emailAddress);
}
public Boolean forwardPostToMailBox(Post post) {
return forwardPostTo(post, userid);
}
/**
* 获得个人信息
*
* @param userID
* 要查询的用户ID
* @return
*/
public Profile getProfile(String userID) {
String url = "http://www.newsmth.net/bbsqry.php?userid=" + userID;
String content = crawler.getUrlContent(url);
if (content == null) {
return null;
}
Pattern profilePattern = Pattern.compile("<pre>(.*?)</pre>",
Pattern.DOTALL);
Profile profile = new Profile();
Matcher profileMatcher = profilePattern.matcher(content);
if (profileMatcher.find()) {
String detailString = profileMatcher.group(1);
profile = StringUtility.parseProfile(detailString);
}
Pattern desPattern = Pattern.compile("prints\\('(.*?)'\\);",
Pattern.DOTALL);
Matcher desMatcher = desPattern.matcher(content);
if (desMatcher.find()) {
String descriptionString = desMatcher.group(1);
descriptionString = descriptionString
.replaceAll("[\\\\n]", "<br/>");
profile.setDescription(descriptionString);
} else {
profile.setDescription("这家伙很懒,啥也没留下");
}
return profile;
}
public String getPostContent(String boardid, String subjectid) {
String url = "http://www.newsmth.net/bbscon.php?bid=" + boardid
+ "&id=" + subjectid;
return crawler.getUrlContent(url);
}
// private String getPostListContent(String board, String subjectid, int
// pageno, int startNumber) {
// String url = "http://www.newsmth.net/bbstcon.php?board=" + board
// + "&gid=" + subjectid;
// if (pageno > 0) {
// url += "&pno=" + pageno;
// }
// if (startNumber > 0) {
// url += "&start=" + startNumber;
// }
// return crawler.getUrlContent(url);
// }
public String getMainSubjectList(String board, int pageno, int type) {
String url = "";
if (type == SubjectListFragment.BOARD_TYPE_SUBJECT) {
url = "http://www.newsmth.net/bbsdoc.php?board=" + board
+ "&ftype=6";
} else if (type == SubjectListFragment.BOARD_TYPE_NORMAL) {
url = "http://www.newsmth.net/bbsdoc.php?board=" + board
+ "&ftype=0";
} else if (type == SubjectListFragment.BOARD_TYPE_DIGEST) {
url = "http://www.newsmth.net/bbsdoc.php?board=" + board
+ "&ftype=1";
} else {// mark
url = "http://www.newsmth.net/bbsdoc.php?board=" + board
+ "&ftype=3";
}
if (pageno > 0) {
url = url + "&page=" + pageno;
}
return crawler.getUrlContent(url);
}
public String getMainSubjectListFromMobile(String board, int pageno,
int type) {
String url = "";
if (type == SubjectListFragment.BOARD_TYPE_SUBJECT) {
url = "http://m.newsmth.net/board/" + board;
} else if (type == SubjectListFragment.BOARD_TYPE_NORMAL) {
url = "http://m.newsmth.net/board/" + board + "/0";
} else if (type == SubjectListFragment.BOARD_TYPE_DIGEST) {
url = "http://m.newsmth.net/board/" + board + "/1";
} else {// mark
url = "http://m.newsmth.net/board/" + board + "/3";
}
if (pageno > 0) {
url = url + "?p=" + pageno;
}
return crawler.getUrlContentFromMobile(url);
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public static String Dot2LongIP(String dottedIP) {
dottedIP = dottedIP.replace('*', '1');
String[] addrArray = dottedIP.split("\\.");
long int_max = 2147483647;
long num = 0;
for (int i = 0; i < addrArray.length; i++) {
int power = 3 - i;
num += ((Integer.parseInt(addrArray[i]) % 256) * Math.pow(256,
power));
}
if (num < int_max) {
return String.valueOf(num);
} else {
return String.valueOf(num - int_max - int_max - 2);
}
}
}
| false | true | public List<Post> getPostListFromMobile(Subject subject,
ArrayList<String> blackList, int boardType) {
String url = "";
int currentPageNo = subject.getCurrentPageNo();
boolean isInSubject = false;
if (boardType == SubjectListFragment.BOARD_TYPE_SUBJECT) {
url = "http://m.newsmth.net/article/" + subject.getBoardEngName()
+ "/" + subject.getSubjectID();
if (currentPageNo > 0) {
url += "?p=" + currentPageNo;
}
isInSubject = true;
} else if (boardType == SubjectListFragment.BOARD_TYPE_DIGEST) {
url = "http://m.newsmth.net/article/" + subject.getBoardEngName()
+ "/single/" + subject.getSubjectID() + "/1";
} else if (boardType == SubjectListFragment.BOARD_TYPE_MARK) {
url = "http://m.newsmth.net/article/" + subject.getBoardEngName()
+ "/single/" + subject.getSubjectID() + "/3";
}
String result = crawler.getUrlContentFromMobile(url);
if (result == null || result.contains("指定的文章不存在或链接错误")
|| result.contains("您无权阅读此版面")) {
return null;
}
List<Post> postList = new ArrayList<Post>();
boolean flag = true;
// <a userid href="/user/query/
Pattern userIDPattern = Pattern
.compile("<a href=\"/user/query/([^<>]+)\"");
Matcher userIDMatcher = userIDPattern.matcher(result);
while (userIDMatcher.find()) {
Post post = new Post();
post.setTopicSubjectID(subject.getTopicSubjectID());
post.setBoardID(subject.getBoardID());
post.setBoard(subject.getBoardEngName());
String author = userIDMatcher.group(1);
post.setAuthor(author);
if (flag) {
flag = false;
if (!StringUtility.isEmpty(author)
&& StringUtility.isEmpty(subject.getAuthor())) {
subject.setAuthor(author);
}
}
postList.add(post);
}
// <a href="/article/NewExpress/post/11111">回复
Pattern subjectPattern = Pattern.compile("<a href=\"/article/"
+ subject.getBoardEngName() + "/post/(\\d+)\"");
Matcher subjectMatcher = subjectPattern.matcher(result);
int index = 0;
while (subjectMatcher.find()) {
postList.get(index).setSubjectID(subjectMatcher.group(1));
++index;
}
// <a class="plant">2012-02-23 00:16:41</a>
Pattern datePattern = Pattern
.compile("<a class=\"plant\">(\\d)([^<>]+)</a>");
Matcher dateMatcher = datePattern.matcher(result);
index = 0;
boolean isOdd = !isInSubject;
flag = true;
while (dateMatcher.find()) {
if (isOdd) {
if (currentPageNo > 1) {
dateMatcher.group(1);
currentPageNo = 0;
continue;
}
isOdd = false;
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
try {
postList.get(index).setDate(
(java.util.Date) sdf.parse(dateMatcher.group(1)
+ dateMatcher.group(2)));
} catch (ParseException e) {
e.printStackTrace();
}
if (!isInSubject) {
break;
}
++index;
} else {
if (flag) {
flag = false;
String pageString = dateMatcher.group(1)
+ dateMatcher.group(2);
int splitIndex = pageString.indexOf("/");
int totalPage = Integer.parseInt(pageString
.substring(splitIndex + 1));
subject.setTotalPageNo(totalPage);
int page = Integer.parseInt(pageString.substring(0,
splitIndex));
subject.setCurrentPageNo(page);
}
isOdd = true;
continue;
}
}
// <li class="f">title</li>
index = 0;
Pattern titlePattern = Pattern.compile("<li class=\"f\">([^<>]+)</li>");
Matcher titleMatcher = titlePattern.matcher(result);
String titleString = "";
if (titleMatcher.find()) {
titleString = Html.fromHtml(titleMatcher.group(1)).toString();
postList.get(index).setTitle(titleString);
}
titleString = "Re: " + titleString;
if (aSMApplication.getCurrentApplication().isWeiboStyle()) {
titleString = null;
}
for (int i = 1; i < postList.size(); i++) {
postList.get(i).setTitle(titleString);
}
// post content
index = 0;
Pattern contentPattern = Pattern
.compile("<div class=\"sp\">(.*?)</div>");
Matcher contentMatcher = contentPattern.matcher(result);
while (contentMatcher.find()) {
String contentString = contentMatcher.group(1);
if (aSMApplication.getCurrentApplication().isWeiboStyle()) {
contentString = contentString
.replaceAll(
"(\\<br\\/\\>)+【 在 (\\S+?) .*?的大作中提到: 】<br\\/>:(.{1,20}).*?FROM",
"//<font color=\"#0099ff\">@$2<\\/font>: $3 <br \\/>FROM");
contentString = contentString.replaceAll("--\\<br \\/\\>FROM",
"<br \\/>FROM");
contentString = contentString.replaceAll(
"FROM: (\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\*)\\]",
"<br \\/>");
}
if (aSMApplication.getCurrentApplication().isShowIp()) {
Pattern myipPattern = Pattern
.compile("FROM (\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\S+)");
Matcher myipMatcher = myipPattern.matcher(contentString);
while (myipMatcher.find()) {
String ipl = myipMatcher.group(1);
if (ipl.length() > 7) {
ipl = "<font color=\"#c0c0c0\">FROM $1("
+ aSMApplication.db
.getLocation(Dot2LongIP(ipl))
+ ")<\\/font>";
} else {
ipl = "<font color=\"#c0c0c0\">FROM $1<\\/font>";
}
contentString = myipMatcher.replaceAll(ipl);
}
}
Object[] objects = StringUtility
.parseMobilePostContent(contentString);
postList.get(index).setContent((String) objects[0]);
ArrayList<Attachment> attachFiles = new ArrayList<Attachment>();
ArrayList<String> attachList = (ArrayList<String>) objects[1];
for (Iterator<String> iterator = attachList.iterator(); iterator
.hasNext();) {
String attach = (String) iterator.next();
Attachment innerAtt = new Attachment();
if (attach.contains("<img")) {
Pattern urlPattern = Pattern
.compile("<a target=\"_blank\" href=\"([^<>]+)\"");
Matcher urlMatcher = urlPattern.matcher(attach);
if (urlMatcher.find()) {
String urlString = urlMatcher.group(1);
innerAtt.setMobileUrlString(urlString);
innerAtt.setName(urlString.substring(urlString
.lastIndexOf("/") + 1) + ".jpg");
}
} else {
Pattern urlPattern = Pattern
.compile("<a href=\"([^<>]+)\">([^<>]+)</a>");
Matcher urlMatcher = urlPattern.matcher(attach);
if (urlMatcher.find()) {
innerAtt.setMobileUrlString(urlMatcher.group(1));
innerAtt.setName(urlMatcher.group(2));
}
}
innerAtt.setMobileType(true);
attachFiles.add(innerAtt);
}
postList.get(index).setAttachFiles(attachFiles);
++index;
}
return postList;
}
| public List<Post> getPostListFromMobile(Subject subject,
ArrayList<String> blackList, int boardType) {
String url = "";
int currentPageNo = subject.getCurrentPageNo();
boolean isInSubject = false;
if (boardType == SubjectListFragment.BOARD_TYPE_SUBJECT) {
url = "http://m.newsmth.net/article/" + subject.getBoardEngName()
+ "/" + subject.getSubjectID();
if (currentPageNo > 0) {
url += "?p=" + currentPageNo;
}
isInSubject = true;
} else if (boardType == SubjectListFragment.BOARD_TYPE_DIGEST) {
url = "http://m.newsmth.net/article/" + subject.getBoardEngName()
+ "/single/" + subject.getSubjectID() + "/1";
} else if (boardType == SubjectListFragment.BOARD_TYPE_MARK) {
url = "http://m.newsmth.net/article/" + subject.getBoardEngName()
+ "/single/" + subject.getSubjectID() + "/3";
}
String result = crawler.getUrlContentFromMobile(url);
if (result == null || result.contains("指定的文章不存在或链接错误")
|| result.contains("您无权阅读此版面")) {
return null;
}
List<Post> postList = new ArrayList<Post>();
boolean flag = true;
// <a userid href="/user/query/
Pattern userIDPattern = Pattern
.compile("<a href=\"/user/query/([^<>]+)\"");
Matcher userIDMatcher = userIDPattern.matcher(result);
while (userIDMatcher.find()) {
Post post = new Post();
post.setTopicSubjectID(subject.getTopicSubjectID());
post.setBoardID(subject.getBoardID());
post.setBoard(subject.getBoardEngName());
String author = userIDMatcher.group(1);
post.setAuthor(author);
if (flag) {
flag = false;
if (!StringUtility.isEmpty(author)
&& StringUtility.isEmpty(subject.getAuthor())) {
subject.setAuthor(author);
}
}
postList.add(post);
}
// <a href="/article/NewExpress/post/11111">回复
Pattern subjectPattern = Pattern.compile("<a href=\"/article/"
+ subject.getBoardEngName() + "/post/(\\d+)\"");
Matcher subjectMatcher = subjectPattern.matcher(result);
int index = 0;
while (subjectMatcher.find()) {
postList.get(index).setSubjectID(subjectMatcher.group(1));
++index;
}
// <a class="plant">2012-02-23 00:16:41</a>
Pattern datePattern = Pattern
.compile("<a class=\"plant\">(\\d)([^<>]+)</a>");
Matcher dateMatcher = datePattern.matcher(result);
index = 0;
boolean isOdd = !isInSubject;
flag = true;
while (dateMatcher.find()) {
if (isOdd) {
if (currentPageNo > 1) {
dateMatcher.group(1);
currentPageNo = 0;
continue;
}
isOdd = false;
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
try {
postList.get(index).setDate(
(java.util.Date) sdf.parse(dateMatcher.group(1)
+ dateMatcher.group(2)));
} catch (ParseException e) {
e.printStackTrace();
}
if (!isInSubject) {
break;
}
++index;
} else {
if (flag) {
flag = false;
String pageString = dateMatcher.group(1)
+ dateMatcher.group(2);
int splitIndex = pageString.indexOf("/");
int totalPage = Integer.parseInt(pageString
.substring(splitIndex + 1));
subject.setTotalPageNo(totalPage);
int page = Integer.parseInt(pageString.substring(0,
splitIndex));
subject.setCurrentPageNo(page);
}
isOdd = true;
continue;
}
}
// <li class="f">title</li>
index = 0;
Pattern titlePattern = Pattern.compile("<li class=\"f\">([^<>]+)</li>");
Matcher titleMatcher = titlePattern.matcher(result);
String titleString = "";
if (titleMatcher.find()) {
titleString = Html.fromHtml(titleMatcher.group(1)).toString();
postList.get(index).setTitle(titleString);
}
titleString = "Re: " + titleString;
if (aSMApplication.getCurrentApplication().isWeiboStyle()) {
titleString = null;
}
for (int i = 1; i < postList.size(); i++) {
postList.get(i).setTitle(titleString);
}
// post content
index = 0;
Pattern contentPattern = Pattern
.compile("<div class=\"sp\">(.*?)</div>");
Matcher contentMatcher = contentPattern.matcher(result);
while (contentMatcher.find()) {
String contentString = contentMatcher.group(1);
if (aSMApplication.getCurrentApplication().isWeiboStyle()) {
contentString = contentString
.replaceAll(
"(\\<br\\/\\>)+【 在 (\\S+?) .*?的大作中提到: 】<br\\/>:(.{1,20}).*?FROM",
"//<font color=\"#0099ff\">@$2<\\/font>: $3 <br \\/>FROM");
contentString = contentString.replaceAll("--\\<br \\/\\>FROM",
"<br \\/>FROM");
contentString = contentString.replaceAll(
"FROM: (\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\*)\\]",
"<br \\/>");
}
if (aSMApplication.getCurrentApplication().isShowIp()) {
Pattern myipPattern = Pattern
.compile("FROM (\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.)\\S+");
Matcher myipMatcher = myipPattern.matcher(contentString);
while (myipMatcher.find()) {
String ipl = myipMatcher.group(1);
if (ipl.length() > 5) {
ipl = "<font color=\"#c0c0c0\">FROM $1\\*("
+ aSMApplication.db
.getLocation(Dot2LongIP(ipl + "1"))
+ ")<\\/font>";
} else {
ipl = "<font color=\"#c0c0c0\">FROM $1\\*<\\/font>";
}
contentString = myipMatcher.replaceAll(ipl);
}
}
Object[] objects = StringUtility
.parseMobilePostContent(contentString);
postList.get(index).setContent((String) objects[0]);
ArrayList<Attachment> attachFiles = new ArrayList<Attachment>();
ArrayList<String> attachList = (ArrayList<String>) objects[1];
for (Iterator<String> iterator = attachList.iterator(); iterator
.hasNext();) {
String attach = (String) iterator.next();
Attachment innerAtt = new Attachment();
if (attach.contains("<img")) {
Pattern urlPattern = Pattern
.compile("<a target=\"_blank\" href=\"([^<>]+)\"");
Matcher urlMatcher = urlPattern.matcher(attach);
if (urlMatcher.find()) {
String urlString = urlMatcher.group(1);
innerAtt.setMobileUrlString(urlString);
innerAtt.setName(urlString.substring(urlString
.lastIndexOf("/") + 1) + ".jpg");
}
} else {
Pattern urlPattern = Pattern
.compile("<a href=\"([^<>]+)\">([^<>]+)</a>");
Matcher urlMatcher = urlPattern.matcher(attach);
if (urlMatcher.find()) {
innerAtt.setMobileUrlString(urlMatcher.group(1));
innerAtt.setName(urlMatcher.group(2));
}
}
innerAtt.setMobileType(true);
attachFiles.add(innerAtt);
}
postList.get(index).setAttachFiles(attachFiles);
++index;
}
return postList;
}
|
diff --git a/editor/src/main/java/com/nebula2d/editor/ui/NewComponentPopup.java b/editor/src/main/java/com/nebula2d/editor/ui/NewComponentPopup.java
index 9f9f3ef..2da2333 100644
--- a/editor/src/main/java/com/nebula2d/editor/ui/NewComponentPopup.java
+++ b/editor/src/main/java/com/nebula2d/editor/ui/NewComponentPopup.java
@@ -1,177 +1,177 @@
/*
* Nebula2D is a cross-platform, 2D game engine for PC, Mac, & Linux
* Copyright (c) 2014 Jon Bonazza
*
* 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 com.nebula2d.editor.ui;
import com.nebula2d.editor.framework.GameObject;
import com.nebula2d.editor.framework.components.Behaviour;
import com.nebula2d.editor.framework.components.Collider;
import com.nebula2d.editor.framework.components.Component;
import com.nebula2d.editor.framework.components.MusicSource;
import com.nebula2d.editor.framework.components.RigidBody;
import com.nebula2d.editor.framework.components.SoundEffectSource;
import com.nebula2d.editor.framework.components.SpriteRenderer;
import com.nebula2d.editor.framework.components.TileMapRenderer;
import com.nebula2d.editor.ui.controls.N2DLabel;
import com.nebula2d.editor.ui.controls.N2DPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
public class NewComponentPopup extends JPopupMenu {
private GameObject gameObject;
private DefaultListModel<Component> listModel;
private JList<Component> list;
public NewComponentPopup(GameObject gameObject, JList<Component> list) {
this.list = list;
this.gameObject = gameObject;
this.listModel = (DefaultListModel<Component>) list.getModel();
create();
}
private void create() {
JMenu rendererMenu = new JMenu("Renderer");
- JMenuItem spriteRendererMenuItem = rendererMenu.add("SpriteAnimatedRenderer");
+ JMenuItem spriteRendererMenuItem = rendererMenu.add("SpriteRenderer");
JMenuItem tileMapRendererMenuItem = rendererMenu.add("TileMapRenderer");
JMenu audioMenu = new JMenu("Audio");
JMenuItem musicSourceMenuItem = audioMenu.add("MusicSource");
JMenuItem soundEffectSourceMenuItem = audioMenu.add("SoundEffectSource");
JMenuItem behaviorMenuItem = new JMenuItem("Behavior");
JMenu physicsMenu = new JMenu("Physics");
JMenuItem rigidBodyMenuItm = physicsMenu.add("RigidBody");
JMenuItem collider = physicsMenu.add("Collider");
behaviorMenuItem.addActionListener(e -> {
Behaviour behaviour = new Behaviour();
new NewComponentDialog(behaviour);
});
musicSourceMenuItem.addActionListener(e -> {
MusicSource musicSource = new MusicSource("");
new NewComponentDialog(musicSource);
});
soundEffectSourceMenuItem.addActionListener(e -> {
SoundEffectSource soundEffectSource = new SoundEffectSource("");
new NewComponentDialog(soundEffectSource);
});
spriteRendererMenuItem.addActionListener(e -> {
if (gameObject.getRenderer() != null) {
JOptionPane.showMessageDialog(NewComponentPopup.this, "This GameObject already has a renderer attached.");
return;
}
new NewComponentDialog(new SpriteRenderer(""));
});
tileMapRendererMenuItem.addActionListener(e -> {
if (gameObject.getRenderer() != null) {
JOptionPane.showMessageDialog(NewComponentPopup.this, "This GameObject already has a renderer attached.");
return;
}
new NewComponentDialog(new TileMapRenderer(""));
});
rigidBodyMenuItm.addActionListener(e -> {
if (gameObject.getRigidBody() != null) {
JOptionPane.showMessageDialog(NewComponentPopup.this, "This GameObject already has a RigidBody attached.");
return;
}
new NewComponentDialog(new RigidBody(gameObject));
});
collider.addActionListener(e -> new NewComponentDialog(new Collider(gameObject)));
add(rendererMenu);
add(audioMenu);
add(behaviorMenuItem);
add(physicsMenu);
addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
setVisible(false);
}
});
}
private class NewComponentDialog extends JDialog {
private Component component;
public NewComponentDialog(Component component) {
this.component = component;
final N2DLabel errorMessage = new N2DLabel("You must enter a valid name for the component.");
errorMessage.setForeground(Color.red);
errorMessage.setVisible(false);
final N2DLabel nameLbl = new N2DLabel("Name:");
final JTextField nameTf = new JTextField(20);
N2DPanel namePanel = new N2DPanel();
namePanel.add(nameLbl);
namePanel.add(nameTf);
JButton okBtn = new JButton("Ok");
okBtn.addActionListener(e -> {
String name = nameTf.getText();
if (!validateText(name)) {
errorMessage.setVisible(true);
return;
}
errorMessage.setVisible(false);
NewComponentDialog.this.component.setName(name);
gameObject.addComponent(NewComponentDialog.this.component);
listModel.addElement(NewComponentDialog.this.component);
dispose();
list.setSelectedValue(NewComponentDialog.this.component, true);
});
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(e -> dispose());
N2DPanel buttonPanel = new N2DPanel(new FlowLayout(FlowLayout.LEFT));
buttonPanel.add(okBtn);
buttonPanel.add(cancelBtn);
add(errorMessage, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.SOUTH);
add(namePanel);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private boolean validateText(String text) {
return !text.trim().equals("");
}
}
}
| true | true | private void create() {
JMenu rendererMenu = new JMenu("Renderer");
JMenuItem spriteRendererMenuItem = rendererMenu.add("SpriteAnimatedRenderer");
JMenuItem tileMapRendererMenuItem = rendererMenu.add("TileMapRenderer");
JMenu audioMenu = new JMenu("Audio");
JMenuItem musicSourceMenuItem = audioMenu.add("MusicSource");
JMenuItem soundEffectSourceMenuItem = audioMenu.add("SoundEffectSource");
JMenuItem behaviorMenuItem = new JMenuItem("Behavior");
JMenu physicsMenu = new JMenu("Physics");
JMenuItem rigidBodyMenuItm = physicsMenu.add("RigidBody");
JMenuItem collider = physicsMenu.add("Collider");
behaviorMenuItem.addActionListener(e -> {
Behaviour behaviour = new Behaviour();
new NewComponentDialog(behaviour);
});
musicSourceMenuItem.addActionListener(e -> {
MusicSource musicSource = new MusicSource("");
new NewComponentDialog(musicSource);
});
soundEffectSourceMenuItem.addActionListener(e -> {
SoundEffectSource soundEffectSource = new SoundEffectSource("");
new NewComponentDialog(soundEffectSource);
});
spriteRendererMenuItem.addActionListener(e -> {
if (gameObject.getRenderer() != null) {
JOptionPane.showMessageDialog(NewComponentPopup.this, "This GameObject already has a renderer attached.");
return;
}
new NewComponentDialog(new SpriteRenderer(""));
});
tileMapRendererMenuItem.addActionListener(e -> {
if (gameObject.getRenderer() != null) {
JOptionPane.showMessageDialog(NewComponentPopup.this, "This GameObject already has a renderer attached.");
return;
}
new NewComponentDialog(new TileMapRenderer(""));
});
rigidBodyMenuItm.addActionListener(e -> {
if (gameObject.getRigidBody() != null) {
JOptionPane.showMessageDialog(NewComponentPopup.this, "This GameObject already has a RigidBody attached.");
return;
}
new NewComponentDialog(new RigidBody(gameObject));
});
collider.addActionListener(e -> new NewComponentDialog(new Collider(gameObject)));
add(rendererMenu);
add(audioMenu);
add(behaviorMenuItem);
add(physicsMenu);
addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
setVisible(false);
}
});
}
| private void create() {
JMenu rendererMenu = new JMenu("Renderer");
JMenuItem spriteRendererMenuItem = rendererMenu.add("SpriteRenderer");
JMenuItem tileMapRendererMenuItem = rendererMenu.add("TileMapRenderer");
JMenu audioMenu = new JMenu("Audio");
JMenuItem musicSourceMenuItem = audioMenu.add("MusicSource");
JMenuItem soundEffectSourceMenuItem = audioMenu.add("SoundEffectSource");
JMenuItem behaviorMenuItem = new JMenuItem("Behavior");
JMenu physicsMenu = new JMenu("Physics");
JMenuItem rigidBodyMenuItm = physicsMenu.add("RigidBody");
JMenuItem collider = physicsMenu.add("Collider");
behaviorMenuItem.addActionListener(e -> {
Behaviour behaviour = new Behaviour();
new NewComponentDialog(behaviour);
});
musicSourceMenuItem.addActionListener(e -> {
MusicSource musicSource = new MusicSource("");
new NewComponentDialog(musicSource);
});
soundEffectSourceMenuItem.addActionListener(e -> {
SoundEffectSource soundEffectSource = new SoundEffectSource("");
new NewComponentDialog(soundEffectSource);
});
spriteRendererMenuItem.addActionListener(e -> {
if (gameObject.getRenderer() != null) {
JOptionPane.showMessageDialog(NewComponentPopup.this, "This GameObject already has a renderer attached.");
return;
}
new NewComponentDialog(new SpriteRenderer(""));
});
tileMapRendererMenuItem.addActionListener(e -> {
if (gameObject.getRenderer() != null) {
JOptionPane.showMessageDialog(NewComponentPopup.this, "This GameObject already has a renderer attached.");
return;
}
new NewComponentDialog(new TileMapRenderer(""));
});
rigidBodyMenuItm.addActionListener(e -> {
if (gameObject.getRigidBody() != null) {
JOptionPane.showMessageDialog(NewComponentPopup.this, "This GameObject already has a RigidBody attached.");
return;
}
new NewComponentDialog(new RigidBody(gameObject));
});
collider.addActionListener(e -> new NewComponentDialog(new Collider(gameObject)));
add(rendererMenu);
add(audioMenu);
add(behaviorMenuItem);
add(physicsMenu);
addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
setVisible(false);
}
});
}
|
diff --git a/dspace-api/src/main/java/org/dspace/authorize/ResourcePolicy.java b/dspace-api/src/main/java/org/dspace/authorize/ResourcePolicy.java
index ff5185b09..4c2751f6a 100644
--- a/dspace-api/src/main/java/org/dspace/authorize/ResourcePolicy.java
+++ b/dspace-api/src/main/java/org/dspace/authorize/ResourcePolicy.java
@@ -1,476 +1,476 @@
/*
* ResourcePolicy.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. 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 Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* 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
* HOLDERS 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.dspace.authorize;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Logger;
import org.dspace.authorize.dao.ResourcePolicyDAO;
import org.dspace.authorize.dao.ResourcePolicyDAOFactory;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
import org.dspace.eperson.dao.EPersonDAO;
import org.dspace.eperson.dao.EPersonDAOFactory;
import org.dspace.eperson.dao.GroupDAO;
import org.dspace.eperson.dao.GroupDAOFactory;
import org.dspace.uri.Identifiable;
import org.dspace.uri.ObjectIdentifier;
import org.dspace.uri.SimpleIdentifier;
import org.dspace.uri.UnsupportedIdentifierException;
import org.dspace.uri.ExternalIdentifier;
import java.util.Date;
import java.util.List;
/**
* Class representing a ResourcePolicy
*
* @author David Stuve
* @version $Revision$
*/
public class ResourcePolicy implements Identifiable
{
private static Logger log = Logger.getLogger(ResourcePolicy.class);
private Context context;
private ResourcePolicyDAO dao;
private EPersonDAO epersonDAO;
private GroupDAO groupDAO;
private int id;
// private ObjectIdentifier oid;
private SimpleIdentifier sid;
// FIXME: Figure out a way to replace all of this using the
// ObjectIdentifier class.
private int resourceID;
private int resourceTypeID;
private int actionID;
private int epersonID;
private int groupID;
private Date startDate;
private Date endDate;
public ResourcePolicy(Context context, int id)
{
this.context = context;
this.id = id;
dao = ResourcePolicyDAOFactory.getInstance(context);
epersonDAO = EPersonDAOFactory.getInstance(context);
groupDAO = GroupDAOFactory.getInstance(context);
resourceID = -1;
resourceTypeID = -1;
actionID = -1;
epersonID = -1;
groupID = -1;
context.cache(this, id);
}
public int getID()
{
return id;
}
public SimpleIdentifier getSimpleIdentifier()
{
return sid;
}
public void setSimpleIdentifier(SimpleIdentifier sid)
{
this.sid = sid;
}
public ObjectIdentifier getIdentifier()
{
return null;
}
public void setIdentifier(ObjectIdentifier oid)
{
this.sid = oid;
}
public List<ExternalIdentifier> getExternalIdentifiers()
{
return null;
}
public void setExternalIdentifiers(List<ExternalIdentifier> eids)
throws UnsupportedIdentifierException
{
throw new UnsupportedIdentifierException("ResourcePolicy does not support the use of ExternalIdentifiers");
}
public void addExternalIdentifier(ExternalIdentifier eid)
throws UnsupportedIdentifierException
{
throw new UnsupportedIdentifierException("ResourcePolicy does not support the use of ExternalIdentifiers");
}
/**
* Get the type of the objects referred to by policy
*
* @return type of object/resource
*/
public int getResourceType()
{
return resourceTypeID;
}
/**
* set both type and id of resource referred to by policy
*
*/
public void setResource(DSpaceObject o)
{
setResourceType(o.getType());
setResourceID(o.getID());
}
/**
* Set the type of the resource referred to by the policy
*/
public void setResourceType(int resourceTypeID)
{
this.resourceTypeID = resourceTypeID;
}
/**
* Get the ID of a resource pointed to by the policy (is null if policy
* doesn't apply to a single resource.)
*/
public int getResourceID()
{
return resourceID;
}
/**
* If the policy refers to a single resource, this is the ID of that
* resource.
*/
public void setResourceID(int resourceID)
{
this.resourceID = resourceID;
}
/**
* Returns the action this policy authorizes.
*/
public int getAction()
{
return actionID;
}
public String getActionText()
{
if (actionID == -1)
{
return "...";
}
else
{
return Constants.actionText[actionID];
}
}
/**
* set the action this policy authorizes
*
* @param actionID action ID from <code>org.dspace.core.Constants</code>
*/
public void setAction(int actionID)
{
this.actionID = actionID;
}
/**
* @return eperson ID, or -1 if EPerson not set
*/
public int getEPersonID()
{
return epersonID;
}
public void setEPersonID(int epersonID)
{
this.epersonID = epersonID;
}
/**
* get EPerson this policy relates to
*
* @return EPerson, or null
*/
public EPerson getEPerson()
{
if (epersonID == -1)
{
return null;
}
return epersonDAO.retrieve(epersonID);
}
/**
* assign an EPerson to this policy
*
* @param e EPerson
*/
public void setEPerson(EPerson eperson)
{
if (eperson != null)
{
epersonID = eperson.getID();
}
else
{
epersonID = -1;
}
}
/**
* gets ID for Group referred to by this policy
*
* @return groupID, or -1 if no group set
*/
public int getGroupID()
{
return groupID;
}
public void setGroupID(int groupID)
{
this.groupID = groupID;
}
/**
* gets Group for this policy
*
* @return Group, or -1 if no group set
*/
public Group getGroup()
{
if (groupID == -1)
{
return null;
}
return groupDAO.retrieve(groupID);
}
/**
* set Group for this policy
*/
public void setGroup(Group group)
{
if (group != null)
{
groupID = group.getID();
}
else
{
groupID = -1;
}
}
/**
* Get the start date of the policy
*
* @return start date, or null if there is no start date set (probably most
* common case)
*/
public Date getStartDate()
{
return startDate;
}
/**
* Set the start date for the policy
*
* @param d
* date, or null for no start date
*/
public void setStartDate(Date startDate)
{
this.startDate = startDate;
}
/**
* Get end date for the policy
*
* @return end date or null for no end date
*/
public Date getEndDate()
{
return endDate;
}
/**
* Set end date for the policy
*
* @param d
* end date, or null
*/
public void setEndDate(Date endDate)
{
this.endDate = endDate;
}
////////////////////////////////////////////////////////////////////
// Utility methods
////////////////////////////////////////////////////////////////////
/**
* figures out if the date is valid for the policy
*
* @return true if policy has begun and hasn't expired yet (or no dates are
* set)
*/
public boolean isDateValid()
{
Date sd = getStartDate();
Date ed = getEndDate();
// if no dates set, return true (most common case)
if ((sd == null) && (ed == null))
{
return true;
}
// one is set, now need to do some date math
Date now = new Date();
// check start date first
if (sd != null)
{
// start date is set, return false if we're before it
if (now.before(sd))
{
return false;
}
}
// now expiration date
if (ed != null)
{
// end date is set, return false if we're after it
- if (now.after(sd))
+ if (now.after(ed))
{
return false;
}
}
// if we made it this far, start < now < end
return true; // date must be okay
}
@Deprecated
ResourcePolicy(Context context, org.dspace.storage.rdbms.TableRow row)
{
this(context, row.getIntColumn("policy_id"));
}
@Deprecated
public static ResourcePolicy find(Context context, int id)
{
return ResourcePolicyDAOFactory.getInstance(context).retrieve(id);
}
@Deprecated
public static ResourcePolicy create(Context context)
throws AuthorizeException
{
return ResourcePolicyDAOFactory.getInstance(context).create();
}
@Deprecated
public void delete()
{
dao.delete(getID());
}
@Deprecated
public void update()
{
dao.update(this);
}
////////////////////////////////////////////////////////////////////
// Utility methods
////////////////////////////////////////////////////////////////////
public String toString()
{
return ToStringBuilder.reflectionToString(this,
ToStringStyle.MULTI_LINE_STYLE);
}
public boolean equals(Object o)
{
return EqualsBuilder.reflectionEquals(this, o);
}
public boolean equals(ResourcePolicy other)
{
if (this.getID() == other.getID())
{
return true;
}
return false;
}
public int hashCode()
{
return HashCodeBuilder.reflectionHashCode(this);
}
}
| true | true | public boolean isDateValid()
{
Date sd = getStartDate();
Date ed = getEndDate();
// if no dates set, return true (most common case)
if ((sd == null) && (ed == null))
{
return true;
}
// one is set, now need to do some date math
Date now = new Date();
// check start date first
if (sd != null)
{
// start date is set, return false if we're before it
if (now.before(sd))
{
return false;
}
}
// now expiration date
if (ed != null)
{
// end date is set, return false if we're after it
if (now.after(sd))
{
return false;
}
}
// if we made it this far, start < now < end
return true; // date must be okay
}
| public boolean isDateValid()
{
Date sd = getStartDate();
Date ed = getEndDate();
// if no dates set, return true (most common case)
if ((sd == null) && (ed == null))
{
return true;
}
// one is set, now need to do some date math
Date now = new Date();
// check start date first
if (sd != null)
{
// start date is set, return false if we're before it
if (now.before(sd))
{
return false;
}
}
// now expiration date
if (ed != null)
{
// end date is set, return false if we're after it
if (now.after(ed))
{
return false;
}
}
// if we made it this far, start < now < end
return true; // date must be okay
}
|
diff --git a/src/gradespeed/Main.java b/src/gradespeed/Main.java
index beb4b4e..13be0e0 100644
--- a/src/gradespeed/Main.java
+++ b/src/gradespeed/Main.java
@@ -1,167 +1,168 @@
package gradespeed;
import java.io.*;
import static java.lang.System.*;
import java.util.*;
import org.jsoup.*;
import org.jsoup.Connection.*;
import org.jsoup.nodes.*;
import org.jsoup.select.*;
public class Main {
public static void main(String[] args) throws Exception{
// String code = "PGRpdiB1bnNlbGVjdGFibGU9Im9uIiBvbnNlbGVjdHN0YXJ0PSJyZXR1cm4gZmFsc2U7IiBzdHlsZT0iLW1vei11c2VyLXNlbGVjdDpub25lIj48UD48ZGl2IGNsYXNzPSJTdHVkZW50SGVhZGVyIj48c3BhbiBjbGFzcz0iU3R1ZGVudE5hbWUiPkxhbmtlbmF1LCBQYXRyaWNpbzwvc3Bhbj4gKEtsZWluIE9hayBIaWdoIFNjaG9vbCk8L2Rpdj48dGFibGUgYm9yZGVyPSIwIiBjZWxsc3BhY2luZz0iMCIgY2VsbHBhZGRpbmc9IjMiIGNsYXNzPSJEYXRhVGFibGUiPjx0ciBjbGFzcz0iVGFibGVIZWFkZXIiPjx0aCBhbGlnbj0ibGVmdCIgc2NvcGU9ImNvbCIVGVhY2hlcjwvdGgPHRoIGFsaWduPSJsZWZ0IiBzY29wZT0iY29sIj5Db3Vyc2U8L3RoPjx0aCBhbGlnbj0ibGVmdCIgc2NvcGU9ImNvbCIUGVyaW9kPC90aD48dGggYWxpZ249ImxlZnQiIHNjb3BlPSJjb2wiPkN5Y2xlIDE8L3RoPjx0aCBhbGlnbj0ibGVmdCIgc2NvcGU9ImNvbCIQ3ljbGUgMjwvdGgPHRoIGFsaWduPSJsZWZ0IiBzY29wZT0iY29sIj5DeWNsZSAzPC90aD48dGggYWxpZ249ImxlZnQiIHNjb3BlPSJjb2wiPkV4YW0gMTwvdGgPHRoIGFsaWduPSJsZWZ0IiBzY29wZT0iY29sIj5TZW0gMTwvdGgPHRoIGFsaWduPSJsZWZ0IiBzY29wZT0iY29sIj5DeWNsZSA0PC90aD48dGggYWxpZ249ImxlZnQiIHNjb3BlPSJj";
// out.println(decodeString(code));
String code = "<div unselectable=\"on\" onselectstart=\"return false;\" style=\"-moz-user-select:none\"><P><div class=\"StudentHeader\"><span class=\"StudentName\">Lankenau, Patricio</span> (Klein Oak High School)</div><table border=\"0\" cellspacing=\"0\" cellpadding=\"3\" class=\"DataTable\"><tr class=\"TableHeader\"><th align=\"left\" scope=\"col\">Teacher</th><th align=\"left\" scope=\"col\">Course</th><th align=\"left\" scope=\"col\">Period</th><th align=\"left\" scope=\"col\">Cycle 1</th><th align=\"left\" scope=\"col\">Cycle 2</th><th align=\"left\" scope=\"col\">Cycle 3</th><th align=\"left\" scope=\"col\">Exam 1</th><th align=\"left\" scope=\"col\">Sem 1</th><th align=\"left\" scope=\"col\">Cycle 4</th><th align=\"left\" scope=\"col\">Cycle 5</th><th align=\"left\" scope=\"col\">Cycle 6</th><th align=\"left\" scope=\"col\">Exam 2</th><th align=\"left\" scope=\"col\">Sem 2</th></tr><tr class=\"DataRow\">"
+"<th align=\"left\" scope=\"row\" class=\"TeacherNameCell\"><a href=\"mailto:jmellen1@kleinisd.net\" class=\"EmailLink\">Mellen, J</a></th><td align=\"left\">COMPUTER SCI HL -IB</td><td>1</td><td><a href=\"?data=MXw1OTY2MDR8MTEwMTN8MzQyOHwzfDEwMTkxNXwz\" class=\"Grade\" title=\"Teacher Mellen, J Course COMPUTER SCI HL -IB Period 1 Cycle 1 Grade 99\">99</a></td><td><a href=\"?data=Mnw1OTY2MDR8MTEwMTN8MzQyOHwzfDEwMTkxNXwz\" class=\"Grade\" title=\"Teacher Mellen, J Course COMPUTER SCI HL -IB Period 1 Cycle 2 Grade 95\">95</a></td><td> </td><td> </td><td><span class=\"Grade\" title=\"Teacher Mellen, J Course COMPUTER SCI HL -IB Period 1 Semester 1 Grade 97\">97</span></td><td> </td><td> </td><td> </td><td> </td><td> </td></tr><tr class=\"DataRowAlt\">"
+"<th align=\"left\" scope=\"row\" class=\"TeacherNameCell\"><a href=\"mailto:sparent1@kleinisd.net\" class=\"EmailLink\">Parent, S</a></th><td align=\"left\">HIST OF AMERICAS HL -IB</td><td>2</td><td><a href=\"?data=MXw1OTY2MDR8MTAzMjJ8MzQxMnwzfDEwMTkxNXwz\" class=\"Grade\" title=\"Teacher Parent, S Course HIST OF AMERICAS HL -IB Period 2 Cycle 1 Grade 95\">95</a></td><td><a href=\"?data=Mnw1OTY2MDR8MTAzMjJ8MzQxMnwzfDEwMTkxNXwz\" class=\"Grade\" title=\"Teacher Parent, S Course HIST OF AMERICAS HL -IB Period 2 Cycle 2 Grade 100\">100</a></td><td> </td><td> </td><td><span class=\"Grade\" title=\"Teacher Parent, S Course HIST OF AMERICAS HL -IB Period 2 Semester 1 Grade 98\">98</span></td><td> </td><td> </td><td> </td><td> </td><td> </td></tr><tr class=\"DataRow\">"
+"<th align=\"left\" scope=\"row\" class=\"TeacherNameCell\"><a href=\"mailto:brice1@kleinisd.net\" class=\"EmailLink\">Rice, B</a></th><td align=\"left\">MATHEMATICS HL -IB</td><td>3</td><td><a href=\"?data=MXw1OTY2MDR8MTAxNzB8MzQyNHwxfDEwMTkxNXwz\" class=\"Grade\" title=\"Teacher Rice, B Course MATHEMATICS HL -IB Period 3 Cycle 1 Grade 92\">92</a></td><td><a href=\"?data=Mnw1OTY2MDR8MTAxNzB8MzQyNHwxfDEwMTkxNXwz\" class=\"Grade\" title=\"Teacher Rice, B Course MATHEMATICS HL -IB Period 3 Cycle 2 Grade 90\">90</a></td><td> </td><td> </td><td><span class=\"Grade\" title=\"Teacher Rice, B Course MATHEMATICS HL -IB Period 3 Semester 1 Grade 91\">91</span></td><td> </td><td> </td><td> </td><td> </td><td> </td></tr><tr class=\"DataRowAlt\">"
+"<th align=\"left\" scope=\"row\" class=\"TeacherNameCell\"><a href=\"mailto:lgarner@kleinisd.net\" class=\"EmailLink\">Garner, L</a></th><td align=\"left\">ENGLISH 4 -IB</td><td>4</td><td><a href=\"?data=MXw1OTY2MDR8NTUxMHwzNDAyfDR8MTAxOTE1fDM%3d\" class=\"Grade\" title=\"Teacher Garner, L Course ENGLISH 4 -IB Period 4 Cycle 1 Grade 93\">93</a></td><td><a href=\"?data=Mnw1OTY2MDR8NTUxMHwzNDAyfDR8MTAxOTE1fDM%3d\" class=\"Grade\" title=\"Teacher Garner, L Course ENGLISH 4 -IB Period 4 Cycle 2 Grade 97\">97</a></td><td> </td><td> </td><td><span class=\"Grade\" title=\"Teacher Garner, L Course ENGLISH 4 -IB Period 4 Semester 1 Grade 95\">95</span></td><td> </td><td> </td><td> </td><td> </td><td> </td></tr><tr class=\"DataRow\">"
+"<th align=\"left\" scope=\"row\" class=\"TeacherNameCell\"><a href=\"mailto:jmellen1@kleinisd.net\" class=\"EmailLink\">Mellen, J</a></th><td align=\"left\">IND STUDY EMERG TECH</td><td>5</td><td><a href=\"?data=MXw1OTY2MDR8MTEwMTN8NDkzNnwxfDEwMTkxNXwz\" class=\"Grade\" title=\"Teacher Mellen, J Course IND STUDY EMERG TECH Period 5 Cycle 1 Grade 100\">100</a></td><td><a href=\"?data=Mnw1OTY2MDR8MTEwMTN8NDkzNnwxfDEwMTkxNXwz\" class=\"Grade\" title=\"Teacher Mellen, J Course IND STUDY EMERG TECH Period 5 Cycle 2 Grade 100\">100</a></td><td> </td><td> </td><td><span class=\"Grade\" title=\"Teacher Mellen, J Course IND STUDY EMERG TECH Period 5 Semester 1 Grade 100\">100</span></td><td> </td><td> </td><td> </td><td> </td><td> </td></tr><tr class=\"DataRowAlt\">'"
+"<th align=\"left\" scope=\"row\" class=\"TeacherNameCell\"><a href=\"mailto:aparent1@kleinisd.net\" class=\"EmailLink\">Parent, A</a></th><td align=\"left\">PHYSICS 2 -IB</td><td>6</td><td><a href=\"?data=MXw1OTY2MDR8MTE0ODh8MzQzOHwxfDEwMTkxNXwz\" class=\"Grade\" title=\"Teacher Parent, A Course PHYSICS 2 -IB Period 6 Cycle 1 Grade 96\">96</a></td><td><a href=\"?data=Mnw1OTY2MDR8MTE0ODh8MzQzOHwxfDEwMTkxNXwz\" class=\"Grade\" title=\"Teacher Parent, A Course PHYSICS 2 -IB Period 6 Cycle 2 Grade 99\">99</a></td><td> </td><td> </td><td><span class=\"Grade\" title=\"Teacher Parent, A Course PHYSICS 2 -IB Period 6 Semester 1 Grade 98\">98</span></td><td> </td><td> </td><td> </td><td> </td><td> </td></tr><tr class=\"DataRow\">"
+"<th align=\"left\" scope=\"row\" class=\"TeacherNameCell\"><a href=\"mailto:rtumlinson@kleinisd.net\" class=\"EmailLink\">Tumlinson, R</a></th><td align=\"left\">THEORY OF KNOWL A -IB</td><td>7</td><td><a href=\"?data=MXw1OTY2MDR8NTU2NHwzNDY4QXwyfDEwMTkxNXwz\" class=\"Grade\" title=\"Teacher Tumlinson, R Course THEORY OF KNOWL A -IB Period 7 Cycle 1 Grade 93\">93</a></td><td><a href=\"?data=Mnw1OTY2MDR8NTU2NHwzNDY4QXwyfDEwMTkxNXwz\" class=\"Grade\" title=\"Teacher Tumlinson, R Course THEORY OF KNOWL A -IB Period 7 Cycle 2 Grade 85\">85</a></td><td> </td><td> </td><td><span class=\"Grade\" title=\"Teacher Tumlinson, R Course THEORY OF KNOWL A -IB Period 7 Semester 1 Grade 89\">89</span></td><td> </td><td> </td><td> </td><td> </td><td> </td></tr></table> </P></div>";
//extrapolate(code);
String html = code;//getHTML();
int c = getCycle(html);
ArrayList<Grade> cycle = extrapolate(html, c);
out.println(cycle.toString());
}
public static String getHTML() throws Exception{
//Log in
long start = System.currentTimeMillis();
out.println("Logging in...");
- String password = "Cocacola1";
+ String username = "";
+ String password = "";
Response res = Jsoup
.connect("https://gradespeed.kleinisd.net/pc/Default.aspx")
- .data("txtUserName", "plankenau")
+ .data("txtUserName", username)
.data("txtPassWord", password)
.method(Method.POST)
.execute();
Document doc = res.parse();
out.println("Logged in ("+((System.currentTimeMillis()-start)/1000F)+" secs)"); //;
start = System.currentTimeMillis();
//Keep logged in
Map<String, String> cookies = res.cookies();
Document doc2 = Jsoup
.connect("https://gradespeed.kleinisd.net/pc/ParentStudentGrades.aspx")
.cookies(cookies)
.get();
String codehtml = doc2.body().html();
out.println("Fetched ("+((System.currentTimeMillis()-start)/1000F)+ " secs)");
start = System.currentTimeMillis();
String code = codehtml.split("var")[1];
code = code.split("</script>")[0];
code = code.replaceAll("[ ]", "");
String var = code.substring(0,code.indexOf(";")); //might have to -1
code = code.replaceAll(var+";","");
code = code.replaceAll(var+"='';","");
code = code.replaceAll(var+"="+var+"+", "");
code = code.replace("';", "");
code = code.replace("+'", "");
//code = code.replaceAll(var,"VAR");
code = code.replace("document.write(decodeString("+var+"));", "");
code = code.replace("-->", "");
code = code.replaceAll("\\n","");
code = code.replaceAll("\\r","");
String decoded = decode(code);
out.println("Decoded ("+((System.currentTimeMillis()-start)/1000F)+ " secs)");
return decoded;
}
public static void print(String what) throws Exception{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("print.out")));
out.println(what);
out.flush();
out.close();
}
public static void print(String code, String decoded) throws Exception{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("coded.out")));
PrintWriter out2 = new PrintWriter(new BufferedWriter(new FileWriter("decoded.out")));
out.println(code);
out.flush();
out.close();
out2.println(decoded);
out2.flush();
out2.close();
}
public static ArrayList<Grade> extrapolate(String html, int cycle){
Document doc = Jsoup.parse(html);
Elements links = doc.select("[href]");
links = links.select("[title*=Cycle "+cycle+"]");
ArrayList<Grade> grades = new ArrayList<Grade>(); //what this kolaveri?
for (Element a: links){
Grade grade = new Grade(a.attr("title"));
grades.add(grade);
System.out.println(grades);
}
return grades;
}
public static int getCycle(String html){
Document doc = Jsoup.parse(html);
Elements links = doc.select("[href]");
links = links.select("[title*=Cycle]");
ArrayList<Integer> cycles = new ArrayList<Integer>();
for (Element e : links){
String t = e.attr("title");
cycles.add(Integer.parseInt(t.substring(t.indexOf("Cycle ")+6,t.indexOf(" Grade"))));
}
Collections.sort(cycles);
return cycles.get(cycles.size()-1);
}
public static String decode(String input) {
String keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
String output = "";
int chr1, chr2, chr3;
int enc1, enc2, enc3, enc4;
int i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
input = input.replaceAll("/[^A-Za-z0-9\\+\\/\\=]/g", "");
do {
try{
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output += (char)(chr1);
if (enc3 != 64) {
output += (char)(chr2);
}
if (enc4 != 64) {
output += (char)(chr3);
}
}catch (Exception e){
err.println("ERROR i:"+i+" \n "+e);
}
}while (i<input.length()-input.length()%4);
return output;
}
}
| false | true | public static String getHTML() throws Exception{
//Log in
long start = System.currentTimeMillis();
out.println("Logging in...");
String password = "Cocacola1";
Response res = Jsoup
.connect("https://gradespeed.kleinisd.net/pc/Default.aspx")
.data("txtUserName", "plankenau")
.data("txtPassWord", password)
.method(Method.POST)
.execute();
Document doc = res.parse();
out.println("Logged in ("+((System.currentTimeMillis()-start)/1000F)+" secs)"); //;
start = System.currentTimeMillis();
//Keep logged in
Map<String, String> cookies = res.cookies();
Document doc2 = Jsoup
.connect("https://gradespeed.kleinisd.net/pc/ParentStudentGrades.aspx")
.cookies(cookies)
.get();
String codehtml = doc2.body().html();
out.println("Fetched ("+((System.currentTimeMillis()-start)/1000F)+ " secs)");
start = System.currentTimeMillis();
String code = codehtml.split("var")[1];
code = code.split("</script>")[0];
code = code.replaceAll("[ ]", "");
String var = code.substring(0,code.indexOf(";")); //might have to -1
code = code.replaceAll(var+";","");
code = code.replaceAll(var+"='';","");
code = code.replaceAll(var+"="+var+"+", "");
code = code.replace("';", "");
code = code.replace("+'", "");
//code = code.replaceAll(var,"VAR");
code = code.replace("document.write(decodeString("+var+"));", "");
code = code.replace("-->", "");
code = code.replaceAll("\\n","");
code = code.replaceAll("\\r","");
String decoded = decode(code);
out.println("Decoded ("+((System.currentTimeMillis()-start)/1000F)+ " secs)");
return decoded;
}
| public static String getHTML() throws Exception{
//Log in
long start = System.currentTimeMillis();
out.println("Logging in...");
String username = "";
String password = "";
Response res = Jsoup
.connect("https://gradespeed.kleinisd.net/pc/Default.aspx")
.data("txtUserName", username)
.data("txtPassWord", password)
.method(Method.POST)
.execute();
Document doc = res.parse();
out.println("Logged in ("+((System.currentTimeMillis()-start)/1000F)+" secs)"); //;
start = System.currentTimeMillis();
//Keep logged in
Map<String, String> cookies = res.cookies();
Document doc2 = Jsoup
.connect("https://gradespeed.kleinisd.net/pc/ParentStudentGrades.aspx")
.cookies(cookies)
.get();
String codehtml = doc2.body().html();
out.println("Fetched ("+((System.currentTimeMillis()-start)/1000F)+ " secs)");
start = System.currentTimeMillis();
String code = codehtml.split("var")[1];
code = code.split("</script>")[0];
code = code.replaceAll("[ ]", "");
String var = code.substring(0,code.indexOf(";")); //might have to -1
code = code.replaceAll(var+";","");
code = code.replaceAll(var+"='';","");
code = code.replaceAll(var+"="+var+"+", "");
code = code.replace("';", "");
code = code.replace("+'", "");
//code = code.replaceAll(var,"VAR");
code = code.replace("document.write(decodeString("+var+"));", "");
code = code.replace("-->", "");
code = code.replaceAll("\\n","");
code = code.replaceAll("\\r","");
String decoded = decode(code);
out.println("Decoded ("+((System.currentTimeMillis()-start)/1000F)+ " secs)");
return decoded;
}
|
diff --git a/sensor/src/main/java/dk/dtu/imm/distributedsystems/projects/sensornetwork/sensor/Sensor.java b/sensor/src/main/java/dk/dtu/imm/distributedsystems/projects/sensornetwork/sensor/Sensor.java
index 7bbc11c..fced9a4 100644
--- a/sensor/src/main/java/dk/dtu/imm/distributedsystems/projects/sensornetwork/sensor/Sensor.java
+++ b/sensor/src/main/java/dk/dtu/imm/distributedsystems/projects/sensornetwork/sensor/Sensor.java
@@ -1,69 +1,71 @@
package dk.dtu.imm.distributedsystems.projects.sensornetwork.sensor;
import java.util.Scanner;
import dk.dtu.imm.distributedsystems.projects.sensornetwork.common.channels.Channel;
import dk.dtu.imm.distributedsystems.projects.sensornetwork.common.exceptions.NodeInitializationException;
import dk.dtu.imm.distributedsystems.projects.sensornetwork.common.nodes.AbstractNode;
import dk.dtu.imm.distributedsystems.projects.sensornetwork.sensor.components.SensorComponent;
import dk.dtu.imm.distributedsystems.projects.sensornetwork.sensor.components.TransceiverComponent;
/**
* Sensor Node for Sensor Network
*
*/
public class Sensor extends AbstractNode {
private TransceiverComponent transceiverComponent;
private SensorComponent sensorComponent;
public Sensor(String id, int period, int threshold, int leftPortNumber,
int rightPortNumber, Channel[] leftChannels,
Channel[] rightChannels, int ackTimeout) {
super(id);
this.transceiverComponent = new TransceiverComponent(id, leftPortNumber,
rightPortNumber, leftChannels, rightChannels,
ackTimeout);
this.sensorComponent = new SensorComponent(id, this.transceiverComponent,
period, threshold);
}
public TransceiverComponent getTransceiverComponent() {
return transceiverComponent;
}
public SensorComponent getSensorComponent() {
return sensorComponent;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out
.println("Please provide only one parameter - a suitable property file");
return;
}
Sensor sensor = null;
try {
sensor = SensorUtility.getSensorInstance(args[0]);
} catch (NodeInitializationException e) {
System.out.println(e.getMessage());
return;
}
Scanner in = new Scanner(System.in);
in.next();
in.close();
System.out.println("Done");
+ sensor.transceiverComponent.close();
+ sensor.sensorComponent.interrupt();
}
}
| true | true | public static void main(String[] args) {
if (args.length != 1) {
System.out
.println("Please provide only one parameter - a suitable property file");
return;
}
Sensor sensor = null;
try {
sensor = SensorUtility.getSensorInstance(args[0]);
} catch (NodeInitializationException e) {
System.out.println(e.getMessage());
return;
}
Scanner in = new Scanner(System.in);
in.next();
in.close();
System.out.println("Done");
}
| public static void main(String[] args) {
if (args.length != 1) {
System.out
.println("Please provide only one parameter - a suitable property file");
return;
}
Sensor sensor = null;
try {
sensor = SensorUtility.getSensorInstance(args[0]);
} catch (NodeInitializationException e) {
System.out.println(e.getMessage());
return;
}
Scanner in = new Scanner(System.in);
in.next();
in.close();
System.out.println("Done");
sensor.transceiverComponent.close();
sensor.sensorComponent.interrupt();
}
|
diff --git a/src/notifier/SRMNotifierServlet.java b/src/notifier/SRMNotifierServlet.java
index 75a9963..9bb2e85 100755
--- a/src/notifier/SRMNotifierServlet.java
+++ b/src/notifier/SRMNotifierServlet.java
@@ -1,132 +1,132 @@
package notifier;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import notifier.parser.SRMCalendarParser;
import twitter4j.TwitterException;
@SuppressWarnings("serial")
public class SRMNotifierServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(SRMNotifierServlet.class
.getName());
private static final String hash = "#Topcoder #SRM";
private static final SimpleDateFormat format = SRMCalendarParser.getDataFormat();
private static final String[] msgs = { "開始24時間前です", "開始12時間前です",
"登録を開始しました", "開始1時間前です", "開始30分前です", "開始15分前です", "開始5分前です",
"Coding Phase を開始しました", "Coding Phase を終了しました",
"Challenge Phase を開始しました", "終了しました" };
private static final long[] dates = { -toLong(24, 60), -toLong(12, 60),
-toLong(3, 60), -toLong(1, 60), -toLong(1, 30), -toLong(1, 15),
-toLong(1, 5), 0, toLong(1, 75), toLong(1, 80), toLong(1, 95) };
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
log.info("場所(Locale):" + Locale.getDefault());
GregorianCalendar cal = new GregorianCalendar();
Date now = cal.getTime();
log.info("[" + now + ":" + format.format(now) + "]");
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
log.info("更新時間(分):" + cal.get(Calendar.MINUTE) + " 更新時間(時):"
+ cal.get(Calendar.HOUR_OF_DAY));
SRM srm = getNearestSRM(pm);
log.info("srm :" + srm.toString());
log.info("compeTime :" + format.format(srm.getCompetisionTime()));
Date target = new Date(srm.getCompetisionTime().getTime()
+ dates[srm.getCount()]);
log.info("通知判定 [now:" + format.format(now) + "].after[target:"
+ format.format(target) + "]==" + now.after(target));
log.info("通知判定 " + now.after(target));
while (now.after(target)) {
// 通知判定
if (now.before(new Date(target.getTime() + toLong(1, 4)))) { //
String notifyDate = "at " + format.format(target);
- if (srm.getCount() < 3) {
+ if (srm.getCount() < 8) {
notifyDate = "開始時間: " + format.format(srm.getCompetisionTime());
}
post(msgs[srm.getCount()], srm, notifyDate);
}
srm.setCount(srm.getCount() + 1);
// SRM終了判定
if (srm.getCount() >= dates.length) {
SRM nextSrm = getSecondNearestSRM(pm);
postNextSRM(nextSrm); // 消すついでに次のSRMの時間も告知
pm.deletePersistent(srm);
log.info(srm.getName() + "のデータを削除");
break;
}
target = new Date(srm.getCompetisionTime().getTime()
+ dates[srm.getCount()]);
}
} catch (Exception e) {
log.warning(e.getMessage());
} finally {
pm.close();
}
}
@SuppressWarnings("unchecked")
private SRM getNearestSRM(PersistenceManager pm) {
Query query = pm.newQuery(SRM.class);
query.setRange(0, 1);
query.setOrdering("competisionTime");
List<SRM> srms = (List<SRM>) query.execute();
SRM srm = srms.get(0);
log.info("最近傍SRM取得:" + srm);
return srm;
}
// SRMが終わったときに次のSRMを通知するため.3・12金
@SuppressWarnings("unchecked")
private SRM getSecondNearestSRM(PersistenceManager pm) {
Query query = pm.newQuery(SRM.class);
query.setRange(1, 2);
query.setOrdering("competisionTime");
List<SRM> srms = (List<SRM>) query.execute();
SRM srm = srms.get(0);
log.info("準最近傍SRM取得:" + srm);
return srm;
}
private void post(String msg, SRM srm, String date) throws TwitterException {
// Twitter twitter;
// SRM 463 終了しました at 2010年03月02日(火) 22時35分 #Topcoder #SRM
String status = srm.getName() + " " + msg + " " + date;
if (2 <= srm.getCount() && srm.getCount() <= 7) {
status += " Arena -> http://bit.ly/gloK93";
}
status += " " + hash;
TwitterManager.post(status);
}
// 次のSRMをpostするため
private void postNextSRM(SRM srm) throws TwitterException {
// Twitter twitter;
// 次の SRM000 は 20XX年XX月XX日(X) XX時XX分 からです #Topcoder #SRM
String status = "次の " + srm.getName() + " は "
+ format.format(srm.getCompetisionTime()) + " からです " + hash;
TwitterManager.post(status);
}
private static long toLong(int hour, int minute) {
return hour * minute * 60 * 1000;
}
}
| true | true | public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
log.info("場所(Locale):" + Locale.getDefault());
GregorianCalendar cal = new GregorianCalendar();
Date now = cal.getTime();
log.info("[" + now + ":" + format.format(now) + "]");
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
log.info("更新時間(分):" + cal.get(Calendar.MINUTE) + " 更新時間(時):"
+ cal.get(Calendar.HOUR_OF_DAY));
SRM srm = getNearestSRM(pm);
log.info("srm :" + srm.toString());
log.info("compeTime :" + format.format(srm.getCompetisionTime()));
Date target = new Date(srm.getCompetisionTime().getTime()
+ dates[srm.getCount()]);
log.info("通知判定 [now:" + format.format(now) + "].after[target:"
+ format.format(target) + "]==" + now.after(target));
log.info("通知判定 " + now.after(target));
while (now.after(target)) {
// 通知判定
if (now.before(new Date(target.getTime() + toLong(1, 4)))) { //
String notifyDate = "at " + format.format(target);
if (srm.getCount() < 3) {
notifyDate = "開始時間: " + format.format(srm.getCompetisionTime());
}
post(msgs[srm.getCount()], srm, notifyDate);
}
srm.setCount(srm.getCount() + 1);
// SRM終了判定
if (srm.getCount() >= dates.length) {
SRM nextSrm = getSecondNearestSRM(pm);
postNextSRM(nextSrm); // 消すついでに次のSRMの時間も告知
pm.deletePersistent(srm);
log.info(srm.getName() + "のデータを削除");
break;
}
target = new Date(srm.getCompetisionTime().getTime()
+ dates[srm.getCount()]);
}
} catch (Exception e) {
log.warning(e.getMessage());
} finally {
pm.close();
}
}
| public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
log.info("場所(Locale):" + Locale.getDefault());
GregorianCalendar cal = new GregorianCalendar();
Date now = cal.getTime();
log.info("[" + now + ":" + format.format(now) + "]");
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
log.info("更新時間(分):" + cal.get(Calendar.MINUTE) + " 更新時間(時):"
+ cal.get(Calendar.HOUR_OF_DAY));
SRM srm = getNearestSRM(pm);
log.info("srm :" + srm.toString());
log.info("compeTime :" + format.format(srm.getCompetisionTime()));
Date target = new Date(srm.getCompetisionTime().getTime()
+ dates[srm.getCount()]);
log.info("通知判定 [now:" + format.format(now) + "].after[target:"
+ format.format(target) + "]==" + now.after(target));
log.info("通知判定 " + now.after(target));
while (now.after(target)) {
// 通知判定
if (now.before(new Date(target.getTime() + toLong(1, 4)))) { //
String notifyDate = "at " + format.format(target);
if (srm.getCount() < 8) {
notifyDate = "開始時間: " + format.format(srm.getCompetisionTime());
}
post(msgs[srm.getCount()], srm, notifyDate);
}
srm.setCount(srm.getCount() + 1);
// SRM終了判定
if (srm.getCount() >= dates.length) {
SRM nextSrm = getSecondNearestSRM(pm);
postNextSRM(nextSrm); // 消すついでに次のSRMの時間も告知
pm.deletePersistent(srm);
log.info(srm.getName() + "のデータを削除");
break;
}
target = new Date(srm.getCompetisionTime().getTime()
+ dates[srm.getCount()]);
}
} catch (Exception e) {
log.warning(e.getMessage());
} finally {
pm.close();
}
}
|
diff --git a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/commands/RemoveElementHandler.java b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/commands/RemoveElementHandler.java
index ea8d30f..a3da15c 100644
--- a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/commands/RemoveElementHandler.java
+++ b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/commands/RemoveElementHandler.java
@@ -1,82 +1,92 @@
// $codepro.audit.disable com.instantiations.assist.eclipse.analysis.audit.rule.effectivejava.alwaysOverridetoString.alwaysOverrideToString, com.instantiations.assist.eclipse.analysis.deserializeabilitySecurity, com.instantiations.assist.eclipse.analysis.disallowReturnMutable, com.instantiations.assist.eclipse.analysis.enforceCloneableUsageSecurity
/*******************************************************************************
* Copyright (c) 2010 Ericsson Research Canada
*
* 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
*
* Description:
*
* This class implements the context-sensitive command used
* to remove the currently selected element form the model
*
* Contributors:
* Sebastien Dubois - Created for Mylyn Review R4E project
*
******************************************************************************/
package org.eclipse.mylyn.reviews.r4e.ui.commands;
import java.util.Iterator;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.OutOfSyncException;
import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.ResourceHandlingException;
import org.eclipse.mylyn.reviews.r4e.ui.Activator;
import org.eclipse.mylyn.reviews.r4e.ui.model.IR4EUIModelElement;
import org.eclipse.mylyn.reviews.r4e.ui.utils.UIUtils;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* @author lmcdubo
* @version $Revision: 1.0 $
*/
public class RemoveElementHandler extends AbstractHandler {
// ------------------------------------------------------------------------
// Methods
// ------------------------------------------------------------------------
/**
* Method execute.
* @param event ExecutionEvent
* @return Object
* @throws ExecutionException
* @see org.eclipse.core.commands.IHandler#execute(ExecutionEvent)
*/
public Object execute(ExecutionEvent event) {
final IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
if (!selection.isEmpty()) {
IR4EUIModelElement element = null;
MessageDialogWithToggle dialog = null;
for (final Iterator<?> iterator = selection.iterator(); iterator.hasNext();) {
element = (IR4EUIModelElement) iterator.next();
Activator.Ftracer.traceInfo("Disable element " + element.getName());
dialog = MessageDialogWithToggle.openOkCancelConfirm(null,
"Disable element",
"Do you really want to disable this element?",
"Also delete from file (not supported yet)",
false,
null,
null);
if (dialog.getReturnCode() == Window.OK) {
try {
+ //First close element if is it open
+ if (element.isOpen()) {
+ element.close();
+ for (IR4EUIModelElement childElement: element.getChildren()) {
+ if (null != childElement && childElement.isOpen()) {
+ childElement.close();
+ break;
+ }
+ }
+ }
element.getParent().removeChildren(element, dialog.getToggleState());
} catch (ResourceHandlingException e) {
UIUtils.displayResourceErrorDialog(e);
} catch (OutOfSyncException e) {
UIUtils.displaySyncErrorDialog(e);
}
}
}
}
return null;
}
}
| true | true | public Object execute(ExecutionEvent event) {
final IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
if (!selection.isEmpty()) {
IR4EUIModelElement element = null;
MessageDialogWithToggle dialog = null;
for (final Iterator<?> iterator = selection.iterator(); iterator.hasNext();) {
element = (IR4EUIModelElement) iterator.next();
Activator.Ftracer.traceInfo("Disable element " + element.getName());
dialog = MessageDialogWithToggle.openOkCancelConfirm(null,
"Disable element",
"Do you really want to disable this element?",
"Also delete from file (not supported yet)",
false,
null,
null);
if (dialog.getReturnCode() == Window.OK) {
try {
element.getParent().removeChildren(element, dialog.getToggleState());
} catch (ResourceHandlingException e) {
UIUtils.displayResourceErrorDialog(e);
} catch (OutOfSyncException e) {
UIUtils.displaySyncErrorDialog(e);
}
}
}
}
return null;
}
| public Object execute(ExecutionEvent event) {
final IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
if (!selection.isEmpty()) {
IR4EUIModelElement element = null;
MessageDialogWithToggle dialog = null;
for (final Iterator<?> iterator = selection.iterator(); iterator.hasNext();) {
element = (IR4EUIModelElement) iterator.next();
Activator.Ftracer.traceInfo("Disable element " + element.getName());
dialog = MessageDialogWithToggle.openOkCancelConfirm(null,
"Disable element",
"Do you really want to disable this element?",
"Also delete from file (not supported yet)",
false,
null,
null);
if (dialog.getReturnCode() == Window.OK) {
try {
//First close element if is it open
if (element.isOpen()) {
element.close();
for (IR4EUIModelElement childElement: element.getChildren()) {
if (null != childElement && childElement.isOpen()) {
childElement.close();
break;
}
}
}
element.getParent().removeChildren(element, dialog.getToggleState());
} catch (ResourceHandlingException e) {
UIUtils.displayResourceErrorDialog(e);
} catch (OutOfSyncException e) {
UIUtils.displaySyncErrorDialog(e);
}
}
}
}
return null;
}
|
diff --git a/src/net/sf/freecol/client/gui/panel/NegotiationDialog.java b/src/net/sf/freecol/client/gui/panel/NegotiationDialog.java
index fa0367f1e..c20ef27b4 100644
--- a/src/net/sf/freecol/client/gui/panel/NegotiationDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/NegotiationDialog.java
@@ -1,730 +1,730 @@
package net.sf.freecol.client.gui.panel;
import java.awt.Color;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextPane;
import javax.swing.SpinnerNumberModel;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.Canvas;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.ColonyTradeItem;
import net.sf.freecol.common.model.DiplomaticTrade;
import net.sf.freecol.common.model.GoldTradeItem;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsTradeItem;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.StanceTradeItem;
import net.sf.freecol.common.model.TradeItem;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.UnitTradeItem;
import org.w3c.dom.Element;
import cz.autel.dmi.HIGLayout;
/**
* The panel that allows negotiations between players.
*/
public final class NegotiationDialog extends FreeColDialog implements ActionListener {
public static final String COPYRIGHT = "Copyright (C) 2003-2007 The FreeCol Team";
public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html";
public static final String REVISION = "$Revision$";
private static final String SEND = "send", ACCEPT = "accept", CANCEL = "cancel";
private static Logger logger = Logger.getLogger(NegotiationDialog.class.getName());
private FreeColClient freeColClient;
private DiplomaticTrade agreement;
private JButton acceptButton, cancelButton, sendButton;
private StanceTradeItemPanel stance;
private GoldTradeItemPanel goldOffer, goldDemand;
private ColonyTradeItemPanel colonyOffer, colonyDemand;
private GoodsTradeItemPanel goodsOffer, goodsDemand;
//private UnitTradeItemPanel unitOffer, unitDemand;
private JTextPane summary;
private final Unit unit;
private final Settlement settlement;
private Player player;
private Player otherPlayer;
private Player sender;
private Player recipient;
private boolean canAccept;
/**
* Creates a new <code>NegotiationDialog</code> instance.
*
* @param parent a <code>Canvas</code> value
* @param unit an <code>Unit</code> value
* @param settlement a <code>Settlement</code> value
*/
public NegotiationDialog(Canvas parent, Unit unit, Settlement settlement) {
this(parent, unit, settlement, null);
}
/**
* Creates a new <code>NegotiationDialog</code> instance.
*
* @param parent a <code>Canvas</code> value
* @param unit an <code>Unit</code> value
* @param settlement a <code>Settlement</code> value
* @param agreement a <code>DiplomaticTrade</code> with the offer
*/
public NegotiationDialog(Canvas parent, Unit unit, Settlement settlement, DiplomaticTrade agreement) {
super(parent);
setFocusCycleRoot(true);
this.unit = unit;
this.settlement = settlement;
this.freeColClient = parent.getClient();
this.player = freeColClient.getMyPlayer();
this.sender = unit.getOwner();
this.recipient = settlement.getOwner();
this.canAccept = agreement != null; // a new offer can't be accepted
if (agreement == null) {
this.agreement = new DiplomaticTrade(unit.getGame(), sender, recipient);
} else {
this.agreement = agreement;
}
if (sender == player) {
this.otherPlayer = recipient;
} else {
this.otherPlayer = sender;
}
if (player.getStance(otherPlayer) == Player.WAR) {
if (!hasPeaceOffer()) {
int stance = Player.PEACE;
this.agreement.add(new StanceTradeItem(freeColClient.getGame(), player, otherPlayer, stance));
}
}
summary = new JTextPane();
summary.setOpaque(false);
summary.setEditable(false);
StyledDocument document = summary.getStyledDocument();
//Initialize some styles.
Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style regular = document.addStyle("regular", def);
StyleConstants.setFontFamily(def, "Dialog");
StyleConstants.setBold(def, true);
StyleConstants.setFontSize(def, 12);
Style buttonStyle = document.addStyle("button", regular);
StyleConstants.setForeground(buttonStyle, LINK_COLOR);
}
/**
* Set up the dialog.
*
*/
public void initialize() {
int foreignGold = 0;
Element report = getCanvas().getClient().getInGameController().getForeignAffairsReport();
int number = report.getChildNodes().getLength();
for (int i = 0; i < number; i++) {
Element enemyElement = (Element) report.getChildNodes().item(i);
int nationID = Integer.parseInt(enemyElement.getAttribute("nation"));
if (nationID == otherPlayer.getNation()) {
foreignGold = Integer.parseInt(enemyElement.getAttribute("gold"));
break;
}
}
sendButton = new JButton(Messages.message("negotiationDialog.send"));
sendButton.addActionListener(this);
sendButton.setActionCommand(SEND);
FreeColPanel.enterPressesWhenFocused(sendButton);
acceptButton = new JButton(Messages.message("negotiationDialog.accept"));
acceptButton.addActionListener(this);
acceptButton.setActionCommand(ACCEPT);
FreeColPanel.enterPressesWhenFocused(acceptButton);
acceptButton.setEnabled(canAccept);
cancelButton = new JButton(Messages.message("negotiationDialog.cancel"));
cancelButton.addActionListener(this);
cancelButton.setActionCommand(CANCEL);
setCancelComponent(cancelButton);
FreeColPanel.enterPressesWhenFocused(cancelButton);
updateSummary();
stance = new StanceTradeItemPanel(this, player, otherPlayer);
goldDemand = new GoldTradeItemPanel(this, otherPlayer, foreignGold);
goldOffer = new GoldTradeItemPanel(this, player, player.getGold());
- goodsDemand = new GoodsTradeItemPanel(this, otherPlayer, settlement.getGoodsContainer().getGoods());
- goodsOffer = new GoodsTradeItemPanel(this, player, unit.getGoodsContainer().getGoods());
colonyDemand = new ColonyTradeItemPanel(this, otherPlayer);
colonyOffer = new ColonyTradeItemPanel(this, player);
/** TODO: UnitTrade
unitDemand = new UnitTradeItemPanel(this, otherPlayer);
unitOffer = new UnitTradeItemPanel(this, player);
*/
int numberOfTradeItems = 4;
int extraRows = 2; // headline and buttons
int[] widths = {200, 10, 300, 10, 200};
int[] heights = new int[2 * (numberOfTradeItems + extraRows) - 1];
for (int index = 1; index < heights.length; index += 2) {
heights[index] = 10;
}
setLayout(new HIGLayout(widths, heights));
int demandColumn = 1;
int summaryColumn = 3;
int offerColumn = 5;
int row = 1;
add(new JLabel(Messages.message("negotiationDialog.demand")),
higConst.rc(row, demandColumn));
add(new JLabel(Messages.message("negotiationDialog.offer")),
higConst.rc(row, offerColumn));
row += 2;
add(stance, higConst.rc(row, offerColumn));
row += 2;
add(goldDemand, higConst.rc(row, demandColumn));
add(goldOffer, higConst.rc(row, offerColumn));
add(summary, higConst.rcwh(row, summaryColumn, 1, 5));
row += 2;
if (unit.isCarrier()) {
+ goodsDemand = new GoodsTradeItemPanel(this, otherPlayer, settlement.getGoodsContainer().getGoods());
add(goodsDemand, higConst.rc(row, demandColumn));
+ goodsOffer = new GoodsTradeItemPanel(this, player, unit.getGoodsContainer().getGoods());
add(goodsOffer, higConst.rc(row, offerColumn));
} else {
add(colonyDemand, higConst.rc(row, demandColumn));
add(colonyOffer, higConst.rc(row, offerColumn));
}
row += 2;
/** TODO: UnitTrade
add(unitDemand, higConst.rc(row, demandColumn));
add(unitOffer, higConst.rc(row, offerColumn));
*/
row += 2;
add(sendButton, higConst.rc(row, demandColumn, ""));
add(acceptButton, higConst.rc(row, summaryColumn, ""));
add(cancelButton, higConst.rc(row, offerColumn, ""));
}
private void updateSummary() {
try {
StyledDocument document = summary.getStyledDocument();
document.remove(0, document.getLength());
String input = Messages.message("negotiationDialog.summary");
int start = input.indexOf('%');
if (start == -1) {
// no variables present
insertText(input.substring(0));
return;
} else if (start > 0) {
// output any string before the first occurence of '%'
insertText(input.substring(0, start));
}
int end;
loop: while ((end = input.indexOf('%', start + 1)) >= 0) {
String var = input.substring(start, end + 1);
if (var.equals("%nation%")) {
insertText(sender.getNationAsString());
start = end + 1;
continue loop;
} else if (var.equals("%offers%")) {
insertOffers();
start = end + 1;
continue loop;
} else if (var.equals("%demands%")) {
insertDemands();
start = end + 1;
continue loop;
} else {
// found no variable to replace: either a single '%', or
// some unnecessary variable
insertText(input.substring(start, end));
start = end;
}
}
// output any string after the last occurence of '%'
if (start < input.length()) {
insertText(input.substring(start));
}
} catch(Exception e) {
logger.warning("Failed to update summary: " + e.toString());
}
}
private void insertText(String text) throws Exception {
StyledDocument document = summary.getStyledDocument();
document.insertString(document.getLength(), text,
document.getStyle("regular"));
}
private void insertOffers() {
insertTradeItemDescriptions(sender);
}
private void insertDemands() {
insertTradeItemDescriptions(recipient);
}
private void insertTradeItemDescriptions(Player itemSource) {
StyledDocument document = summary.getStyledDocument();
List<TradeItem> items = agreement.getTradeItems();
boolean foundItem = false;
for (int index = 0; index < items.size(); index++) {
TradeItem item = items.get(index);
if (item.getSource() == itemSource) {
foundItem = true;
String description = "";
if (item instanceof StanceTradeItem) {
description = Player.getStanceAsString(((StanceTradeItem) item).getStance());
} else if (item instanceof GoldTradeItem) {
String gold = String.valueOf(((GoldTradeItem) item).getGold());
description = Messages.message("tradeItem.gold.long",
new String[][] {{"%amount%", gold}});
} else if (item instanceof ColonyTradeItem) {
description = Messages.message("tradeItem.colony.long",
new String[][] {
{"%colony%", ((ColonyTradeItem) item).getColony().getName()}});
} else if (item instanceof GoodsTradeItem) {
description = String.valueOf(((GoodsTradeItem) item).getGoods().getAmount()) + " " +
((GoodsTradeItem) item).getGoods().getName();
} else if (item instanceof UnitTradeItem) {
description = ((UnitTradeItem) item).getUnit().getName();
}
try {
JButton button = new JButton(description);
button.setMargin(new Insets(0,0,0,0));
button.setOpaque(false);
button.setForeground(LINK_COLOR);
button.setAlignmentY(0.8f);
button.setBorder(BorderFactory.createEmptyBorder());
button.addActionListener(this);
button.setActionCommand(String.valueOf(index));
StyleConstants.setComponent(document.getStyle("button"), button);
document.insertString(document.getLength(), " ", document.getStyle("button"));
if (index < items.size() - 1) {
document.insertString(document.getLength(), ", ", document.getStyle("regular"));
} else {
return;
}
} catch(Exception e) {
logger.warning(e.toString());
}
}
}
if (!foundItem) {
try {
document.insertString(document.getLength(), Messages.message("negotiationDialog.nothing"),
document.getStyle("regular"));
} catch(Exception e) {
logger.warning(e.toString());
}
}
}
private boolean hasPeaceOffer() {
return (getStance() > Integer.MIN_VALUE);
}
/**
* Adds a <code>ColonyTradeItem</code> to the list of TradeItems.
*
* @param source a <code>Player</code> value
* @param colony a <code>Colony</code> value
*/
public void addColonyTradeItem(Player source, Colony colony) {
Player destination;
if (source == otherPlayer) {
destination = player;
} else {
destination = otherPlayer;
}
agreement.add(new ColonyTradeItem(freeColClient.getGame(), source, destination, colony));
}
/**
* Adds a <code>GoldTradeItem</code> to the list of TradeItems.
*
* @param source a <code>Player</code> value
* @param amount an <code>int</code> value
*/
public void addGoldTradeItem(Player source, int amount) {
Player destination;
if (source == otherPlayer) {
destination = player;
} else {
destination = otherPlayer;
}
agreement.add(new GoldTradeItem(freeColClient.getGame(), source, destination, amount));
}
/**
* Adds a <code>GoodsTradeItem</code> to the list of TradeItems.
*
* @param source a <code>Player</code> value
* @param goods a <code>Goods</code> value
*/
public void addGoodsTradeItem(Player source, Goods goods) {
Player destination;
if (source == otherPlayer) {
destination = player;
} else {
destination = otherPlayer;
}
agreement.add(new GoodsTradeItem(freeColClient.getGame(), source, destination, goods, settlement));
}
/**
* Sets the <code>stance</code> between the players.
*
* @param stance an <code>int</code> value
*/
public void setStance(int stance) {
agreement.add(new StanceTradeItem(freeColClient.getGame(), otherPlayer, player, stance));
}
/**
* Returns the stance being offered, or Integer.MIN_VALUE if none
* is being offered.
*
* @return an <code>int</code> value
*/
public int getStance() {
return agreement.getStance();
}
/**
* Analyzes an event and calls the right external methods to take care of
* the user's request.
*
* @param event The incoming action event
*/
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals(CANCEL)) {
setResponse(null);
} else if (command.equals(ACCEPT)) {
agreement.setAccept(true);
setResponse(agreement);
} else if (command.equals(SEND)) {
setResponse(agreement);
} else {
int index = Integer.parseInt(command);
agreement.remove(index);
initialize();
}
}
public class ColonyTradeItemPanel extends JPanel implements ActionListener {
private JComboBox colonyBox;
private JButton addButton;
private Player player;
private NegotiationDialog negotiationDialog;
/**
* Creates a new <code>ColonyTradeItemPanel</code> instance.
*
* @param parent a <code>NegotiationDialog</code> value
* @param source a <code>Player</code> value
*/
public ColonyTradeItemPanel(NegotiationDialog parent, Player source) {
this.player = source;
this.negotiationDialog = parent;
addButton = new JButton(Messages.message("negotiationDialog.add"));
addButton.addActionListener(this);
addButton.setActionCommand("add");
colonyBox = new JComboBox();
updateColonyBox();
setLayout(new HIGLayout(new int[] {0}, new int[] {0, 0, 0}));
setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
add(new JLabel(Messages.message("tradeItem.colony")),
higConst.rc(1, 1));
add(colonyBox, higConst.rc(2, 1));
add(addButton, higConst.rc(3, 1));
}
private void updateColonyBox() {
if (!player.isEuropean()) {
return;
}
// Remove all action listeners, so the update has no effect (except
// updating the list).
ActionListener[] listeners = colonyBox.getActionListeners();
for (ActionListener al : listeners) {
colonyBox.removeActionListener(al);
}
colonyBox.removeAllItems();
List<Colony> colonies = player.getColonies();
Collections.sort(colonies, freeColClient.getClientOptions().getColonyComparator());
Iterator<Colony> colonyIterator = colonies.iterator();
while (colonyIterator.hasNext()) {
colonyBox.addItem(colonyIterator.next());
}
for(ActionListener al : listeners) {
colonyBox.addActionListener(al);
}
}
/**
* Analyzes an event and calls the right external methods to take care of
* the user's request.
*
* @param event The incoming action event
*/
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("add")) {
negotiationDialog.addColonyTradeItem(player, (Colony) colonyBox.getSelectedItem());
updateSummary();
}
}
}
public class GoodsTradeItemPanel extends JPanel implements ActionListener {
private JComboBox goodsBox;
private JButton addButton;
private Player player;
private NegotiationDialog negotiationDialog;
/**
* Creates a new <code>GoodsTradeItemPanel</code> instance.
*
* @param parent a <code>NegotiationDialog</code> value
* @param source a <code>Player</code> value
* @param allGoods a <code>List</code> of <code>Goods</code> values
*/
public GoodsTradeItemPanel(NegotiationDialog parent, Player source, List<Goods> allGoods) {
this.player = source;
this.negotiationDialog = parent;
addButton = new JButton(Messages.message("negotiationDialog.add"));
addButton.addActionListener(this);
addButton.setActionCommand("add");
goodsBox = new JComboBox();
JLabel label = new JLabel(Messages.message("tradeItem.goods"));
if (allGoods == null) {
label.setEnabled(false);
addButton.setEnabled(false);
goodsBox.setEnabled(false);
} else {
updateGoodsBox(allGoods);
}
setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
setLayout(new HIGLayout(new int[] {0}, new int[] {0, 0, 0}));
add(label, higConst.rc(1, 1));
add(goodsBox, higConst.rc(2, 1));
add(addButton, higConst.rc(3, 1));
setSize(getPreferredSize());
}
private void updateGoodsBox(List<Goods> allGoods) {
// Remove all action listeners, so the update has no effect (except
// updating the list).
ActionListener[] listeners = goodsBox.getActionListeners();
for (ActionListener al : listeners) {
goodsBox.removeActionListener(al);
}
goodsBox.removeAllItems();
Iterator<Goods> goodsIterator = allGoods.iterator();
while (goodsIterator.hasNext()) {
goodsBox.addItem(goodsIterator.next());
}
for(ActionListener al : listeners) {
goodsBox.addActionListener(al);
}
}
/**
* Analyzes an event and calls the right external methods to take care of
* the user's request.
*
* @param event The incoming action event
*/
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("add")) {
negotiationDialog.addGoodsTradeItem(player, (Goods) goodsBox.getSelectedItem());
updateSummary();
}
}
}
public class StanceTradeItemPanel extends JPanel implements ActionListener {
class StanceItem {
private int value;
StanceItem(int value) {
this.value = value;
}
public String toString() {
return Player.getStanceAsString(value);
}
int getValue() {
return value;
}
public boolean equals(Object other) {
if (other == null || !(other instanceof StanceItem)) {
return false;
}
return value == ((StanceItem) other).value;
}
}
private JComboBox stanceBox;
private JButton addButton;
private NegotiationDialog negotiationDialog;
/**
* Creates a new <code>StanceTradeItemPanel</code> instance.
*
* @param parent a <code>NegotiationDialog</code> value
* @param source a <code>Player</code> value
*/
public StanceTradeItemPanel(NegotiationDialog parent, Player source, Player target) {
this.negotiationDialog = parent;
addButton = new JButton(Messages.message("negotiationDialog.add"));
addButton.addActionListener(this);
addButton.setActionCommand("add");
stanceBox = new JComboBox();
int stance = source.getStance(target);
if (stance != Player.WAR) stanceBox.addItem(new StanceItem(Player.WAR));
if (stance == Player.WAR) stanceBox.addItem(new StanceItem(Player.CEASE_FIRE));
if (stance != Player.PEACE) stanceBox.addItem(new StanceItem(Player.PEACE));
if (stance != Player.ALLIANCE) stanceBox.addItem(new StanceItem(Player.ALLIANCE));
if (parent.hasPeaceOffer()) {
stanceBox.setSelectedItem(new StanceItem(parent.getStance()));
}
setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
setLayout(new HIGLayout(new int[] {0}, new int[] {0, 0, 0}));
add(new JLabel(Messages.message("tradeItem.stance")),
higConst.rc(1, 1));
add(stanceBox, higConst.rc(2, 1));
add(addButton, higConst.rc(3, 1));
}
/**
* Analyzes an event and calls the right external methods to take care of
* the user's request.
*
* @param event The incoming action event
*/
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("add")) {
StanceItem stance = (StanceItem) stanceBox.getSelectedItem();
negotiationDialog.setStance(stance.getValue());
updateSummary();
}
}
}
public class GoldTradeItemPanel extends JPanel implements ActionListener {
private JSpinner spinner;
private JButton addButton;
private Player player;
private NegotiationDialog negotiationDialog;
/**
* Creates a new <code>GoldTradeItemPanel</code> instance.
*
* @param parent a <code>NegotiationDialog</code> value
* @param source a <code>Player</code> value
*/
public GoldTradeItemPanel(NegotiationDialog parent, Player source, int gold) {
this.player = source;
this.negotiationDialog = parent;
addButton = new JButton(Messages.message("negotiationDialog.add"));
addButton.addActionListener(this);
addButton.setActionCommand("add");
spinner = new JSpinner(new SpinnerNumberModel(0, 0, gold, 1));
setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
setLayout(new HIGLayout(new int[] {0}, new int[] {0, 0, 0}));
add(new JLabel(Messages.message("tradeItem.gold")),
higConst.rc(1, 1));
add(spinner, higConst.rc(2, 1));
add(addButton, higConst.rc(3, 1));
}
/**
* Analyzes an event and calls the right external methods to take care of
* the user's request.
*
* @param event The incoming action event
*/
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("add")) {
int amount = ((Integer) spinner.getValue()).intValue();
negotiationDialog.addGoldTradeItem(player, amount);
updateSummary();
}
}
}
}
| false | true | public void initialize() {
int foreignGold = 0;
Element report = getCanvas().getClient().getInGameController().getForeignAffairsReport();
int number = report.getChildNodes().getLength();
for (int i = 0; i < number; i++) {
Element enemyElement = (Element) report.getChildNodes().item(i);
int nationID = Integer.parseInt(enemyElement.getAttribute("nation"));
if (nationID == otherPlayer.getNation()) {
foreignGold = Integer.parseInt(enemyElement.getAttribute("gold"));
break;
}
}
sendButton = new JButton(Messages.message("negotiationDialog.send"));
sendButton.addActionListener(this);
sendButton.setActionCommand(SEND);
FreeColPanel.enterPressesWhenFocused(sendButton);
acceptButton = new JButton(Messages.message("negotiationDialog.accept"));
acceptButton.addActionListener(this);
acceptButton.setActionCommand(ACCEPT);
FreeColPanel.enterPressesWhenFocused(acceptButton);
acceptButton.setEnabled(canAccept);
cancelButton = new JButton(Messages.message("negotiationDialog.cancel"));
cancelButton.addActionListener(this);
cancelButton.setActionCommand(CANCEL);
setCancelComponent(cancelButton);
FreeColPanel.enterPressesWhenFocused(cancelButton);
updateSummary();
stance = new StanceTradeItemPanel(this, player, otherPlayer);
goldDemand = new GoldTradeItemPanel(this, otherPlayer, foreignGold);
goldOffer = new GoldTradeItemPanel(this, player, player.getGold());
goodsDemand = new GoodsTradeItemPanel(this, otherPlayer, settlement.getGoodsContainer().getGoods());
goodsOffer = new GoodsTradeItemPanel(this, player, unit.getGoodsContainer().getGoods());
colonyDemand = new ColonyTradeItemPanel(this, otherPlayer);
colonyOffer = new ColonyTradeItemPanel(this, player);
/** TODO: UnitTrade
unitDemand = new UnitTradeItemPanel(this, otherPlayer);
unitOffer = new UnitTradeItemPanel(this, player);
*/
int numberOfTradeItems = 4;
int extraRows = 2; // headline and buttons
int[] widths = {200, 10, 300, 10, 200};
int[] heights = new int[2 * (numberOfTradeItems + extraRows) - 1];
for (int index = 1; index < heights.length; index += 2) {
heights[index] = 10;
}
setLayout(new HIGLayout(widths, heights));
int demandColumn = 1;
int summaryColumn = 3;
int offerColumn = 5;
int row = 1;
add(new JLabel(Messages.message("negotiationDialog.demand")),
higConst.rc(row, demandColumn));
add(new JLabel(Messages.message("negotiationDialog.offer")),
higConst.rc(row, offerColumn));
row += 2;
add(stance, higConst.rc(row, offerColumn));
row += 2;
add(goldDemand, higConst.rc(row, demandColumn));
add(goldOffer, higConst.rc(row, offerColumn));
add(summary, higConst.rcwh(row, summaryColumn, 1, 5));
row += 2;
if (unit.isCarrier()) {
add(goodsDemand, higConst.rc(row, demandColumn));
add(goodsOffer, higConst.rc(row, offerColumn));
} else {
add(colonyDemand, higConst.rc(row, demandColumn));
add(colonyOffer, higConst.rc(row, offerColumn));
}
row += 2;
/** TODO: UnitTrade
add(unitDemand, higConst.rc(row, demandColumn));
add(unitOffer, higConst.rc(row, offerColumn));
*/
row += 2;
add(sendButton, higConst.rc(row, demandColumn, ""));
add(acceptButton, higConst.rc(row, summaryColumn, ""));
add(cancelButton, higConst.rc(row, offerColumn, ""));
}
| public void initialize() {
int foreignGold = 0;
Element report = getCanvas().getClient().getInGameController().getForeignAffairsReport();
int number = report.getChildNodes().getLength();
for (int i = 0; i < number; i++) {
Element enemyElement = (Element) report.getChildNodes().item(i);
int nationID = Integer.parseInt(enemyElement.getAttribute("nation"));
if (nationID == otherPlayer.getNation()) {
foreignGold = Integer.parseInt(enemyElement.getAttribute("gold"));
break;
}
}
sendButton = new JButton(Messages.message("negotiationDialog.send"));
sendButton.addActionListener(this);
sendButton.setActionCommand(SEND);
FreeColPanel.enterPressesWhenFocused(sendButton);
acceptButton = new JButton(Messages.message("negotiationDialog.accept"));
acceptButton.addActionListener(this);
acceptButton.setActionCommand(ACCEPT);
FreeColPanel.enterPressesWhenFocused(acceptButton);
acceptButton.setEnabled(canAccept);
cancelButton = new JButton(Messages.message("negotiationDialog.cancel"));
cancelButton.addActionListener(this);
cancelButton.setActionCommand(CANCEL);
setCancelComponent(cancelButton);
FreeColPanel.enterPressesWhenFocused(cancelButton);
updateSummary();
stance = new StanceTradeItemPanel(this, player, otherPlayer);
goldDemand = new GoldTradeItemPanel(this, otherPlayer, foreignGold);
goldOffer = new GoldTradeItemPanel(this, player, player.getGold());
colonyDemand = new ColonyTradeItemPanel(this, otherPlayer);
colonyOffer = new ColonyTradeItemPanel(this, player);
/** TODO: UnitTrade
unitDemand = new UnitTradeItemPanel(this, otherPlayer);
unitOffer = new UnitTradeItemPanel(this, player);
*/
int numberOfTradeItems = 4;
int extraRows = 2; // headline and buttons
int[] widths = {200, 10, 300, 10, 200};
int[] heights = new int[2 * (numberOfTradeItems + extraRows) - 1];
for (int index = 1; index < heights.length; index += 2) {
heights[index] = 10;
}
setLayout(new HIGLayout(widths, heights));
int demandColumn = 1;
int summaryColumn = 3;
int offerColumn = 5;
int row = 1;
add(new JLabel(Messages.message("negotiationDialog.demand")),
higConst.rc(row, demandColumn));
add(new JLabel(Messages.message("negotiationDialog.offer")),
higConst.rc(row, offerColumn));
row += 2;
add(stance, higConst.rc(row, offerColumn));
row += 2;
add(goldDemand, higConst.rc(row, demandColumn));
add(goldOffer, higConst.rc(row, offerColumn));
add(summary, higConst.rcwh(row, summaryColumn, 1, 5));
row += 2;
if (unit.isCarrier()) {
goodsDemand = new GoodsTradeItemPanel(this, otherPlayer, settlement.getGoodsContainer().getGoods());
add(goodsDemand, higConst.rc(row, demandColumn));
goodsOffer = new GoodsTradeItemPanel(this, player, unit.getGoodsContainer().getGoods());
add(goodsOffer, higConst.rc(row, offerColumn));
} else {
add(colonyDemand, higConst.rc(row, demandColumn));
add(colonyOffer, higConst.rc(row, offerColumn));
}
row += 2;
/** TODO: UnitTrade
add(unitDemand, higConst.rc(row, demandColumn));
add(unitOffer, higConst.rc(row, offerColumn));
*/
row += 2;
add(sendButton, higConst.rc(row, demandColumn, ""));
add(acceptButton, higConst.rc(row, summaryColumn, ""));
add(cancelButton, higConst.rc(row, offerColumn, ""));
}
|
diff --git a/src/org/xbmc/jsonrpc/client/ControlClient.java b/src/org/xbmc/jsonrpc/client/ControlClient.java
index 77de163..0844675 100644
--- a/src/org/xbmc/jsonrpc/client/ControlClient.java
+++ b/src/org/xbmc/jsonrpc/client/ControlClient.java
@@ -1,490 +1,490 @@
/*
* Copyright (C) 2005-2009 Team XBMC
* http://xbmc.org
*
* 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, 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 XBMC Remote; see the file license. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
package org.xbmc.jsonrpc.client;
import org.codehaus.jackson.JsonNode;
import org.xbmc.api.business.INotifiableManager;
import org.xbmc.api.data.IControlClient;
import org.xbmc.api.info.PlayStatus;
import org.xbmc.api.object.Host;
import org.xbmc.api.type.SeekType;
import org.xbmc.jsonrpc.Connection;
/**
* The ControlClient class takes care of everything related to controlling
* XBMC. These are essentially play controls, navigation controls other actions
* the user may wants to execute. It equally reads the information instead of
* setting it.
*
* @author Team XBMC
*/
public class ControlClient extends Client implements IControlClient {
/**
* Class constructor needs reference to HTTP client connection
* @param connection
*/
public ControlClient(Connection connection) {
super(connection);
}
/**
* Updates host info on the connection.
* @param host
*/
public void setHost(Host host) {
mConnection.setHost(host);
}
/**
* Adds a file or folder (<code>fileOrFolder</code> is either a file or a folder) to the current playlist.
* @param manager Manager reference
* @param fileOrFolder
* @return true on success, false otherwise.
*/
public boolean addToPlaylist(INotifiableManager manager, String fileOrFolder, int playlistId) {
String type = "file";
if(fileOrFolder.endsWith("/") || fileOrFolder.endsWith("\\"))
type = "directory";
return mConnection.getString(manager, "Playlist.Add", obj().p("playlistid", playlistId).p("item", obj().p(type, fileOrFolder))).equals("OK");
}
public boolean play(INotifiableManager manager, int playlistId){
return mConnection.getString(manager, "Player.Open", obj().p("item", obj().p("playlistid", playlistId))).equals("OK");
}
/**
* Starts playing the media file <code>filename</code> .
* @param manager Manager reference
* @param filename File to play
* @return true on success, false otherwise.
*/
public boolean playFile(INotifiableManager manager, String filename, int playlistId) {
if(clearPlaylist(manager, playlistId))
if(addToPlaylist(manager, filename, playlistId))
return play(manager, playlistId);
else
return false;
else
return false;
}
/**
* Starts playing/showing the next media/image in the current playlist or,
* if currently showing a slideshow, the slideshow playlist.
* @param manager Manager reference
* @return true on success, false otherwise.
*/
public boolean playNext(INotifiableManager manager) {
return mConnection.getString(manager, "Player.GoNext", obj().p("playlistid", getPlaylistId(manager))).equals("OK");
}
/**
* Starts playing/showing the previous media/image in the current playlist
* or, if currently showing a slidshow, the slideshow playlist.
* @param manager Manager reference
* @return true on success, false otherwise.
*/
public boolean playPrevious(INotifiableManager manager) {
return mConnection.getString(manager, "Player.GoPrevious", obj().p("playlistid", getPlaylistId(manager))).equals("OK");
}
/**
* Pauses the currently playing media.
* @param manager Manager reference
* @return true on success, false otherwise.
*/
public boolean pause(INotifiableManager manager) {
mConnection.getInt(manager, "Player.PlayPause", obj().p("playerid", getActivePlayerId(manager)), "speed");
return true;
}
/**
* Stops the currently playing media.
* @param manager Manager reference
* @return true on success, false otherwise.
*/
public boolean stop(INotifiableManager manager) {
return mConnection.getString(manager, "Player.Stop", obj().p("playerid", getActivePlayerId(manager))).equals("OK");
}
/**
* Start playing the media file at the given URL
* @param manager Manager reference
* @param url An URL pointing to a supported media file
* @return true on success, false otherwise.
*/
public boolean playUrl(INotifiableManager manager, String url) {
return playFile(manager, url, 1);
}
/**
* Show the picture file <code>filename</code> .
* @param manager Manager reference
* @param filename File to show
* @return true on success, false otherwise.
*/
public boolean showPicture(INotifiableManager manager, String filename) {
return playNext(manager);
}
/**
* Send the string <code>text</code> via keys on the virtual keyboard.
* @param manager Manager reference
* @param text The text string to send.
* @return true on success, false otherwise.
*/
public boolean sendText(INotifiableManager manager, String text) {
/*final int codeOffset = 0xf100;
for (char c : text.toCharArray()) {
int code = (int)c+codeOffset;
if (! mConnection.getBoolean(manager, "SendKey", Integer.toString(code))) {
return false;
}
}*/
return false;
}
/**
* Sets the volume as a percentage of the maximum possible.
* @param manager Manager reference
* @param volume New volume (0-100)
* @return true on success, false otherwise.
*/
public boolean setVolume(INotifiableManager manager, int volume) {
return mConnection.getString(manager, "Application.SetVolume", obj().p("volume", volume)).equals("OK");
}
/**
* Seeks to a position. If type is
* <ul>
* <li><code>absolute</code> - Sets the playing position of the currently
* playing media as a percentage of the media�s length.</li>
* <li><code>relative</code> - Adds/Subtracts the current percentage on to
* the current position in the song</li>
* </ul>
*
* @param manager Manager reference
* @param type Seek type, relative or absolute
* @param progress Progress
* @return true on success, false otherwise.
*/
public boolean seek(INotifiableManager manager, SeekType type, int progress) {
if (type.compareTo(SeekType.absolute) == 0)
return mConnection.getJson(manager, "Player.Seek", obj().p("playerid", getActivePlayerId(manager)).p("value", progress)).get("percentage")!=null;
else
return false;//mConnection.getBoolean(manager, "SeekPercentageRelative", String.valueOf(progress));
}
/**
* Toggles the sound on/off.
* @param manager Manager reference
* @return true on success, false otherwise.
*/
public boolean mute(INotifiableManager manager) {
return mConnection.getString(manager, "Application.SetMute", obj().p("volume", 1)).equals("OK");
}
/**
* Retrieves the current playing position of the currently playing media as
* a percentage of the media's length.
* @param manager Manager reference
* @return Percentage (0-100)
*/
public int getPercentage(INotifiableManager manager) {
return mConnection.getInt(manager, "Player.GetProperties", obj().p("playerid", getActivePlayerId(manager)).p(PARAM_PROPERTIES, arr().add("percentage")), "percentage");
}
/**
* Retrieves the current volume setting as a percentage of the maximum
* possible value.
* @param manager Manager reference
* @return Volume (0-100)
*/
public int getVolume(INotifiableManager manager) {
return mConnection.getInt(manager, "Application.GetProperties", obj().p("playerid", getActivePlayerId(manager)).p(PARAM_PROPERTIES, arr().add("volume")), "volume");
}
/**
* Navigates... UP!
* @param manager Manager reference
* @return true on success, false otherwise.
*/
public boolean navUp(INotifiableManager manager) {
return mConnection.getString(manager, "Input.Up", null).equals("OK");
}
/**
* Navigates... DOWN!
* @param manager Manager reference
* @return true on success, false otherwise.
*/
public boolean navDown(INotifiableManager manager) {
return mConnection.getString(manager, "Input.Down", null).equals("OK");
}
/**
* Navigates... LEFT!
* @param manager Manager reference
* @return true on success, false otherwise.
*/
public boolean navLeft(INotifiableManager manager) {
return mConnection.getString(manager, "Input.Left", null).equals("OK");
}
/**
* Navigates... RIGHT!
* @param manager Manager reference
* @return true on success, false otherwise.
*/
public boolean navRight(INotifiableManager manager) {
return mConnection.getString(manager, "Input.Right", null).equals("OK");
}
/**
* Selects current item.
* @param manager Manager reference
* @return true on success, false otherwise.
*/
public boolean navSelect(INotifiableManager manager) {
return mConnection.getString(manager, "Input.Select", null).equals("OK");
}
/**
* Takes either "video" or "music" as a parameter to begin updating the
* corresponding database.
*
* TODO For "video" you can additionally specify a specific path to be scanned.
*
* @param manager Manager reference
* @param mediaType Either <code>video</code> or <code>music</code>.
* @return True on success, false otherwise.
*/
public boolean updateLibrary(INotifiableManager manager, String mediaType) {
if(mediaType == "video")
return mConnection.getString(manager, "VideoLibrary.Scan", null).equals("OK");
else if(mediaType == "music")
return mConnection.getString(manager, "AudioLibrary.Scan", null).equals("OK");
else
return false;
}
/**
* Broadcast a message. Used to test broadcasting feature.
* @param manager Manager reference
* @param message
* @return True on success, false otherwise.
*/
public boolean broadcast(INotifiableManager manager, String message) {
//TODO
return false;//mConnection.getBoolean(manager, "Broadcast", message);
}
/**
* Returns the current broadcast port number, or 0 if deactivated.
* @param manager Manager reference
* @return Current broadcast port number.
*/
public int getBroadcast(INotifiableManager manager) {
//TODO
/*final String ret[] = mConnection.getString(manager, "GetBroadcast").split(";");
try {
final int port = Integer.parseInt(ret[1]);
return port > 1 && !ret[0].equals("0") ? port : 0;
} catch (NumberFormatException e) {
return 0;
}*/
return 0;
}
/**
* Sets the brodcast level and port. Level currently only takes three values:
* <ul>
* <li><code>0</code> - No broadcasts</li>
* <li><code>1</code> - Media playback and startup & shutdown events
* <li><code>2</code> - "OnAction" events (e.g. buttons) as well as level 1 events.
* </ul>
*
* @param manager Manager reference
* @param port Broadcast port
* @param level Broadcast level
* @return True on success, false otherwise.
*/
public boolean setBroadcast(INotifiableManager manager, int port, int level) {
//TODO
return false;//mConnection.getBoolean(manager, "SetBroadcast", level + ";" + port);
}
/**
* Returns current play state
* @param manager Manager reference
* @return
*/
public int getPlayState(INotifiableManager manager) {
return mConnection.getInt(manager, "Application.GetProperties", obj().p("playerid", getActivePlayerId(manager)).p(PARAM_PROPERTIES, arr().add("speed")), "speed");
}
/**
* Returns the current playlist identifier
* @param manager Manager reference
*/
public int getPlaylistId(INotifiableManager manager) {
return mConnection.getInt(manager, "Player.GetProperties", obj().p("playerid", getActivePlayerId(manager)).p(PARAM_PROPERTIES, arr().add("playlistid")), "playlistid");
}
/**
* Sets the current playlist identifier
* @param manager Manager reference
* @param id Playlist identifier
* @return True on success, false otherwise.
*/
public boolean setPlaylistId(INotifiableManager manager, int id) {
return mConnection.getString(manager, "Player.Open", obj().p("item", obj().p("playlistid", id))).equals("OK");
}
/**
* Sets the current playlist position
* @param manager Manager reference0
* @param position New playlist position
* @return True on success, false otherwise.
*/
public boolean setPlaylistPos(INotifiableManager manager, int playlistId, int position) {
int playerid = getActivePlayerId(manager);
int currentplaylistid = getPlaylistId(manager);
if(playerid == -1 || currentplaylistid != playlistId)
return mConnection.getString(manager, "Player.Open", obj().p("item", obj().p("playlistid", playlistId).p("position", position))).equals("OK");
else
return mConnection.getString(manager, "Player.GoTo", obj().p("playerid", getActivePlayerId(manager)).p("position", position)).equals("OK");
}
/**
* Clears a playlist.
* @param manager Manager reference
* @param int Playlist to clear (0 = music, 1 = video)
* @return True on success, false otherwise.
*/
public boolean clearPlaylist(INotifiableManager manager, int playlistId) {
return mConnection.getString(manager, "Playlist.Clear", obj().p("playlistid", playlistId)).equals("OK");
}
/**
* Sets current playlist
* @param manager Manager reference
* @param playlistId Playlist ID ("0" = music, "1" = video)
* @return True on success, false otherwise.
*/
public boolean setCurrentPlaylist(INotifiableManager manager, int playlistId) {
return mConnection.getString(manager, "Player.Open", obj().p("item", obj().p("playlistid", playlistId))).equals("OK");
}
/**
* Sets the correct response format to default values
* @param manager Manager reference
* @return True on success, false otherwise.
*/
/**
* Sets the gui setting of XBMC to value
* @param manager
* @param setting see {@link org.xbmc.api.info.GuiSettings} for the available settings
* @param value the value to set
* @return {@code true} if the value was set successfully
*/
public boolean setGuiSetting(INotifiableManager manager, final int setting, final String value) {
return false;//mConnection.getBoolean(manager, "SetGUISetting", GuiSettings.getType(setting) + ";" + GuiSettings.getName(setting) + ";" + value);
}
/**
* Returns state and type of the media currently playing.
* @return
*/
public ICurrentlyPlaying getCurrentlyPlaying(INotifiableManager manager) {
final IControlClient.ICurrentlyPlaying nothingPlaying = new IControlClient.ICurrentlyPlaying() {
private static final long serialVersionUID = -1554068775915058884L;
public boolean isPlaying() { return false; }
public int getMediaType() { return 0; }
public int getPlaylistPosition() { return -1; }
public String getTitle() { return ""; }
public int getTime() { return 0; }
public int getPlayStatus() { return PlayStatus.STOPPED; }
public float getPercentage() { return 0; }
public String getFilename() { return ""; }
public int getDuration() { return 0; }
public String getArtist() { return ""; }
public String getAlbum() { return ""; }
public int getHeight() { return 0; }
public int getWidth() { return 0; }
};
final JsonNode active = mConnection.getJson(manager, "Player.GetActivePlayers", null);
if(active.size() == 0)
return nothingPlaying;
int playerid = getActivePlayerId(manager);
final JsonNode player_details = mConnection.getJson(manager, "Player.GetProperties", obj().p("playerid", playerid).p(PARAM_PROPERTIES, arr().add("percentage").add("position").add("speed").add("time").add("totaltime").add("type")));
if(player_details != null){
final JsonNode file_details = mConnection.getJson(manager, "Player.GetItem", obj().p("playerid", playerid).p(PARAM_PROPERTIES, arr().add("artist").add("album").add("duration").add("episode").add("genre").add("file").add("season").add("showtitle").add("tagline").add("title"))).get("item");
if(file_details.get("Filename") != null && file_details.get("Filename").getTextValue().contains("Nothing Playing")) {
return nothingPlaying;
}
if(getString(file_details, "type").equals("song")){
return MusicClient.getCurrentlyPlaying(player_details, file_details);
}
- else if(getString(file_details, "type").indexOf("video") != -1){
+ else if(getString(file_details, "type").indexOf("video") != -1 || getString(file_details, "type").indexOf("movie") != -1){
return VideoClient.getCurrentlyPlaying(player_details, file_details);
}
else if(getString(file_details, "type").equals("episode")){
return TvShowClient.getCurrentlyPlaying(player_details, file_details);
}
else
return nothingPlaying;
}
else
return nothingPlaying;
}
public static int parseTime(JsonNode node) {
int time=0;
time += node.get("hours").getIntValue() * 3600;
time += node.get("minutes").getIntValue() * 60;
time += node.get("seconds").getIntValue();
return time;
}
}
| true | true | public ICurrentlyPlaying getCurrentlyPlaying(INotifiableManager manager) {
final IControlClient.ICurrentlyPlaying nothingPlaying = new IControlClient.ICurrentlyPlaying() {
private static final long serialVersionUID = -1554068775915058884L;
public boolean isPlaying() { return false; }
public int getMediaType() { return 0; }
public int getPlaylistPosition() { return -1; }
public String getTitle() { return ""; }
public int getTime() { return 0; }
public int getPlayStatus() { return PlayStatus.STOPPED; }
public float getPercentage() { return 0; }
public String getFilename() { return ""; }
public int getDuration() { return 0; }
public String getArtist() { return ""; }
public String getAlbum() { return ""; }
public int getHeight() { return 0; }
public int getWidth() { return 0; }
};
final JsonNode active = mConnection.getJson(manager, "Player.GetActivePlayers", null);
if(active.size() == 0)
return nothingPlaying;
int playerid = getActivePlayerId(manager);
final JsonNode player_details = mConnection.getJson(manager, "Player.GetProperties", obj().p("playerid", playerid).p(PARAM_PROPERTIES, arr().add("percentage").add("position").add("speed").add("time").add("totaltime").add("type")));
if(player_details != null){
final JsonNode file_details = mConnection.getJson(manager, "Player.GetItem", obj().p("playerid", playerid).p(PARAM_PROPERTIES, arr().add("artist").add("album").add("duration").add("episode").add("genre").add("file").add("season").add("showtitle").add("tagline").add("title"))).get("item");
if(file_details.get("Filename") != null && file_details.get("Filename").getTextValue().contains("Nothing Playing")) {
return nothingPlaying;
}
if(getString(file_details, "type").equals("song")){
return MusicClient.getCurrentlyPlaying(player_details, file_details);
}
else if(getString(file_details, "type").indexOf("video") != -1){
return VideoClient.getCurrentlyPlaying(player_details, file_details);
}
else if(getString(file_details, "type").equals("episode")){
return TvShowClient.getCurrentlyPlaying(player_details, file_details);
}
else
return nothingPlaying;
}
else
return nothingPlaying;
}
| public ICurrentlyPlaying getCurrentlyPlaying(INotifiableManager manager) {
final IControlClient.ICurrentlyPlaying nothingPlaying = new IControlClient.ICurrentlyPlaying() {
private static final long serialVersionUID = -1554068775915058884L;
public boolean isPlaying() { return false; }
public int getMediaType() { return 0; }
public int getPlaylistPosition() { return -1; }
public String getTitle() { return ""; }
public int getTime() { return 0; }
public int getPlayStatus() { return PlayStatus.STOPPED; }
public float getPercentage() { return 0; }
public String getFilename() { return ""; }
public int getDuration() { return 0; }
public String getArtist() { return ""; }
public String getAlbum() { return ""; }
public int getHeight() { return 0; }
public int getWidth() { return 0; }
};
final JsonNode active = mConnection.getJson(manager, "Player.GetActivePlayers", null);
if(active.size() == 0)
return nothingPlaying;
int playerid = getActivePlayerId(manager);
final JsonNode player_details = mConnection.getJson(manager, "Player.GetProperties", obj().p("playerid", playerid).p(PARAM_PROPERTIES, arr().add("percentage").add("position").add("speed").add("time").add("totaltime").add("type")));
if(player_details != null){
final JsonNode file_details = mConnection.getJson(manager, "Player.GetItem", obj().p("playerid", playerid).p(PARAM_PROPERTIES, arr().add("artist").add("album").add("duration").add("episode").add("genre").add("file").add("season").add("showtitle").add("tagline").add("title"))).get("item");
if(file_details.get("Filename") != null && file_details.get("Filename").getTextValue().contains("Nothing Playing")) {
return nothingPlaying;
}
if(getString(file_details, "type").equals("song")){
return MusicClient.getCurrentlyPlaying(player_details, file_details);
}
else if(getString(file_details, "type").indexOf("video") != -1 || getString(file_details, "type").indexOf("movie") != -1){
return VideoClient.getCurrentlyPlaying(player_details, file_details);
}
else if(getString(file_details, "type").equals("episode")){
return TvShowClient.getCurrentlyPlaying(player_details, file_details);
}
else
return nothingPlaying;
}
else
return nothingPlaying;
}
|
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettingsController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettingsController.java
index 0f236cf7..a0dfcbab 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettingsController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettingsController.java
@@ -1,349 +1,351 @@
/*
* Copyright (C) 2012 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.systemui.statusbar.phone;
import static com.android.internal.util.cm.QSConstants.TILES_DEFAULT;
import static com.android.internal.util.cm.QSConstants.TILE_AIRPLANE;
import static com.android.internal.util.cm.QSConstants.TILE_AUTOROTATE;
import static com.android.internal.util.cm.QSConstants.TILE_BATTERY;
import static com.android.internal.util.cm.QSConstants.TILE_BLUETOOTH;
import static com.android.internal.util.cm.QSConstants.TILE_BRIGHTNESS;
import static com.android.internal.util.cm.QSConstants.TILE_DELIMITER;
import static com.android.internal.util.cm.QSConstants.TILE_GPS;
import static com.android.internal.util.cm.QSConstants.TILE_HOLOBAM;
import static com.android.internal.util.cm.QSConstants.TILE_LOCKSCREEN;
import static com.android.internal.util.cm.QSConstants.TILE_MOBILEDATA;
import static com.android.internal.util.cm.QSConstants.TILE_NETWORKMODE;
import static com.android.internal.util.cm.QSConstants.TILE_NFC;
import static com.android.internal.util.cm.QSConstants.TILE_RINGER;
import static com.android.internal.util.cm.QSConstants.TILE_SCREENTIMEOUT;
import static com.android.internal.util.cm.QSConstants.TILE_SETTINGS;
import static com.android.internal.util.cm.QSConstants.TILE_SLEEP;
import static com.android.internal.util.cm.QSConstants.TILE_SYNC;
import static com.android.internal.util.cm.QSConstants.TILE_TORCH;
import static com.android.internal.util.cm.QSConstants.TILE_USER;
import static com.android.internal.util.cm.QSConstants.TILE_VOLUME;
import static com.android.internal.util.cm.QSConstants.TILE_WIFI;
import static com.android.internal.util.cm.QSConstants.TILE_WIFIAP;
import static com.android.internal.util.cm.QSConstants.TILE_DESKTOPMODE;
import static com.android.internal.util.cm.QSConstants.TILE_HYBRID;
import static com.android.internal.util.cm.QSConstants.TILE_REBOOT;
import static com.android.internal.util.cm.QSUtils.deviceSupportsBluetooth;
import static com.android.internal.util.cm.QSUtils.deviceSupportsTelephony;
import static com.android.internal.util.cm.QSUtils.deviceSupportsUsbTether;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import com.android.systemui.statusbar.BaseStatusBar;
import com.android.systemui.quicksettings.AirplaneModeTile;
import com.android.systemui.quicksettings.AlarmTile;
import com.android.systemui.quicksettings.AutoRotateTile;
import com.android.systemui.quicksettings.BatteryTile;
import com.android.systemui.quicksettings.BluetoothTile;
import com.android.systemui.quicksettings.BrightnessTile;
import com.android.systemui.quicksettings.BugReportTile;
import com.android.systemui.quicksettings.GPSTile;
import com.android.systemui.quicksettings.HolobamTile;
import com.android.systemui.quicksettings.InputMethodTile;
import com.android.systemui.quicksettings.MobileNetworkTile;
import com.android.systemui.quicksettings.MobileNetworkTypeTile;
import com.android.systemui.quicksettings.NfcTile;
import com.android.systemui.quicksettings.PreferencesTile;
import com.android.systemui.quicksettings.QuickSettingsTile;
import com.android.systemui.quicksettings.RingerModeTile;
import com.android.systemui.quicksettings.ScreenTimeoutTile;
import com.android.systemui.quicksettings.SleepScreenTile;
import com.android.systemui.quicksettings.SyncTile;
import com.android.systemui.quicksettings.ToggleLockscreenTile;
import com.android.systemui.quicksettings.TorchTile;
import com.android.systemui.quicksettings.UsbTetherTile;
import com.android.systemui.quicksettings.UserTile;
import com.android.systemui.quicksettings.VolumeTile;
import com.android.systemui.quicksettings.WiFiDisplayTile;
import com.android.systemui.quicksettings.WiFiTile;
import com.android.systemui.quicksettings.WifiAPTile;
import com.android.systemui.quicksettings.DesktopModeTile;
import com.android.systemui.quicksettings.HybridTile;
import com.android.systemui.quicksettings.RebootTile;
import com.android.systemui.statusbar.powerwidget.PowerButton;
import java.util.ArrayList;
import java.util.HashMap;
public class QuickSettingsController {
private static String TAG = "QuickSettingsController";
// Stores the broadcast receivers and content observers
// quick tiles register for.
public HashMap<String, ArrayList<QuickSettingsTile>> mReceiverMap
= new HashMap<String, ArrayList<QuickSettingsTile>>();
public HashMap<Uri, ArrayList<QuickSettingsTile>> mObserverMap
= new HashMap<Uri, ArrayList<QuickSettingsTile>>();
private final Context mContext;
private ArrayList<QuickSettingsTile> mQuickSettingsTiles;
public PanelBar mBar;
private final QuickSettingsContainerView mContainerView;
private final Handler mHandler;
private BroadcastReceiver mReceiver;
private ContentObserver mObserver;
public BaseStatusBar mStatusBarService;
private InputMethodTile mIMETile;
public QuickSettingsController(Context context, QuickSettingsContainerView container, BaseStatusBar statusBarService) {
mContext = context;
mContainerView = container;
mHandler = new Handler();
mStatusBarService = statusBarService;
mQuickSettingsTiles = new ArrayList<QuickSettingsTile>();
}
void loadTiles() {
// Reset reference tiles
mIMETile = null;
// Filter items not compatible with device
boolean bluetoothSupported = deviceSupportsBluetooth();
boolean telephonySupported = deviceSupportsTelephony(mContext);
if (!bluetoothSupported) {
TILES_DEFAULT.remove(TILE_BLUETOOTH);
}
if (!telephonySupported) {
TILES_DEFAULT.remove(TILE_WIFIAP);
TILES_DEFAULT.remove(TILE_MOBILEDATA);
TILES_DEFAULT.remove(TILE_NETWORKMODE);
}
// Read the stored list of tiles
ContentResolver resolver = mContext.getContentResolver();
LayoutInflater inflater = LayoutInflater.from(mContext);
String tiles = Settings.System.getString(resolver, Settings.System.QUICK_SETTINGS);
if (tiles == null) {
Log.i(TAG, "Default tiles being loaded");
tiles = TextUtils.join(TILE_DELIMITER, TILES_DEFAULT);
}
Log.i(TAG, "Tiles list: " + tiles);
// Split out the tile names and add to the list
for (String tile : tiles.split("\\|")) {
QuickSettingsTile qs = null;
if (tile.equals(TILE_USER)) {
qs = new UserTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BATTERY)) {
qs = new BatteryTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SETTINGS)) {
qs = new PreferencesTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_WIFI)) {
qs = new WiFiTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_GPS)) {
qs = new GPSTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BLUETOOTH) && bluetoothSupported) {
qs = new BluetoothTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BRIGHTNESS)) {
qs = new BrightnessTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_RINGER)) {
qs = new RingerModeTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SYNC)) {
qs = new SyncTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_WIFIAP) && telephonySupported) {
qs = new WifiAPTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SCREENTIMEOUT)) {
qs = new ScreenTimeoutTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_MOBILEDATA) && telephonySupported) {
qs = new MobileNetworkTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_LOCKSCREEN)) {
qs = new ToggleLockscreenTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_AUTOROTATE)) {
qs = new AutoRotateTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_AIRPLANE)) {
qs = new AirplaneModeTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_TORCH)) {
qs = new TorchTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_SLEEP)) {
qs = new SleepScreenTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_NFC)) {
// User cannot add the NFC tile if the device does not support it
// No need to check again here
qs = new NfcTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_DESKTOPMODE)) {
qs = new DesktopModeTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_HYBRID)) {
qs = new HybridTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_VOLUME)) {
qs = new VolumeTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_REBOOT)) {
qs = new RebootTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_HOLOBAM)) {
qs = new HolobamTile(mContext, inflater, mContainerView, this, mHandler);
+ } else if (tile.equals(TILE_NETWORKMODE)) {
+ qs = new MobileNetworkTypeTile(mContext, inflater, mContainerView, this, mHandler);
}
if (qs != null) {
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
}
// Load the dynamic tiles
// These toggles must be the last ones added to the view, as they will show
// only when they are needed
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_ALARM, 1) == 1) {
QuickSettingsTile qs = new AlarmTile(mContext, inflater, mContainerView, this, mHandler);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_BUGREPORT, 1) == 1) {
QuickSettingsTile qs = new BugReportTile(mContext, inflater, mContainerView, this, mHandler);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_WIFI, 1) == 1) {
QuickSettingsTile qs = new WiFiDisplayTile(mContext, inflater, mContainerView, this);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
mIMETile = new InputMethodTile(mContext, inflater, mContainerView, this);
mIMETile.setupQuickSettingsTile();
mQuickSettingsTiles.add(mIMETile);
if (deviceSupportsUsbTether(mContext) && Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_USBTETHER, 1) == 1) {
QuickSettingsTile qs = new UsbTetherTile(mContext, inflater, mContainerView, this);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
}
public void setupQuickSettings() {
mQuickSettingsTiles.clear();
mContainerView.removeAllViews();
// Clear out old receiver
if (mReceiver != null) {
mContext.unregisterReceiver(mReceiver);
}
mReceiver = new QSBroadcastReceiver();
mReceiverMap.clear();
ContentResolver resolver = mContext.getContentResolver();
// Clear out old observer
if (mObserver != null) {
resolver.unregisterContentObserver(mObserver);
}
mObserver = new QuickSettingsObserver(mHandler);
mObserverMap.clear();
loadTiles();
setupBroadcastReceiver();
setupContentObserver();
}
void setupContentObserver() {
ContentResolver resolver = mContext.getContentResolver();
for (Uri uri : mObserverMap.keySet()) {
resolver.registerContentObserver(uri, false, mObserver);
}
}
private class QuickSettingsObserver extends ContentObserver {
public QuickSettingsObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange, Uri uri) {
ContentResolver resolver = mContext.getContentResolver();
for (QuickSettingsTile tile : mObserverMap.get(uri)) {
tile.onChangeUri(resolver, uri);
}
}
}
void setupBroadcastReceiver() {
IntentFilter filter = new IntentFilter();
for (String action : mReceiverMap.keySet()) {
filter.addAction(action);
}
mContext.registerReceiver(mReceiver, filter);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void registerInMap(Object item, QuickSettingsTile tile, HashMap map) {
if (map.keySet().contains(item)) {
ArrayList list = (ArrayList) map.get(item);
if (!list.contains(tile)) {
list.add(tile);
}
} else {
ArrayList<QuickSettingsTile> list = new ArrayList<QuickSettingsTile>();
list.add(tile);
map.put(item, list);
}
}
public void registerAction(Object action, QuickSettingsTile tile) {
registerInMap(action, tile, mReceiverMap);
}
public void registerObservedContent(Uri uri, QuickSettingsTile tile) {
registerInMap(uri, tile, mObserverMap);
}
private class QSBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null) {
for (QuickSettingsTile t : mReceiverMap.get(action)) {
t.onReceive(context, intent);
}
}
}
};
public void setBar(PanelBar bar) {
mBar = bar;
}
public void setService(BaseStatusBar phoneStatusBar) {
mStatusBarService = phoneStatusBar;
}
public void setImeWindowStatus(boolean visible) {
if (mIMETile != null) {
mIMETile.toggleVisibility(visible);
}
}
public void updateResources() {
mContainerView.updateResources();
for (QuickSettingsTile t : mQuickSettingsTiles) {
t.updateResources();
}
}
}
| true | true | void loadTiles() {
// Reset reference tiles
mIMETile = null;
// Filter items not compatible with device
boolean bluetoothSupported = deviceSupportsBluetooth();
boolean telephonySupported = deviceSupportsTelephony(mContext);
if (!bluetoothSupported) {
TILES_DEFAULT.remove(TILE_BLUETOOTH);
}
if (!telephonySupported) {
TILES_DEFAULT.remove(TILE_WIFIAP);
TILES_DEFAULT.remove(TILE_MOBILEDATA);
TILES_DEFAULT.remove(TILE_NETWORKMODE);
}
// Read the stored list of tiles
ContentResolver resolver = mContext.getContentResolver();
LayoutInflater inflater = LayoutInflater.from(mContext);
String tiles = Settings.System.getString(resolver, Settings.System.QUICK_SETTINGS);
if (tiles == null) {
Log.i(TAG, "Default tiles being loaded");
tiles = TextUtils.join(TILE_DELIMITER, TILES_DEFAULT);
}
Log.i(TAG, "Tiles list: " + tiles);
// Split out the tile names and add to the list
for (String tile : tiles.split("\\|")) {
QuickSettingsTile qs = null;
if (tile.equals(TILE_USER)) {
qs = new UserTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BATTERY)) {
qs = new BatteryTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SETTINGS)) {
qs = new PreferencesTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_WIFI)) {
qs = new WiFiTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_GPS)) {
qs = new GPSTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BLUETOOTH) && bluetoothSupported) {
qs = new BluetoothTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BRIGHTNESS)) {
qs = new BrightnessTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_RINGER)) {
qs = new RingerModeTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SYNC)) {
qs = new SyncTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_WIFIAP) && telephonySupported) {
qs = new WifiAPTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SCREENTIMEOUT)) {
qs = new ScreenTimeoutTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_MOBILEDATA) && telephonySupported) {
qs = new MobileNetworkTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_LOCKSCREEN)) {
qs = new ToggleLockscreenTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_AUTOROTATE)) {
qs = new AutoRotateTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_AIRPLANE)) {
qs = new AirplaneModeTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_TORCH)) {
qs = new TorchTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_SLEEP)) {
qs = new SleepScreenTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_NFC)) {
// User cannot add the NFC tile if the device does not support it
// No need to check again here
qs = new NfcTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_DESKTOPMODE)) {
qs = new DesktopModeTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_HYBRID)) {
qs = new HybridTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_VOLUME)) {
qs = new VolumeTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_REBOOT)) {
qs = new RebootTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_HOLOBAM)) {
qs = new HolobamTile(mContext, inflater, mContainerView, this, mHandler);
}
if (qs != null) {
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
}
// Load the dynamic tiles
// These toggles must be the last ones added to the view, as they will show
// only when they are needed
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_ALARM, 1) == 1) {
QuickSettingsTile qs = new AlarmTile(mContext, inflater, mContainerView, this, mHandler);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_BUGREPORT, 1) == 1) {
QuickSettingsTile qs = new BugReportTile(mContext, inflater, mContainerView, this, mHandler);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_WIFI, 1) == 1) {
QuickSettingsTile qs = new WiFiDisplayTile(mContext, inflater, mContainerView, this);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
mIMETile = new InputMethodTile(mContext, inflater, mContainerView, this);
mIMETile.setupQuickSettingsTile();
mQuickSettingsTiles.add(mIMETile);
if (deviceSupportsUsbTether(mContext) && Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_USBTETHER, 1) == 1) {
QuickSettingsTile qs = new UsbTetherTile(mContext, inflater, mContainerView, this);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
}
| void loadTiles() {
// Reset reference tiles
mIMETile = null;
// Filter items not compatible with device
boolean bluetoothSupported = deviceSupportsBluetooth();
boolean telephonySupported = deviceSupportsTelephony(mContext);
if (!bluetoothSupported) {
TILES_DEFAULT.remove(TILE_BLUETOOTH);
}
if (!telephonySupported) {
TILES_DEFAULT.remove(TILE_WIFIAP);
TILES_DEFAULT.remove(TILE_MOBILEDATA);
TILES_DEFAULT.remove(TILE_NETWORKMODE);
}
// Read the stored list of tiles
ContentResolver resolver = mContext.getContentResolver();
LayoutInflater inflater = LayoutInflater.from(mContext);
String tiles = Settings.System.getString(resolver, Settings.System.QUICK_SETTINGS);
if (tiles == null) {
Log.i(TAG, "Default tiles being loaded");
tiles = TextUtils.join(TILE_DELIMITER, TILES_DEFAULT);
}
Log.i(TAG, "Tiles list: " + tiles);
// Split out the tile names and add to the list
for (String tile : tiles.split("\\|")) {
QuickSettingsTile qs = null;
if (tile.equals(TILE_USER)) {
qs = new UserTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BATTERY)) {
qs = new BatteryTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SETTINGS)) {
qs = new PreferencesTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_WIFI)) {
qs = new WiFiTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_GPS)) {
qs = new GPSTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BLUETOOTH) && bluetoothSupported) {
qs = new BluetoothTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BRIGHTNESS)) {
qs = new BrightnessTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_RINGER)) {
qs = new RingerModeTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SYNC)) {
qs = new SyncTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_WIFIAP) && telephonySupported) {
qs = new WifiAPTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SCREENTIMEOUT)) {
qs = new ScreenTimeoutTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_MOBILEDATA) && telephonySupported) {
qs = new MobileNetworkTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_LOCKSCREEN)) {
qs = new ToggleLockscreenTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_AUTOROTATE)) {
qs = new AutoRotateTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_AIRPLANE)) {
qs = new AirplaneModeTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_TORCH)) {
qs = new TorchTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_SLEEP)) {
qs = new SleepScreenTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_NFC)) {
// User cannot add the NFC tile if the device does not support it
// No need to check again here
qs = new NfcTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_DESKTOPMODE)) {
qs = new DesktopModeTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_HYBRID)) {
qs = new HybridTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_VOLUME)) {
qs = new VolumeTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_REBOOT)) {
qs = new RebootTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_HOLOBAM)) {
qs = new HolobamTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_NETWORKMODE)) {
qs = new MobileNetworkTypeTile(mContext, inflater, mContainerView, this, mHandler);
}
if (qs != null) {
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
}
// Load the dynamic tiles
// These toggles must be the last ones added to the view, as they will show
// only when they are needed
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_ALARM, 1) == 1) {
QuickSettingsTile qs = new AlarmTile(mContext, inflater, mContainerView, this, mHandler);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_BUGREPORT, 1) == 1) {
QuickSettingsTile qs = new BugReportTile(mContext, inflater, mContainerView, this, mHandler);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_WIFI, 1) == 1) {
QuickSettingsTile qs = new WiFiDisplayTile(mContext, inflater, mContainerView, this);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
mIMETile = new InputMethodTile(mContext, inflater, mContainerView, this);
mIMETile.setupQuickSettingsTile();
mQuickSettingsTiles.add(mIMETile);
if (deviceSupportsUsbTether(mContext) && Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_USBTETHER, 1) == 1) {
QuickSettingsTile qs = new UsbTetherTile(mContext, inflater, mContainerView, this);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
}
|
diff --git a/plugins/org.eclipse.birt.report.data.oda.xml/src/org/eclipse/birt/report/data/oda/xml/util/SaxParserConsumer.java b/plugins/org.eclipse.birt.report.data.oda.xml/src/org/eclipse/birt/report/data/oda/xml/util/SaxParserConsumer.java
index a4626c1f2..231e3e536 100644
--- a/plugins/org.eclipse.birt.report.data.oda.xml/src/org/eclipse/birt/report/data/oda/xml/util/SaxParserConsumer.java
+++ b/plugins/org.eclipse.birt.report.data.oda.xml/src/org/eclipse/birt/report/data/oda/xml/util/SaxParserConsumer.java
@@ -1,38 +1,38 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.data.oda.xml.util;
import org.eclipse.birt.report.data.oda.xml.impl.ResultSet;
import org.eclipse.datatools.connectivity.oda.OdaException;
import org.eclipse.datatools.enablement.oda.xml.util.RelationInformation;
import org.eclipse.datatools.enablement.oda.xml.util.XMLDataInputStream;
/**
* This class is an implementation of ISaxParserConsumer. The instance of this class deligate the communication
* between ResultSet and SaxParser, and does the majority of result-set population job.
* @deprecated Please use DTP xml driver
*/
public class SaxParserConsumer extends org.eclipse.datatools.enablement.oda.xml.util.SaxParserConsumer
{
/**
*
* @param rs
* @param rinfo
* @param is
* @param tName
* @throws OdaException
*/
public SaxParserConsumer( ResultSet rs, RelationInformation rinfo, XMLDataInputStream is, String tName ) throws OdaException
{
- super( rs, rinfo, is, tName );
+ super( rinfo, is, tName );
}
}
| true | true | public SaxParserConsumer( ResultSet rs, RelationInformation rinfo, XMLDataInputStream is, String tName ) throws OdaException
{
super( rs, rinfo, is, tName );
}
| public SaxParserConsumer( ResultSet rs, RelationInformation rinfo, XMLDataInputStream is, String tName ) throws OdaException
{
super( rinfo, is, tName );
}
|
diff --git a/src/main/java/org/basex/gui/view/editor/EditorView.java b/src/main/java/org/basex/gui/view/editor/EditorView.java
index 299bdc7c9..37d2acb28 100644
--- a/src/main/java/org/basex/gui/view/editor/EditorView.java
+++ b/src/main/java/org/basex/gui/view/editor/EditorView.java
@@ -1,776 +1,776 @@
package org.basex.gui.view.editor;
import static org.basex.core.Text.*;
import static org.basex.gui.GUIConstants.*;
import static org.basex.util.Token.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.event.*;
import org.basex.core.*;
import org.basex.data.*;
import org.basex.gui.*;
import org.basex.gui.GUIConstants.Fill;
import org.basex.gui.GUIConstants.Msg;
import org.basex.gui.dialog.*;
import org.basex.gui.editor.Editor.Action;
import org.basex.gui.editor.*;
import org.basex.gui.layout.*;
import org.basex.gui.layout.BaseXFileChooser.Mode;
import org.basex.gui.layout.BaseXLayout.DropHandler;
import org.basex.gui.view.*;
import org.basex.io.*;
import org.basex.util.*;
import org.basex.util.list.*;
/**
* This view allows the input and evaluation of queries and documents.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public final class EditorView extends View {
/** Number of files in the history. */
private static final int HISTORY = 18;
/** Number of files in the compact history. */
private static final int HISTCOMP = 7;
/** XQuery error pattern. */
private static final Pattern XQERROR = Pattern.compile(
"(.*?), ([0-9]+)/([0-9]+)" + COL);
/** XML error pattern. */
private static final Pattern XMLERROR = Pattern.compile(
LINE_X.replaceAll("%", "(.*?)") + COL + ".*");
/** Error information pattern. */
private static final Pattern ERRORINFO = Pattern.compile(
"^.*\r?\n\\[.*?\\] |" + LINE_X.replaceAll("%", ".*?") + COLS + "|\r?\n.*",
Pattern.DOTALL);
/** Error tooltip pattern. */
private static final Pattern ERRORTT = Pattern.compile(
"^.*\r?\n" + STOPPED_AT + "|\r?\n" + STACK_TRACE_C + ".*", Pattern.DOTALL);
/** Search bar. */
final SearchBar search;
/** History Button. */
final BaseXButton hist;
/** Execute Button. */
final BaseXButton stop;
/** Info label. */
final BaseXLabel info;
/** Position label. */
final BaseXLabel pos;
/** Query area. */
final BaseXTabs tabs;
/** Execute button. */
final BaseXButton go;
/** Thread counter. */
int threadID;
/** File in which the most recent error occurred. */
IO errFile;
/** Last error message. */
private String errMsg;
/** Most recent error position; used for clicking on error message. */
private int errPos;
/** Header string. */
private final BaseXLabel label;
/** Filter button. */
private final BaseXButton filter;
/**
* Default constructor.
* @param man view manager
*/
public EditorView(final ViewNotifier man) {
super(EDITORVIEW, man);
border(5).layout(new BorderLayout());
label = new BaseXLabel(EDITOR, true, false);
label.setForeground(GUIConstants.GRAY);
final BaseXButton openB = BaseXButton.command(GUICommands.C_EDITOPEN, gui);
final BaseXButton saveB = new BaseXButton(gui, "save", H_SAVE);
hist = new BaseXButton(gui, "hist", H_RECENTLY_OPEN);
final BaseXButton srch = new BaseXButton(gui, "search",
BaseXLayout.addShortcut(H_REPLACE, BaseXKeys.FIND.toString()));
stop = new BaseXButton(gui, "stop", H_STOP_PROCESS);
stop.addKeyListener(this);
stop.setEnabled(false);
go = new BaseXButton(gui, "go",
- BaseXLayout.addShortcut(H_REPLACE, BaseXKeys.EXEC.toString()));
+ BaseXLayout.addShortcut(H_EXECUTE_QUERY, BaseXKeys.EXEC.toString()));
go.addKeyListener(this);
filter = BaseXButton.command(GUICommands.C_FILTER, gui);
filter.addKeyListener(this);
filter.setEnabled(false);
final BaseXBack buttons = new BaseXBack(Fill.NONE);
buttons.layout(new TableLayout(1, 8, 1, 0)).border(0, 0, 8, 0);
buttons.add(openB);
buttons.add(saveB);
buttons.add(hist);
buttons.add(srch);
buttons.add(Box.createHorizontalStrut(6));
buttons.add(stop);
buttons.add(go);
buttons.add(filter);
final BaseXBack b = new BaseXBack(Fill.NONE).layout(new BorderLayout());
b.add(buttons, BorderLayout.WEST);
b.add(label, BorderLayout.EAST);
add(b, BorderLayout.NORTH);
tabs = new BaseXTabs(gui);
tabs.setFocusable(Prop.MAC);
final SearchEditor se = new SearchEditor(gui, tabs, null).button(srch);
search = se.bar();
addCreateTab();
add(se, BorderLayout.CENTER);
// status and query pane
search.editor(addTab(), false);
info = new BaseXLabel().setText(OK, Msg.SUCCESS);
pos = new BaseXLabel(" ");
posCode.invokeLater();
final BaseXBack south = new BaseXBack(Fill.NONE).border(10, 0, 2, 0);
south.layout(new BorderLayout(4, 0));
south.add(info, BorderLayout.CENTER);
south.add(pos, BorderLayout.EAST);
add(south, BorderLayout.SOUTH);
refreshLayout();
// add listeners
saveB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pop = new JPopupMenu();
final StringBuilder mnem = new StringBuilder();
final JMenuItem sa = GUIMenu.newItem(GUICommands.C_EDITSAVE, gui, mnem);
final JMenuItem sas = GUIMenu.newItem(GUICommands.C_EDITSAVEAS, gui, mnem);
GUICommands.C_EDITSAVE.refresh(gui, sa);
GUICommands.C_EDITSAVEAS.refresh(gui, sas);
pop.add(sa);
pop.add(sas);
pop.show(saveB, 0, saveB.getHeight());
}
});
hist.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pm = new JPopupMenu();
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
// rewrite and open chosen file
final String s = ac.getActionCommand().replaceAll("(.*) \\[(.*)\\]", "$2/$1");
open(new IOFile(s), true);
}
};
// create popup menu with of recently opened files
final StringList opened = new StringList();
for(final EditorArea ea : editors()) opened.add(ea.file.path());
final StringList files = new StringList(HISTORY);
final StringList all = new StringList(gui.gprop.strings(GUIProp.EDITOR));
final int fl = Math.min(all.size(), e == null ? HISTORY : HISTCOMP);
for(int f = 0; f < fl; f++) files.add(all.get(f));
Font f = null;
for(final String en : files.sort(Prop.CASE)) {
// disable opened files
final JMenuItem it = new JMenuItem(en.replaceAll("(.*)[/\\\\](.*)", "$2 [$1]"));
if(opened.contains(en)) {
if(f == null) f = it.getFont().deriveFont(Font.BOLD);
it.setFont(f);
}
pm.add(it).addActionListener(al);
}
al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
hist.getActionListeners()[0].actionPerformed(null);
}
};
if(e != null && pm.getComponentCount() == HISTCOMP) {
pm.add(new JMenuItem("...")).addActionListener(al);
}
pm.show(hist, 0, hist.getHeight());
}
});
refreshHistory(null);
info.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
jumpToError();
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
stop.setEnabled(false);
go.setEnabled(false);
gui.stop();
}
});
go.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
getEditor().release(Action.EXECUTE);
}
});
tabs.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
final EditorArea ea = getEditor();
if(ea == null) return;
search.editor(ea, true);
gui.refreshControls();
posCode.invokeLater();
}
});
BaseXLayout.addDrop(this, new DropHandler() {
@Override
public void drop(final Object file) {
if(file instanceof File) open(new IOFile((File) file), true);
}
});
}
@Override
public void refreshInit() { }
@Override
public void refreshFocus() { }
@Override
public void refreshMark() {
final EditorArea edit = getEditor();
go.setEnabled(edit.script || !gui.gprop.is(GUIProp.EXECRT));
final Nodes mrk = gui.context.marked;
filter.setEnabled(!gui.gprop.is(GUIProp.FILTERRT) && mrk != null && mrk.size() != 0);
}
@Override
public void refreshContext(final boolean more, final boolean quick) { }
@Override
public void refreshLayout() {
label.border(-6, 0, 0, 2).setFont(GUIConstants.lfont);
for(final EditorArea edit : editors()) edit.setFont(GUIConstants.mfont);
search.refreshLayout();
final Font ef = GUIConstants.font.deriveFont(7f + (GUIConstants.fontSize >> 1));
info.setFont(ef);
pos.setFont(ef);
}
@Override
public void refreshUpdate() { }
@Override
public boolean visible() {
return gui.gprop.is(GUIProp.SHOWEDITOR);
}
@Override
public void visible(final boolean v) {
gui.gprop.set(GUIProp.SHOWEDITOR, v);
}
@Override
protected boolean db() {
return false;
}
/**
* Opens a new file.
*/
public void open() {
// open file chooser for XML creation
final BaseXFileChooser fc = new BaseXFileChooser(OPEN,
gui.gprop.get(GUIProp.WORKPATH), gui);
fc.filter(XQUERY_FILES, IO.XQSUFFIXES);
fc.filter(BXS_FILES, IO.BXSSUFFIX);
fc.textFilters();
final IOFile[] files = fc.multi().selectAll(Mode.FOPEN);
for(final IOFile f : files) open(f, true);
}
/**
* Reverts the contents of the currently opened editor.
*/
public void reopen() {
getEditor().reopen(true);
}
/**
* Saves the contents of the currently opened editor.
* @return {@code false} if operation was canceled
*/
public boolean save() {
final EditorArea edit = getEditor();
return edit.opened() ? save(edit.file) : saveAs();
}
/**
* Saves the contents of the currently opened editor under a new name.
* @return {@code false} if operation was canceled
*/
public boolean saveAs() {
// open file chooser for XML creation
final EditorArea edit = getEditor();
final String path = edit.opened() ? edit.file.path() :
gui.gprop.get(GUIProp.WORKPATH);
final BaseXFileChooser fc = new BaseXFileChooser(SAVE_AS, path, gui);
fc.filter(XQUERY_FILES, IO.XQSUFFIXES);
fc.filter(BXS_FILES, IO.BXSSUFFIX);
fc.textFilters();
fc.suffix(IO.XQSUFFIX);
final IOFile file = fc.select(Mode.FSAVE);
return file != null && save(file);
}
/**
* Creates a new file.
*/
public void newFile() {
addTab();
refreshControls(true);
}
/**
* Opens the specified query file.
* @param file query file
* @param parse parse contents
* @return opened editor, or {@code null} if file could not be opened
*/
public EditorArea open(final IO file, final boolean parse) {
if(!visible()) GUICommands.C_SHOWEDITOR.execute(gui);
EditorArea edit = find(file, true);
if(edit != null) {
// display open file
tabs.setSelectedComponent(edit);
edit.reopen(true);
} else {
try {
final byte[] text = file.read();
// get current editor
edit = getEditor();
// create new tab if current text is stored on disk or has been modified
if(edit.opened() || edit.modified) edit = addTab();
edit.initText(text);
edit.file(file);
if(parse) edit.release(Action.PARSE);
} catch(final IOException ex) {
refreshHistory(null);
BaseXDialog.error(gui, FILE_NOT_OPENED);
return null;
}
}
return edit;
}
/**
* Refreshes the list of recent query files and updates the query path.
* @param file new file
*/
void refreshHistory(final IO file) {
final StringList paths = new StringList();
String path = null;
if(file != null) {
path = file.path();
gui.gprop.set(GUIProp.WORKPATH, file.dirPath());
paths.add(path);
tabs.setToolTipTextAt(tabs.getSelectedIndex(), path);
}
final String[] old = gui.gprop.strings(GUIProp.EDITOR);
for(int p = 0; paths.size() < HISTORY && p < old.length; p++) {
final IO fl = IO.get(old[p]);
if(fl.exists() && !fl.eq(file)) paths.add(fl.path());
}
// store sorted history
gui.gprop.set(GUIProp.EDITOR, paths.toArray());
hist.setEnabled(!paths.isEmpty());
}
/**
* Closes an editor.
* @param edit editor to be closed. {@code null} closes the currently
* opened editor.
* @return {@code true} if editor was closed
*/
public boolean close(final EditorArea edit) {
final EditorArea ea = edit != null ? edit : getEditor();
if(!confirm(ea)) return false;
tabs.remove(ea);
final int t = tabs.getTabCount();
final int i = tabs.getSelectedIndex();
if(t == 1) {
// reopen single tab
addTab();
} else if(i + 1 == t) {
// if necessary, activate last editor tab
tabs.setSelectedIndex(i - 1);
}
return true;
}
/**
* Jumps to a specific line.
*/
public void gotoLine() {
final EditorArea edit = getEditor();
final int ll = edit.last.length;
final int cr = edit.getCaret();
int l = 1;
for(int e = 0; e < ll && e < cr; e += cl(edit.last, e)) {
if(edit.last[e] == '\n') ++l;
}
final DialogLine dl = new DialogLine(gui, l);
if(!dl.ok()) return;
final int el = dl.line();
int p = 0;
l = 1;
for(int e = 0; e < ll && l < el; e += cl(edit.last, e)) {
if(edit.last[e] != '\n') continue;
p = e + 1;
++l;
}
edit.setCaret(p);
posCode.invokeLater();
}
/**
* Starts a thread, which shows a waiting info after a short timeout.
*/
public void start() {
final int thread = threadID;
new Thread() {
@Override
public void run() {
Performance.sleep(200);
if(thread == threadID) {
info.setText(PLEASE_WAIT_D, Msg.SUCCESS).setToolTipText(null);
stop.setEnabled(true);
}
}
}.start();
}
/**
* Evaluates the info message resulting from a parsed or executed query.
* @param msg info message
* @param ok {@code true} if evaluation was successful
* @param refresh refresh buttons
*/
public void info(final String msg, final boolean ok, final boolean refresh) {
// do not refresh view when query is running
if(!refresh && stop.isEnabled()) return;
++threadID;
errPos = -1;
errFile = null;
errMsg = null;
getEditor().resetError();
if(refresh) {
stop.setEnabled(false);
refreshMark();
}
if(ok) {
info.setCursor(GUIConstants.CURSORARROW);
info.setText(msg, Msg.SUCCESS).setToolTipText(null);
} else {
error(msg, false);
info.setCursor(GUIConstants.CURSORHAND);
info.setText(ERRORINFO.matcher(msg).replaceAll(""), Msg.ERROR);
final String tt = ERRORTT.matcher(msg).replaceAll("").
replace("<", "<").replace(">", ">").
replaceAll("\r?\n", "<br/>").replaceAll("(<br/>.*?)<br/>.*", "$1");
info.setToolTipText("<html>" + tt + "</html>");
}
}
/**
* Jumps to the current error.
*/
void jumpToError() {
if(errMsg != null) error(true);
}
/**
* Handles info messages resulting from a query execution.
* @param jump jump to error position
* @param msg info message
*/
public void error(final String msg, final boolean jump) {
errMsg = msg;
for(final String s : msg.split("\r?\n")) {
if(XQERROR.matcher(s).matches()) {
errMsg = s.replace(STOPPED_AT, "");
break;
}
}
error(jump);
}
/**
* Handles info messages resulting from a query execution.
* @param jump jump to error position
*/
private void error(final boolean jump) {
Matcher m = XQERROR.matcher(errMsg);
int el, ec = 2;
if(m.matches()) {
errFile = new IOFile(m.group(1));
el = Token.toInt(m.group(2));
ec = Token.toInt(m.group(3));
} else {
m = XMLERROR.matcher(errMsg);
if(!m.matches()) return;
el = Token.toInt(m.group(1));
errFile = getEditor().file;
}
EditorArea edit = find(errFile, false);
if(jump) {
if(edit == null) edit = open(errFile, false);
if(edit != null) tabs.setSelectedComponent(edit);
}
if(edit == null) return;
// find approximate error position
final int ll = edit.last.length;
int ep = ll;
for(int p = 0, l = 1, c = 1; p < ll; ++c, p += cl(edit.last, p)) {
if(l > el || l == el && c == ec) {
ep = p;
break;
}
if(edit.last[p] == '\n') {
++l;
c = 0;
}
}
if(ep < ll && Character.isLetterOrDigit(cp(edit.last, ep))) {
while(ep > 0 && Character.isLetterOrDigit(cp(edit.last, ep - 1))) ep--;
}
edit.error(ep);
errPos = ep;
if(jump) {
edit.jumpError(errPos);
posCode.invokeLater();
}
}
/**
* Shows a quit dialog for all modified query files.
* @return {@code false} if confirmation was canceled
*/
public boolean confirm() {
for(final EditorArea edit : editors()) {
tabs.setSelectedComponent(edit);
if(!close(edit)) return false;
}
return true;
}
/**
* Checks if the current text can be saved or reverted.
* @return result of check
*/
public boolean modified() {
final EditorArea edit = getEditor();
return edit.modified || !edit.opened();
}
/**
* Returns the current editor.
* @return editor
*/
public EditorArea getEditor() {
final Component c = tabs.getSelectedComponent();
return c instanceof EditorArea ? (EditorArea) c : null;
}
/**
* Refreshes the query modification flag.
* @param force action
*/
void refreshControls(final boolean force) {
// update modification flag
final EditorArea edit = getEditor();
final boolean oe = edit.modified;
edit.modified = edit.hist != null && edit.hist.modified();
if(edit.modified == oe && !force) return;
// update tab title
String title = edit.file.name();
if(edit.modified) title += '*';
edit.label.setText(title);
// update components
gui.refreshControls();
posCode.invokeLater();
}
/** Code for setting cursor position. */
final GUICode posCode = new GUICode() {
@Override
public void eval(final Object arg) {
final int[] lc = getEditor().pos();
pos.setText(lc[0] + " : " + lc[1]);
}
};
/**
* Finds the editor that contains the specified file.
* @param file file to be found
* @param opened considers only opened files
* @return editor
*/
EditorArea find(final IO file, final boolean opened) {
for(final EditorArea edit : editors()) {
if(edit.file.eq(file) && (!opened || edit.opened())) return edit;
}
return null;
}
/**
* Saves the specified editor contents.
* @param file file to write
* @return {@code false} if confirmation was canceled
*/
private boolean save(final IO file) {
try {
final EditorArea edit = getEditor();
((IOFile) file).write(edit.getText());
edit.file(file);
return true;
} catch(final Exception ex) {
BaseXDialog.error(gui, FILE_NOT_SAVED);
return false;
}
}
/**
* Choose a unique tab file.
* @return io reference
*/
private IOFile newTabFile() {
// collect numbers of existing files
final BoolList bl = new BoolList();
for(final EditorArea edit : editors()) {
if(edit.opened()) continue;
final String n = edit.file.name().substring(FILE.length());
bl.set(n.isEmpty() ? 1 : Integer.parseInt(n), true);
}
// find first free file number
int c = 0;
while(++c < bl.size() && bl.get(c));
// create io reference
return new IOFile(gui.gprop.get(GUIProp.WORKPATH), FILE + (c == 1 ? "" : c));
}
/**
* Adds a new editor tab.
* @return editor reference
*/
EditorArea addTab() {
final EditorArea edit = new EditorArea(this, newTabFile());
edit.setFont(GUIConstants.mfont);
final BaseXBack tab = new BaseXBack(new BorderLayout(10, 0)).mode(Fill.NONE);
tab.add(edit.label, BorderLayout.CENTER);
final BaseXButton close = tabButton("e_close");
close.setRolloverIcon(BaseXLayout.icon("e_close2"));
close.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
close(edit);
}
});
tab.add(close, BorderLayout.EAST);
tabs.add(edit, tab, tabs.getComponentCount() - 2);
return edit;
}
/**
* Adds a tab for creating new tabs.
*/
private void addCreateTab() {
final BaseXButton add = tabButton("e_new");
add.setRolloverIcon(BaseXLayout.icon("e_new2"));
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
addTab();
refreshControls(true);
}
});
tabs.add(new BaseXBack(), add, 0);
tabs.setEnabledAt(0, false);
}
/**
* Adds a new tab button.
* @param icon button icon
* @return button
*/
private BaseXButton tabButton(final String icon) {
final BaseXButton b = new BaseXButton(gui, icon, null);
b.border(2, 2, 2, 2).setContentAreaFilled(false);
b.setFocusable(false);
return b;
}
/**
* Shows a quit dialog for the specified editor.
* @param edit editor to be saved
* @return {@code false} if confirmation was canceled
*/
private boolean confirm(final EditorArea edit) {
if(edit.modified && (edit.opened() || edit.getText().length != 0)) {
final Boolean ok = BaseXDialog.yesNoCancel(gui,
Util.info(CLOSE_FILE_X, edit.file.name()));
if(ok == null || ok && !save()) return false;
}
return true;
}
/**
* Returns all editors.
* @return editors
*/
EditorArea[] editors() {
final ArrayList<EditorArea> edits = new ArrayList<EditorArea>();
for(final Component c : tabs.getComponents()) {
if(c instanceof EditorArea) edits.add((EditorArea) c);
}
return edits.toArray(new EditorArea[edits.size()]);
}
}
| true | true | public EditorView(final ViewNotifier man) {
super(EDITORVIEW, man);
border(5).layout(new BorderLayout());
label = new BaseXLabel(EDITOR, true, false);
label.setForeground(GUIConstants.GRAY);
final BaseXButton openB = BaseXButton.command(GUICommands.C_EDITOPEN, gui);
final BaseXButton saveB = new BaseXButton(gui, "save", H_SAVE);
hist = new BaseXButton(gui, "hist", H_RECENTLY_OPEN);
final BaseXButton srch = new BaseXButton(gui, "search",
BaseXLayout.addShortcut(H_REPLACE, BaseXKeys.FIND.toString()));
stop = new BaseXButton(gui, "stop", H_STOP_PROCESS);
stop.addKeyListener(this);
stop.setEnabled(false);
go = new BaseXButton(gui, "go",
BaseXLayout.addShortcut(H_REPLACE, BaseXKeys.EXEC.toString()));
go.addKeyListener(this);
filter = BaseXButton.command(GUICommands.C_FILTER, gui);
filter.addKeyListener(this);
filter.setEnabled(false);
final BaseXBack buttons = new BaseXBack(Fill.NONE);
buttons.layout(new TableLayout(1, 8, 1, 0)).border(0, 0, 8, 0);
buttons.add(openB);
buttons.add(saveB);
buttons.add(hist);
buttons.add(srch);
buttons.add(Box.createHorizontalStrut(6));
buttons.add(stop);
buttons.add(go);
buttons.add(filter);
final BaseXBack b = new BaseXBack(Fill.NONE).layout(new BorderLayout());
b.add(buttons, BorderLayout.WEST);
b.add(label, BorderLayout.EAST);
add(b, BorderLayout.NORTH);
tabs = new BaseXTabs(gui);
tabs.setFocusable(Prop.MAC);
final SearchEditor se = new SearchEditor(gui, tabs, null).button(srch);
search = se.bar();
addCreateTab();
add(se, BorderLayout.CENTER);
// status and query pane
search.editor(addTab(), false);
info = new BaseXLabel().setText(OK, Msg.SUCCESS);
pos = new BaseXLabel(" ");
posCode.invokeLater();
final BaseXBack south = new BaseXBack(Fill.NONE).border(10, 0, 2, 0);
south.layout(new BorderLayout(4, 0));
south.add(info, BorderLayout.CENTER);
south.add(pos, BorderLayout.EAST);
add(south, BorderLayout.SOUTH);
refreshLayout();
// add listeners
saveB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pop = new JPopupMenu();
final StringBuilder mnem = new StringBuilder();
final JMenuItem sa = GUIMenu.newItem(GUICommands.C_EDITSAVE, gui, mnem);
final JMenuItem sas = GUIMenu.newItem(GUICommands.C_EDITSAVEAS, gui, mnem);
GUICommands.C_EDITSAVE.refresh(gui, sa);
GUICommands.C_EDITSAVEAS.refresh(gui, sas);
pop.add(sa);
pop.add(sas);
pop.show(saveB, 0, saveB.getHeight());
}
});
hist.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pm = new JPopupMenu();
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
// rewrite and open chosen file
final String s = ac.getActionCommand().replaceAll("(.*) \\[(.*)\\]", "$2/$1");
open(new IOFile(s), true);
}
};
// create popup menu with of recently opened files
final StringList opened = new StringList();
for(final EditorArea ea : editors()) opened.add(ea.file.path());
final StringList files = new StringList(HISTORY);
final StringList all = new StringList(gui.gprop.strings(GUIProp.EDITOR));
final int fl = Math.min(all.size(), e == null ? HISTORY : HISTCOMP);
for(int f = 0; f < fl; f++) files.add(all.get(f));
Font f = null;
for(final String en : files.sort(Prop.CASE)) {
// disable opened files
final JMenuItem it = new JMenuItem(en.replaceAll("(.*)[/\\\\](.*)", "$2 [$1]"));
if(opened.contains(en)) {
if(f == null) f = it.getFont().deriveFont(Font.BOLD);
it.setFont(f);
}
pm.add(it).addActionListener(al);
}
al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
hist.getActionListeners()[0].actionPerformed(null);
}
};
if(e != null && pm.getComponentCount() == HISTCOMP) {
pm.add(new JMenuItem("...")).addActionListener(al);
}
pm.show(hist, 0, hist.getHeight());
}
});
refreshHistory(null);
info.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
jumpToError();
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
stop.setEnabled(false);
go.setEnabled(false);
gui.stop();
}
});
go.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
getEditor().release(Action.EXECUTE);
}
});
tabs.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
final EditorArea ea = getEditor();
if(ea == null) return;
search.editor(ea, true);
gui.refreshControls();
posCode.invokeLater();
}
});
BaseXLayout.addDrop(this, new DropHandler() {
@Override
public void drop(final Object file) {
if(file instanceof File) open(new IOFile((File) file), true);
}
});
}
| public EditorView(final ViewNotifier man) {
super(EDITORVIEW, man);
border(5).layout(new BorderLayout());
label = new BaseXLabel(EDITOR, true, false);
label.setForeground(GUIConstants.GRAY);
final BaseXButton openB = BaseXButton.command(GUICommands.C_EDITOPEN, gui);
final BaseXButton saveB = new BaseXButton(gui, "save", H_SAVE);
hist = new BaseXButton(gui, "hist", H_RECENTLY_OPEN);
final BaseXButton srch = new BaseXButton(gui, "search",
BaseXLayout.addShortcut(H_REPLACE, BaseXKeys.FIND.toString()));
stop = new BaseXButton(gui, "stop", H_STOP_PROCESS);
stop.addKeyListener(this);
stop.setEnabled(false);
go = new BaseXButton(gui, "go",
BaseXLayout.addShortcut(H_EXECUTE_QUERY, BaseXKeys.EXEC.toString()));
go.addKeyListener(this);
filter = BaseXButton.command(GUICommands.C_FILTER, gui);
filter.addKeyListener(this);
filter.setEnabled(false);
final BaseXBack buttons = new BaseXBack(Fill.NONE);
buttons.layout(new TableLayout(1, 8, 1, 0)).border(0, 0, 8, 0);
buttons.add(openB);
buttons.add(saveB);
buttons.add(hist);
buttons.add(srch);
buttons.add(Box.createHorizontalStrut(6));
buttons.add(stop);
buttons.add(go);
buttons.add(filter);
final BaseXBack b = new BaseXBack(Fill.NONE).layout(new BorderLayout());
b.add(buttons, BorderLayout.WEST);
b.add(label, BorderLayout.EAST);
add(b, BorderLayout.NORTH);
tabs = new BaseXTabs(gui);
tabs.setFocusable(Prop.MAC);
final SearchEditor se = new SearchEditor(gui, tabs, null).button(srch);
search = se.bar();
addCreateTab();
add(se, BorderLayout.CENTER);
// status and query pane
search.editor(addTab(), false);
info = new BaseXLabel().setText(OK, Msg.SUCCESS);
pos = new BaseXLabel(" ");
posCode.invokeLater();
final BaseXBack south = new BaseXBack(Fill.NONE).border(10, 0, 2, 0);
south.layout(new BorderLayout(4, 0));
south.add(info, BorderLayout.CENTER);
south.add(pos, BorderLayout.EAST);
add(south, BorderLayout.SOUTH);
refreshLayout();
// add listeners
saveB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pop = new JPopupMenu();
final StringBuilder mnem = new StringBuilder();
final JMenuItem sa = GUIMenu.newItem(GUICommands.C_EDITSAVE, gui, mnem);
final JMenuItem sas = GUIMenu.newItem(GUICommands.C_EDITSAVEAS, gui, mnem);
GUICommands.C_EDITSAVE.refresh(gui, sa);
GUICommands.C_EDITSAVEAS.refresh(gui, sas);
pop.add(sa);
pop.add(sas);
pop.show(saveB, 0, saveB.getHeight());
}
});
hist.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pm = new JPopupMenu();
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
// rewrite and open chosen file
final String s = ac.getActionCommand().replaceAll("(.*) \\[(.*)\\]", "$2/$1");
open(new IOFile(s), true);
}
};
// create popup menu with of recently opened files
final StringList opened = new StringList();
for(final EditorArea ea : editors()) opened.add(ea.file.path());
final StringList files = new StringList(HISTORY);
final StringList all = new StringList(gui.gprop.strings(GUIProp.EDITOR));
final int fl = Math.min(all.size(), e == null ? HISTORY : HISTCOMP);
for(int f = 0; f < fl; f++) files.add(all.get(f));
Font f = null;
for(final String en : files.sort(Prop.CASE)) {
// disable opened files
final JMenuItem it = new JMenuItem(en.replaceAll("(.*)[/\\\\](.*)", "$2 [$1]"));
if(opened.contains(en)) {
if(f == null) f = it.getFont().deriveFont(Font.BOLD);
it.setFont(f);
}
pm.add(it).addActionListener(al);
}
al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
hist.getActionListeners()[0].actionPerformed(null);
}
};
if(e != null && pm.getComponentCount() == HISTCOMP) {
pm.add(new JMenuItem("...")).addActionListener(al);
}
pm.show(hist, 0, hist.getHeight());
}
});
refreshHistory(null);
info.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
jumpToError();
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
stop.setEnabled(false);
go.setEnabled(false);
gui.stop();
}
});
go.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
getEditor().release(Action.EXECUTE);
}
});
tabs.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
final EditorArea ea = getEditor();
if(ea == null) return;
search.editor(ea, true);
gui.refreshControls();
posCode.invokeLater();
}
});
BaseXLayout.addDrop(this, new DropHandler() {
@Override
public void drop(final Object file) {
if(file instanceof File) open(new IOFile((File) file), true);
}
});
}
|
diff --git a/me/duper51/BattlefieldPlugin/BFMain.java b/me/duper51/BattlefieldPlugin/BFMain.java
index 3722657..a39db88 100644
--- a/me/duper51/BattlefieldPlugin/BFMain.java
+++ b/me/duper51/BattlefieldPlugin/BFMain.java
@@ -1,29 +1,28 @@
package me.duper51.BattlefieldPlugin;
import java.util.logging.Logger;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class BFMain extends JavaPlugin {
private final BFPlayerListener plistener = new BFPlayerListener();
Logger log = Logger.getLogger("Minecraft");
@Override
public void onDisable() {
// TODO Auto-generated method stub
log.info("[BFPlugin] Battlefield Plugin is disabled.");
}
@Override
public void onEnable() {
// TODO Auto-generated method stub
PluginManager pm = getServer().getPluginManager();
- pm.registerEvent(Event.Type.PLAYER_LOGIN, plistener, null, Priority.Normal, this);
- pm.registerEvent(Event.Type.PLAYER_QUIT, plistener, null, Priority.Normal, this);
- log.info("[BFPlugin] Battlefield Plugin is enabled.");
+ pm.registerEvent(Event.Type.PLAYER_LOGIN, plistener, Priority.Normal, this);
+ pm.registerEvent(Event.Type.PLAYER_QUIT, plistener, Priority.Normal, this);
getCommand("bf").setExecutor(new BFCMDEXE());
}
}
| true | true | public void onEnable() {
// TODO Auto-generated method stub
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.PLAYER_LOGIN, plistener, null, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, plistener, null, Priority.Normal, this);
log.info("[BFPlugin] Battlefield Plugin is enabled.");
getCommand("bf").setExecutor(new BFCMDEXE());
}
| public void onEnable() {
// TODO Auto-generated method stub
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.PLAYER_LOGIN, plistener, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, plistener, Priority.Normal, this);
getCommand("bf").setExecutor(new BFCMDEXE());
}
|
diff --git a/src/main/java/org/drpowell/varitas/MendelianConstraintFilter.java b/src/main/java/org/drpowell/varitas/MendelianConstraintFilter.java
index c6524e6..ae2a97a 100644
--- a/src/main/java/org/drpowell/varitas/MendelianConstraintFilter.java
+++ b/src/main/java/org/drpowell/varitas/MendelianConstraintFilter.java
@@ -1,251 +1,251 @@
package org.drpowell.varitas;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.drpowell.util.FilteringIterator;
import org.drpowell.util.GunzipIfGZipped;
import org.drpowell.vcf.VCFHeaders;
import org.drpowell.vcf.VCFMeta;
import org.drpowell.vcf.VCFParser;
import org.drpowell.vcf.VCFUtils;
import org.drpowell.vcf.VCFVariant;
public class MendelianConstraintFilter extends FilteringIterator<VCFVariant> {
private List<int []> trios;
public static VCFMeta[] ADDITIONAL_HEADERS = {
VCFParser.parseVCFMeta("##INFO=<ID=MVCLR,Number=1,Type=Float,Description=\"Log-likelihood ratio of most likely unconstrained to constrained genotype\">"),
VCFParser.parseVCFMeta("##INFO=<ID=MENDELLR,Number=1,Type=Float,Description=\"Log-likelihood ratio of unconstrained to constrained genotypes\">"),
VCFParser.parseVCFMeta("##INFO=<ID=UNCGT,Number=1,Type=String,Description=\"Most likely unconstrained trio genotypes\">"),
VCFParser.parseVCFMeta("##INFO=<ID=CONGT,Number=1,Type=String,Description=\"Most likely genotypes under mendelian constraints\">"),
};
/**
* PL and GL fields in VCF/BCF are defined to have ordering:
* AA,
* AB, BB,
* AC, BC, CC,
* AD, BD, CD, DD, ...
*
* So that genotype (j,k) appears at position k*(k+1)/2 + j
* (with j < k, and zero-based alleles)
*
* GENOTYPE_INDEX gives the integers where bits are set to reflect the alleles
* present in the nth entry of the PL/GL array. This has been precomputed for
* up to 16 alleles at a site. Seeing as how I am only analyzing trios for now,
* this is overkill.
*/
public static final int[] GENOTYPE_INDEX = { 1, 3, 2, 5, 6, 4, 9, 10, 12, 8,
17, 18, 20, 24, 16, 33, 34, 36, 40, 48, 32, 65, 66, 68, 72, 80, 96,
64, 129, 130, 132, 136, 144, 160, 192, 128, 257, 258, 260, 264,
272, 288, 320, 384, 256, 513, 514, 516, 520, 528, 544, 576, 640,
768, 512, 1025, 1026, 1028, 1032, 1040, 1056, 1088, 1152, 1280,
1536, 1024, 2049, 2050, 2052, 2056, 2064, 2080, 2112, 2176, 2304,
2560, 3072, 2048, 4097, 4098, 4100, 4104, 4112, 4128, 4160, 4224,
4352, 4608, 5120, 6144, 4096, 8193, 8194, 8196, 8200, 8208, 8224,
8256, 8320, 8448, 8704, 9216, 10240, 12288, 8192, 16385, 16386,
16388, 16392, 16400, 16416, 16448, 16512, 16640, 16896, 17408,
18432, 20480, 24576, 16384, 32769, 32770, 32772, 32776, 32784,
32800, 32832, 32896, 33024, 33280, 33792, 34816, 36864, 40960,
49152, 32768 };
public MendelianConstraintFilter(Iterator<VCFVariant> client, VCFHeaders headers) {
super(client);
trios = VCFUtils.getTrioIndices(headers);
}
private boolean singleAllele(int genotype) {
//return Integer.bitCount(genotype) == 1;
return (genotype > 0) && ((genotype & (genotype-1)) == 0);
}
private String [] stringsFromInts(int [] in) {
String [] out = new String[in.length];
for (int i = 0; i < out.length; i++) {
out[i] = Integer.toString(in[i]);
}
return out;
}
/**
* executed for its side effect of annotating with constrained vs. unconstrained likelihood ratio
*
* @param element
* @return
*/
@Override
public VCFVariant filter(VCFVariant element) {
// FIXME - have option to only return variants with at least one MV
double [][] logLikelihoods = element.getGenotypeLikelihoods();
if (null == logLikelihoods) return element; // no likelihood info, just pass on through. FIXME-- decide whether to pass or fail
TRIO:
for (int [] trio : trios) {
// FIXME - can sometimes phase when a member of trio is missing
if (trio[0] < 0 || trio[1] < 0 || trio[2] < 0) continue;
// check that we will have all of the likelihoods we will need
double [][] trioLL = new double[trio.length][];
// 0: child 1: father 2:mother
for (int i = 0; i < trioLL.length; i++) {
if (trio[i] >= logLikelihoods.length || (trioLL[i] = logLikelihoods[trio[i]]) == null) {
// no likelihood data for this sample
element.putInfo("NOPL", (String []) null);
continue TRIO;
}
}
double maxUnconstrained = Double.NEGATIVE_INFINITY;
int [] gtUnconstrained = {0, 0, 0};
double maxConstrained = Double.NEGATIVE_INFINITY;
int [] gtConstrained = {0, 0, 0};
int [] phase = {0, 0, 0}; // for a|b, -1 => b<a, 0 => unphased, 1 => a<=b
ArrayList<Double> constrainedLikelihoods = new ArrayList<Double>(30);
ArrayList<Double> unconstrainedLikelihoods = new ArrayList<Double>(30);
// FIXME - could skip this for common cases (look if the zeros in plc, plf, plm do not violate mendelian constraints)
for (int c = 0; c < trioLL[0].length; c++) {
int ca = GENOTYPE_INDEX[c];
for (int f = 0; f < trioLL[1].length; f++) {
int fa = GENOTYPE_INDEX[f];
for (int m = 0; m < trioLL[2].length; m++) {
int ma = GENOTYPE_INDEX[m];
double sum = trioLL[0][c] + trioLL[1][f] + trioLL[2][m];
if ( (((fa|ma)&ca) == ca) && (fa&ca) > 0 && (ma&ca) > 0 ) {
// OK by mendelian rules
// if (sum == 0) return true; // special-case: ML genotype is not mendelian violation
if (sum > maxConstrained) {
maxConstrained = sum;
gtConstrained[0] = c; gtConstrained[1] = f; gtConstrained[2] = m;
if (singleAllele(ca)) { // GENOTYPE_CARDINALITY[c] == 1
// child homozygous
phase[0] = 1;
phase[1] = (fa^ca) >= ca ? 1 : -1;
phase[2] = (ma^ca) >= ca ? 1 : -1;
} else {
int father_transmitted = 0;
int mother_transmitted = 0;
if (singleAllele(fa&ca)) {
// only one allele could have come from father
father_transmitted = ca&fa;
mother_transmitted = ca^father_transmitted;
} else if (singleAllele(ma&ca)) {
// only one allele could have come from mother
mother_transmitted = ca&ma;
father_transmitted = ca^mother_transmitted;
}
if (mother_transmitted > 0 && father_transmitted > 0) {
phase[0] = father_transmitted <= mother_transmitted ? 1 : -1;
phase[1] = father_transmitted <= (father_transmitted ^ fa) ? 1 : -1;
- phase[2] = mother_transmitted <= (mother_transmitted ^ fa) ? 1 : -1;
+ phase[2] = mother_transmitted <= (mother_transmitted ^ ma) ? 1 : -1;
} else {
phase[0] = phase[1] = phase[2] = 0;
}
}
}
constrainedLikelihoods.add(sum);
} else {
// violation
if (sum > maxUnconstrained) {
maxUnconstrained = sum;
gtUnconstrained[0] = c; gtUnconstrained[1] = f; gtUnconstrained[2] = m;
}
unconstrainedLikelihoods.add(sum);
}
}
}
}
// FIXME - need to handle multiple trios better
if (maxConstrained < maxUnconstrained) {
element.putInfo("MVCLR", String.format("%.3g", maxUnconstrained - maxConstrained));
// FIXME-- this is not doing what I think it should...
element.putInfo("MENDELLR", String.format("%.3g", calcLogLikelihoodRatio(constrainedLikelihoods, unconstrainedLikelihoods)));
element.putInfo("UNCGT", getGenotypes(gtUnconstrained, null));
element.putInfo("CONGT", getGenotypes(gtConstrained, phase));
} else {
element = element.setPhases(trio, phase);
}
}
return element; // FIXME - just returning all variants for now, consider returning only phased or MV
}
private double calcLogLikelihoodRatio(ArrayList<Double> constrainedSums, ArrayList<Double> unconstrainedSums) {
return logSumOfLogs(unconstrainedSums) - logSumOfLogs(constrainedSums);
}
private final double logSumOfLogs(ArrayList<Double> logPs) {
if (logPs.size() == 1) return logPs.get(0);
// to enhance numerical stability, normalize to the maximum value
double sum = 0;
double max = Double.NEGATIVE_INFINITY;
for (Double logP : logPs) {
if (logP > max) {
max = logP;
}
}
if (Double.NEGATIVE_INFINITY == max) return max;
for (Double logP : logPs) {
if (Double.NEGATIVE_INFINITY != logP) sum += Math.pow(10.0, logP - max);
}
return max + Math.log10(sum);
}
private String [] getGenotypes(int[] genotypePLindices, int [] phase) {
String [] gts = new String[genotypePLindices.length];
for (int i = 0; i < genotypePLindices.length; i++) {
if (phase != null && i < phase.length) {
gts[i] = plIndexToAlleles(genotypePLindices[i], phase[i]);
} else {
gts[i] = plIndexToAlleles(genotypePLindices[i], 0);
}
}
return gts;
}
private final String plIndexToAlleles(int i, int phase) {
int k = (int) Math.floor(triangularRoot(i));
int j = i - (k * (k + 1)) / 2;
if (phase == 0) {
return Integer.toString(j) + "/" + Integer.toString(k);
}
if (phase < 0) {
j ^= k; k ^= j; j ^= k; // obscure swap
}
return Integer.toString(j) + "|" + Integer.toString(k);
}
private final double triangularRoot(double x) {
return (Math.sqrt(8.0 * x + 1) - 1) / 2.0;
}
public static void main(String argv[]) throws IOException {
BufferedReader br = GunzipIfGZipped.filenameToBufferedReader(argv[0]);
VCFParser p = new VCFParser(br);
VCFHeaders h = p.getHeaders();
for (VCFMeta m : ADDITIONAL_HEADERS) { h.add(m); }
System.out.print(h.toString());
System.out.println(h.getColumnHeaderLine());
int yes = 0, no = 0;
for (MendelianConstraintFilter mcf = new MendelianConstraintFilter(p.iterator(), p.getHeaders());
mcf.hasNext();) {
VCFVariant v = mcf.next();
if (v.hasInfo("MENDELLR")) {
System.out.println(v);
yes++;
} else {
System.out.println(v);
no++;
}
}
br.close();
System.err.println(String.format("%d mendelian violations, %d otherwise", yes, no));
}
}
| true | true | public VCFVariant filter(VCFVariant element) {
// FIXME - have option to only return variants with at least one MV
double [][] logLikelihoods = element.getGenotypeLikelihoods();
if (null == logLikelihoods) return element; // no likelihood info, just pass on through. FIXME-- decide whether to pass or fail
TRIO:
for (int [] trio : trios) {
// FIXME - can sometimes phase when a member of trio is missing
if (trio[0] < 0 || trio[1] < 0 || trio[2] < 0) continue;
// check that we will have all of the likelihoods we will need
double [][] trioLL = new double[trio.length][];
// 0: child 1: father 2:mother
for (int i = 0; i < trioLL.length; i++) {
if (trio[i] >= logLikelihoods.length || (trioLL[i] = logLikelihoods[trio[i]]) == null) {
// no likelihood data for this sample
element.putInfo("NOPL", (String []) null);
continue TRIO;
}
}
double maxUnconstrained = Double.NEGATIVE_INFINITY;
int [] gtUnconstrained = {0, 0, 0};
double maxConstrained = Double.NEGATIVE_INFINITY;
int [] gtConstrained = {0, 0, 0};
int [] phase = {0, 0, 0}; // for a|b, -1 => b<a, 0 => unphased, 1 => a<=b
ArrayList<Double> constrainedLikelihoods = new ArrayList<Double>(30);
ArrayList<Double> unconstrainedLikelihoods = new ArrayList<Double>(30);
// FIXME - could skip this for common cases (look if the zeros in plc, plf, plm do not violate mendelian constraints)
for (int c = 0; c < trioLL[0].length; c++) {
int ca = GENOTYPE_INDEX[c];
for (int f = 0; f < trioLL[1].length; f++) {
int fa = GENOTYPE_INDEX[f];
for (int m = 0; m < trioLL[2].length; m++) {
int ma = GENOTYPE_INDEX[m];
double sum = trioLL[0][c] + trioLL[1][f] + trioLL[2][m];
if ( (((fa|ma)&ca) == ca) && (fa&ca) > 0 && (ma&ca) > 0 ) {
// OK by mendelian rules
// if (sum == 0) return true; // special-case: ML genotype is not mendelian violation
if (sum > maxConstrained) {
maxConstrained = sum;
gtConstrained[0] = c; gtConstrained[1] = f; gtConstrained[2] = m;
if (singleAllele(ca)) { // GENOTYPE_CARDINALITY[c] == 1
// child homozygous
phase[0] = 1;
phase[1] = (fa^ca) >= ca ? 1 : -1;
phase[2] = (ma^ca) >= ca ? 1 : -1;
} else {
int father_transmitted = 0;
int mother_transmitted = 0;
if (singleAllele(fa&ca)) {
// only one allele could have come from father
father_transmitted = ca&fa;
mother_transmitted = ca^father_transmitted;
} else if (singleAllele(ma&ca)) {
// only one allele could have come from mother
mother_transmitted = ca&ma;
father_transmitted = ca^mother_transmitted;
}
if (mother_transmitted > 0 && father_transmitted > 0) {
phase[0] = father_transmitted <= mother_transmitted ? 1 : -1;
phase[1] = father_transmitted <= (father_transmitted ^ fa) ? 1 : -1;
phase[2] = mother_transmitted <= (mother_transmitted ^ fa) ? 1 : -1;
} else {
phase[0] = phase[1] = phase[2] = 0;
}
}
}
constrainedLikelihoods.add(sum);
} else {
// violation
if (sum > maxUnconstrained) {
maxUnconstrained = sum;
gtUnconstrained[0] = c; gtUnconstrained[1] = f; gtUnconstrained[2] = m;
}
unconstrainedLikelihoods.add(sum);
}
}
}
}
// FIXME - need to handle multiple trios better
if (maxConstrained < maxUnconstrained) {
element.putInfo("MVCLR", String.format("%.3g", maxUnconstrained - maxConstrained));
// FIXME-- this is not doing what I think it should...
element.putInfo("MENDELLR", String.format("%.3g", calcLogLikelihoodRatio(constrainedLikelihoods, unconstrainedLikelihoods)));
element.putInfo("UNCGT", getGenotypes(gtUnconstrained, null));
element.putInfo("CONGT", getGenotypes(gtConstrained, phase));
} else {
element = element.setPhases(trio, phase);
}
}
return element; // FIXME - just returning all variants for now, consider returning only phased or MV
}
| public VCFVariant filter(VCFVariant element) {
// FIXME - have option to only return variants with at least one MV
double [][] logLikelihoods = element.getGenotypeLikelihoods();
if (null == logLikelihoods) return element; // no likelihood info, just pass on through. FIXME-- decide whether to pass or fail
TRIO:
for (int [] trio : trios) {
// FIXME - can sometimes phase when a member of trio is missing
if (trio[0] < 0 || trio[1] < 0 || trio[2] < 0) continue;
// check that we will have all of the likelihoods we will need
double [][] trioLL = new double[trio.length][];
// 0: child 1: father 2:mother
for (int i = 0; i < trioLL.length; i++) {
if (trio[i] >= logLikelihoods.length || (trioLL[i] = logLikelihoods[trio[i]]) == null) {
// no likelihood data for this sample
element.putInfo("NOPL", (String []) null);
continue TRIO;
}
}
double maxUnconstrained = Double.NEGATIVE_INFINITY;
int [] gtUnconstrained = {0, 0, 0};
double maxConstrained = Double.NEGATIVE_INFINITY;
int [] gtConstrained = {0, 0, 0};
int [] phase = {0, 0, 0}; // for a|b, -1 => b<a, 0 => unphased, 1 => a<=b
ArrayList<Double> constrainedLikelihoods = new ArrayList<Double>(30);
ArrayList<Double> unconstrainedLikelihoods = new ArrayList<Double>(30);
// FIXME - could skip this for common cases (look if the zeros in plc, plf, plm do not violate mendelian constraints)
for (int c = 0; c < trioLL[0].length; c++) {
int ca = GENOTYPE_INDEX[c];
for (int f = 0; f < trioLL[1].length; f++) {
int fa = GENOTYPE_INDEX[f];
for (int m = 0; m < trioLL[2].length; m++) {
int ma = GENOTYPE_INDEX[m];
double sum = trioLL[0][c] + trioLL[1][f] + trioLL[2][m];
if ( (((fa|ma)&ca) == ca) && (fa&ca) > 0 && (ma&ca) > 0 ) {
// OK by mendelian rules
// if (sum == 0) return true; // special-case: ML genotype is not mendelian violation
if (sum > maxConstrained) {
maxConstrained = sum;
gtConstrained[0] = c; gtConstrained[1] = f; gtConstrained[2] = m;
if (singleAllele(ca)) { // GENOTYPE_CARDINALITY[c] == 1
// child homozygous
phase[0] = 1;
phase[1] = (fa^ca) >= ca ? 1 : -1;
phase[2] = (ma^ca) >= ca ? 1 : -1;
} else {
int father_transmitted = 0;
int mother_transmitted = 0;
if (singleAllele(fa&ca)) {
// only one allele could have come from father
father_transmitted = ca&fa;
mother_transmitted = ca^father_transmitted;
} else if (singleAllele(ma&ca)) {
// only one allele could have come from mother
mother_transmitted = ca&ma;
father_transmitted = ca^mother_transmitted;
}
if (mother_transmitted > 0 && father_transmitted > 0) {
phase[0] = father_transmitted <= mother_transmitted ? 1 : -1;
phase[1] = father_transmitted <= (father_transmitted ^ fa) ? 1 : -1;
phase[2] = mother_transmitted <= (mother_transmitted ^ ma) ? 1 : -1;
} else {
phase[0] = phase[1] = phase[2] = 0;
}
}
}
constrainedLikelihoods.add(sum);
} else {
// violation
if (sum > maxUnconstrained) {
maxUnconstrained = sum;
gtUnconstrained[0] = c; gtUnconstrained[1] = f; gtUnconstrained[2] = m;
}
unconstrainedLikelihoods.add(sum);
}
}
}
}
// FIXME - need to handle multiple trios better
if (maxConstrained < maxUnconstrained) {
element.putInfo("MVCLR", String.format("%.3g", maxUnconstrained - maxConstrained));
// FIXME-- this is not doing what I think it should...
element.putInfo("MENDELLR", String.format("%.3g", calcLogLikelihoodRatio(constrainedLikelihoods, unconstrainedLikelihoods)));
element.putInfo("UNCGT", getGenotypes(gtUnconstrained, null));
element.putInfo("CONGT", getGenotypes(gtConstrained, phase));
} else {
element = element.setPhases(trio, phase);
}
}
return element; // FIXME - just returning all variants for now, consider returning only phased or MV
}
|
diff --git a/datastore/src/main/java/org/jboss/capedwarf/datastore/query/Projections.java b/datastore/src/main/java/org/jboss/capedwarf/datastore/query/Projections.java
index eb42fe8e..12b973f9 100644
--- a/datastore/src/main/java/org/jboss/capedwarf/datastore/query/Projections.java
+++ b/datastore/src/main/java/org/jboss/capedwarf/datastore/query/Projections.java
@@ -1,358 +1,358 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.capedwarf.datastore.query;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import com.google.appengine.api.datastore.DatastoreNeedIndexException;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Projection;
import com.google.appengine.api.datastore.PropertyProjection;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.RawValue;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.hibernate.search.SearchException;
import org.infinispan.query.CacheQuery;
import org.infinispan.query.ProjectionConstants;
import org.jboss.capedwarf.common.config.CapedwarfEnvironment;
import org.jboss.capedwarf.common.reflection.ReflectionUtils;
import org.jboss.capedwarf.shared.config.IndexesXml;
/**
* Handle query projections.
*
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
* @author <a href="mailto:mluksa@redhat.com">Marko Luksa</a>
*/
class Projections {
private static final String TYPES_FIELD = "__capedwarf___TYPES___";
private static final int OFFSET = 2;
private Properties bridges = new Properties();
Projections() {
}
/**
* Apply GAE projections onto Cache projections.
*
* @param gaeQuery the GAE query
* @param cacheQuery the cache query
*/
static void applyProjections(Query gaeQuery, CacheQuery cacheQuery) {
List<String> projections = getProjections(gaeQuery);
if (projections.isEmpty() == false) {
cacheQuery.projection(projections.toArray(new String[projections.size()]));
if (!gaeQuery.isKeysOnly()) {
String fullTextFilterName = getFullTextFilterName(gaeQuery);
try {
cacheQuery.enableFullTextFilter(fullTextFilterName);
} catch (SearchException e) {
throw new DatastoreNeedIndexException("No matching index found (FullTextFilterName: " + fullTextFilterName + ")");
}
}
}
}
private static String getFullTextFilterName(Query gaeQuery) {
for (IndexesXml.Index index : CapedwarfEnvironment.getThreadLocalInstance().getIndexes().getIndexes().values()) {
if (indexMatches(index, gaeQuery)) {
return index.getName();
}
}
throw new DatastoreNeedIndexException("No matching index found");
}
private static boolean indexMatches(IndexesXml.Index index, Query query) {
if (!index.getKind().equals(query.getKind())) {
return false;
}
Set<String> filterProperties = getFilterProperties(query);
Set<String> sortProperties = getSortProperties(query);
Set<String> projectionProperties = getProjectionProperties(query);
sortProperties.removeAll(filterProperties);
projectionProperties.removeAll(filterProperties);
projectionProperties.removeAll(sortProperties);
List<String> indexProperties = index.getPropertyNames();
while (!indexProperties.isEmpty()) {
String property = indexProperties.get(0);
if (!filterProperties.isEmpty()) {
if (filterProperties.remove(property)) {
indexProperties.remove(0);
} else {
return false;
}
} else if (!sortProperties.isEmpty()) {
if (sortProperties.remove(property)) {
indexProperties.remove(0);
} else {
return false;
}
} else if (!projectionProperties.isEmpty()) {
if (projectionProperties.remove(property)) {
indexProperties.remove(0);
} else {
return false;
}
} else {
return false;
}
}
- return indexProperties.isEmpty();
+ return indexProperties.isEmpty() && filterProperties.isEmpty() && sortProperties.isEmpty() && projectionProperties.isEmpty();
}
@SuppressWarnings("deprecation")
private static Set<String> getFilterProperties(Query query) {
Set<String> set = new HashSet<>();
addFilterPropertiesToSet(set, query.getFilter());
for (Query.FilterPredicate predicate : query.getFilterPredicates()) {
addFilterPropertiesToSet(set, predicate);
}
return set;
}
private static void addFilterPropertiesToSet(Set<String> set, Query.Filter filter) {
if (filter == null) {
return;
}
if (filter instanceof Query.FilterPredicate) {
Query.FilterPredicate predicate = (Query.FilterPredicate) filter;
set.add(predicate.getPropertyName());
} else if (filter instanceof Query.CompositeFilter) {
Query.CompositeFilter composite = (Query.CompositeFilter) filter;
for (Query.Filter subFilter : composite.getSubFilters()) {
addFilterPropertiesToSet(set, subFilter);
}
} else {
throw new IllegalArgumentException("Unsupported filter type " + filter);
}
}
private static Set<String> getSortProperties(Query query) {
Set<String> set = new HashSet<>();
for (Query.SortPredicate sortPredicate : query.getSortPredicates()) {
set.add(sortPredicate.getPropertyName());
}
return set;
}
private static Set<String> getProjectionProperties(Query query) {
Set<String> set = new HashSet<>();
for (Projection projection : query.getProjections()) {
set.add(getPropertyName(projection));
}
return set;
}
private static List<String> getProjections(Query gaeQuery) {
List<String> projections = new ArrayList<String>();
if (gaeQuery.isKeysOnly()) {
projections.add(ProjectionConstants.KEY);
projections.add(TYPES_FIELD);
projections.addAll(getPropertiesRequiredOnlyForSorting(gaeQuery));
} else if (gaeQuery.getProjections().size() > 0) {
projections.add(ProjectionConstants.KEY);
projections.add(TYPES_FIELD);
for (Projection projection : gaeQuery.getProjections()) {
projections.add(getPropertyName(projection));
}
projections.addAll(getPropertiesRequiredOnlyForSorting(gaeQuery));
}
return projections;
}
public static List<String> getPropertiesRequiredOnlyForSorting(Query gaeQuery) {
List<String> list = new ArrayList<String>();
QueryResultProcessor processor = new QueryResultProcessor(gaeQuery);
if (processor.isProcessingNeeded()) {
for (String propertyName : processor.getPropertiesUsedInIn()) {
if (isOnlyNeededForSorting(propertyName, gaeQuery)) {
list.add(propertyName);
}
}
}
return list;
}
private static String getPropertyName(Projection projection) {
if (projection instanceof PropertyProjection) {
PropertyProjection propertyProjection = (PropertyProjection) projection;
return propertyProjection.getName();
} else {
throw new IllegalStateException("Unsupported projection type: " + projection.getClass());
}
}
/**
* Store property's bridge.
*
* @param propertyName the property name
* @param bridge the bridge
*/
void storePropertyBridge(String propertyName, Bridge bridge) {
bridges.put(propertyName, String.valueOf(bridge.name()));
}
/**
* Store bridges to document.
*
* @param document the Lucene document
*/
void finish(Document document) {
try {
StringWriter writer = new StringWriter();
bridges.store(writer, null);
document.add(new Field(TYPES_FIELD, writer.toString(), Field.Store.YES, Field.Index.NO));
} catch (IOException e) {
throw new IllegalArgumentException("Cannot store bridges!", e);
}
}
/**
* Read bridges.
*
* @param field the types field
* @return bridges
*/
static Properties readPropertiesBridges(String field) {
try {
Properties bridges = new Properties();
bridges.load(new StringReader(field));
return bridges;
} catch (IOException e) {
throw new IllegalArgumentException("Cannot read bridges!", e);
}
}
/**
* Convert to entity.
*
* @param query the GAE query
* @param result the current result
* @return Entity instance
*/
static Entity convertToEntity(Query query, Object result) {
if (result instanceof Entity) {
return Entity.class.cast(result);
}
final Object[] row = (Object[]) result;
final Entity entity = new Entity((Key) row[0]);
if (row.length > 1) {
final Properties bridges = readPropertiesBridges(row[1].toString());
int i = OFFSET;
for (Projection projection : query.getProjections()) {
if (projection instanceof PropertyProjection) {
PropertyProjection pp = (PropertyProjection) projection;
String propertyName = pp.getName();
Object value;
Bridge bridge = getBridge(propertyName, bridges);
if (mustBeWrappedInRawValue(pp)) {
value = bridge.getValue((String) row[i]);
value = newRawValue(value);
} else {
Class<?> type = pp.getType();
if (type != null && bridge.isAssignableTo(type) == false) {
throw new IllegalArgumentException("Wrong projection type: " + pp);
}
value = convert(bridge, row[i]);
}
entity.setProperty(propertyName, value);
} else {
throw new IllegalStateException("Unsupported projection type: " + projection.getClass());
}
i++;
}
for (String propertyName : getPropertiesRequiredOnlyForSorting(query)) {
Object value = convert(propertyName, row[i], bridges);
entity.setProperty(propertyName, value);
i++;
}
}
return entity;
}
private static boolean mustBeWrappedInRawValue(PropertyProjection propertyProjection) {
return propertyProjection.getType() == null;
}
@SuppressWarnings("SimplifiableIfStatement")
private static boolean isOnlyNeededForSorting(String propertyName, Query query) {
if (query.isKeysOnly()) {
return true;
} else if (query.getProjections().size() > 0) {
return isProjectedProperty(propertyName, query) == false;
} else {
return false;
}
}
private static boolean isProjectedProperty(String propertyName, Query query) {
for (Projection projection : query.getProjections()) {
if (projection instanceof PropertyProjection) {
PropertyProjection propertyProjection = (PropertyProjection) projection;
if (propertyProjection.getName().equals(propertyName)) {
return true;
}
}
}
return false;
}
private static Object convert(Bridge bridge, Object o) {
if (o instanceof String) {
return bridge.stringToObject(o.toString());
}
return o;
}
private static Object convert(String propertyName, Object o, Properties bridges) {
if (o instanceof String) {
final Bridge bridge = getBridge(propertyName, bridges);
return bridge.stringToObject(o.toString());
}
return o;
}
private static RawValue newRawValue(Object value) {
return ReflectionUtils.newInstance(RawValue.class, new Class[]{Object.class}, new Object[]{value});
}
private static Bridge getBridge(String propertyName, Properties bridges) {
String bridgeName = bridges.getProperty(propertyName);
return Bridge.valueOf(bridgeName);
}
}
| true | true | private static boolean indexMatches(IndexesXml.Index index, Query query) {
if (!index.getKind().equals(query.getKind())) {
return false;
}
Set<String> filterProperties = getFilterProperties(query);
Set<String> sortProperties = getSortProperties(query);
Set<String> projectionProperties = getProjectionProperties(query);
sortProperties.removeAll(filterProperties);
projectionProperties.removeAll(filterProperties);
projectionProperties.removeAll(sortProperties);
List<String> indexProperties = index.getPropertyNames();
while (!indexProperties.isEmpty()) {
String property = indexProperties.get(0);
if (!filterProperties.isEmpty()) {
if (filterProperties.remove(property)) {
indexProperties.remove(0);
} else {
return false;
}
} else if (!sortProperties.isEmpty()) {
if (sortProperties.remove(property)) {
indexProperties.remove(0);
} else {
return false;
}
} else if (!projectionProperties.isEmpty()) {
if (projectionProperties.remove(property)) {
indexProperties.remove(0);
} else {
return false;
}
} else {
return false;
}
}
return indexProperties.isEmpty();
}
| private static boolean indexMatches(IndexesXml.Index index, Query query) {
if (!index.getKind().equals(query.getKind())) {
return false;
}
Set<String> filterProperties = getFilterProperties(query);
Set<String> sortProperties = getSortProperties(query);
Set<String> projectionProperties = getProjectionProperties(query);
sortProperties.removeAll(filterProperties);
projectionProperties.removeAll(filterProperties);
projectionProperties.removeAll(sortProperties);
List<String> indexProperties = index.getPropertyNames();
while (!indexProperties.isEmpty()) {
String property = indexProperties.get(0);
if (!filterProperties.isEmpty()) {
if (filterProperties.remove(property)) {
indexProperties.remove(0);
} else {
return false;
}
} else if (!sortProperties.isEmpty()) {
if (sortProperties.remove(property)) {
indexProperties.remove(0);
} else {
return false;
}
} else if (!projectionProperties.isEmpty()) {
if (projectionProperties.remove(property)) {
indexProperties.remove(0);
} else {
return false;
}
} else {
return false;
}
}
return indexProperties.isEmpty() && filterProperties.isEmpty() && sortProperties.isEmpty() && projectionProperties.isEmpty();
}
|
diff --git a/generator/src/main/java/org/jsonddl/generator/idiomatic/IdiomaticDialect.java b/generator/src/main/java/org/jsonddl/generator/idiomatic/IdiomaticDialect.java
index dcb2c09..80bfb1a 100644
--- a/generator/src/main/java/org/jsonddl/generator/idiomatic/IdiomaticDialect.java
+++ b/generator/src/main/java/org/jsonddl/generator/idiomatic/IdiomaticDialect.java
@@ -1,169 +1,170 @@
/*
* Copyright 2011 Robert W. Vawter III <bob@vawter.org>
*
* 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.jsonddl.generator.idiomatic;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import org.jsonddl.JsonDdlVisitor;
import org.jsonddl.generator.Dialect;
import org.jsonddl.model.EnumValue;
import org.jsonddl.model.Model;
import org.jsonddl.model.Property;
import org.jsonddl.model.Schema;
import org.jsonddl.model.Type;
/**
* Produces an idiomatic representation of a schema. It won't be character-accurate to the original
* idiomatic input, but should re-parse to the same normalized version.
*/
public class IdiomaticDialect implements Dialect {
static class Visitor implements JsonDdlVisitor {
private final StringWriter contents = new StringWriter();
private final IndentedWriter out = new IndentedWriter(contents);
private boolean needsCommaAfterEnum;
private boolean needsCommaAfterModel;
private boolean needsCommaAfterProperty;
public void endVisit(EnumValue v) {
if (needsCommaAfterEnum) {
out.println(",");
} else {
needsCommaAfterEnum = true;
out.println();
}
if (v.getComment() != null) {
out.println(v.getComment());
}
out.format("\"%s\"", v.getName());
}
public void endVisit(Model m) {
out.println();
out.outdent();
if (m.getEnumValues() != null) {
out.print("]");
} else {
out.print("}");
}
}
public void endVisit(Schema s) {
out.println();
out.outdent();
out.println("};");
}
@Override
public String toString() {
return contents.toString();
}
public boolean visit(Model m) {
if (needsCommaAfterModel) {
out.println(",");
} else {
out.println();
needsCommaAfterModel = true;
}
needsCommaAfterProperty = false;
needsCommaAfterEnum = false;
if (m.getComment() != null) {
out.println(m.getComment());
}
if (m.getEnumValues() != null) {
out.println("%s : [", m.getName());
out.indent();
} else {
out.format("%s : {", m.getName());
out.indent();
}
return true;
}
public boolean visit(Property p) {
if (needsCommaAfterProperty) {
out.println(",");
} else {
needsCommaAfterProperty = true;
out.println();
}
if (p.getComment() != null) {
out.println(p.getComment());
}
out.format("%s : ", p.getName());
return true;
}
public boolean visit(Schema s, Context<Schema> ctx) {
out.print("var schema = {");
out.indent();
return true;
}
public boolean visit(Type t) {
switch (t.getKind()) {
case BOOLEAN:
out.print("false");
break;
case DDL:
case ENUM:
case EXTERNAL:
out.format("\"%s\"", t.getName());
break;
case DOUBLE:
out.print("0.0");
break;
case INTEGER:
out.print("0");
+ break;
case LIST:
out.print("[");
t.getListElement().accept(this);
out.print("]");
break;
case MAP:
out.print("{");
t.getMapKey().accept(this);
out.print(" : ");
t.getMapValue().accept(this);
out.print("}");
break;
case STRING:
out.print("\"\"");
break;
default:
throw new UnsupportedOperationException("Unknown kind " + t.getKind());
}
return false;
}
}
@Override
public void generate(String packageName, Collector output, Schema s) throws IOException {
Visitor v = new Visitor();
s.accept(v);
OutputStream out = output.writeResource(packageName.replace('.', '/') + "/idiomatic.js");
out.write(v.toString().getBytes("UTF8"));
out.close();
}
@Override
public String getName() {
return "idiomatic";
}
}
| true | true | public boolean visit(Type t) {
switch (t.getKind()) {
case BOOLEAN:
out.print("false");
break;
case DDL:
case ENUM:
case EXTERNAL:
out.format("\"%s\"", t.getName());
break;
case DOUBLE:
out.print("0.0");
break;
case INTEGER:
out.print("0");
case LIST:
out.print("[");
t.getListElement().accept(this);
out.print("]");
break;
case MAP:
out.print("{");
t.getMapKey().accept(this);
out.print(" : ");
t.getMapValue().accept(this);
out.print("}");
break;
case STRING:
out.print("\"\"");
break;
default:
throw new UnsupportedOperationException("Unknown kind " + t.getKind());
}
return false;
}
| public boolean visit(Type t) {
switch (t.getKind()) {
case BOOLEAN:
out.print("false");
break;
case DDL:
case ENUM:
case EXTERNAL:
out.format("\"%s\"", t.getName());
break;
case DOUBLE:
out.print("0.0");
break;
case INTEGER:
out.print("0");
break;
case LIST:
out.print("[");
t.getListElement().accept(this);
out.print("]");
break;
case MAP:
out.print("{");
t.getMapKey().accept(this);
out.print(" : ");
t.getMapValue().accept(this);
out.print("}");
break;
case STRING:
out.print("\"\"");
break;
default:
throw new UnsupportedOperationException("Unknown kind " + t.getKind());
}
return false;
}
|
diff --git a/src/ConsensusHealthChecker.java b/src/ConsensusHealthChecker.java
index d85c5c5..b274b03 100644
--- a/src/ConsensusHealthChecker.java
+++ b/src/ConsensusHealthChecker.java
@@ -1,747 +1,747 @@
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.commons.codec.binary.*;
/*
* TODO Possible extensions:
* - Include consensus signatures and tell by which Tor versions the
* consensus will be accepted (and by which not)
*/
public class ConsensusHealthChecker {
private String mostRecentValidAfterTime = null;
private byte[] mostRecentConsensus = null;
private SortedMap<String, byte[]> mostRecentVotes =
new TreeMap<String, byte[]>();
public void processConsensus(String validAfterTime, byte[] data) {
if (this.mostRecentValidAfterTime == null ||
this.mostRecentValidAfterTime.compareTo(validAfterTime) < 0) {
this.mostRecentValidAfterTime = validAfterTime;
this.mostRecentVotes.clear();
this.mostRecentConsensus = data;
}
}
public void processVote(String validAfterTime, String dirSource,
byte[] data) {
if (this.mostRecentValidAfterTime == null ||
this.mostRecentValidAfterTime.compareTo(validAfterTime) < 0) {
this.mostRecentValidAfterTime = validAfterTime;
this.mostRecentVotes.clear();
this.mostRecentConsensus = null;
}
if (this.mostRecentValidAfterTime.equals(validAfterTime)) {
this.mostRecentVotes.put(dirSource, data);
}
}
public void writeStatusWebsite() {
/* If we don't have any consensus, we cannot write useful consensus
* health information to the website. Do not overwrite existing page
* with a warning, because we might just not have learned about a new
* consensus in this execution. */
if (this.mostRecentConsensus == null) {
return;
}
/* Prepare parsing dates. */
SimpleDateFormat dateTimeFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
StringBuilder knownFlagsResults = new StringBuilder();
StringBuilder numRelaysVotesResults = new StringBuilder();
StringBuilder consensusMethodsResults = new StringBuilder();
StringBuilder versionsResults = new StringBuilder();
StringBuilder paramsResults = new StringBuilder();
StringBuilder authorityKeysResults = new StringBuilder();
StringBuilder bandwidthScannersResults = new StringBuilder();
SortedSet<String> allKnownFlags = new TreeSet<String>();
SortedSet<String> allKnownVotes = new TreeSet<String>();
SortedMap<String, String> consensusAssignedFlags =
new TreeMap<String, String>();
SortedMap<String, SortedSet<String>> votesAssignedFlags =
new TreeMap<String, SortedSet<String>>();
SortedMap<String, String> votesKnownFlags =
new TreeMap<String, String>();
SortedMap<String, SortedMap<String, Integer>> flagsAgree =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsLost =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsMissing =
new TreeMap<String, SortedMap<String, Integer>>();
/* Read consensus and parse all information that we want to compare to
* votes. */
String consensusConsensusMethod = null, consensusKnownFlags = null,
consensusClientVersions = null, consensusServerVersions = null,
consensusParams = null, rLineTemp = null;
int consensusTotalRelays = 0, consensusRunningRelays = 0;
Scanner s = new Scanner(new String(this.mostRecentConsensus));
while (s.hasNextLine()) {
String line = s.nextLine();
if (line.startsWith("consensus-method ")) {
consensusConsensusMethod = line;
} else if (line.startsWith("client-versions ")) {
consensusClientVersions = line;
} else if (line.startsWith("server-versions ")) {
consensusServerVersions = line;
} else if (line.startsWith("known-flags ")) {
consensusKnownFlags = line;
} else if (line.startsWith("params ")) {
consensusParams = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
consensusTotalRelays++;
if (line.contains(" Running")) {
consensusRunningRelays++;
}
consensusAssignedFlags.put(Hex.encodeHexString(
Base64.decodeBase64(rLineTemp.split(" ")[2] + "=")).
toUpperCase() + " " + rLineTemp.split(" ")[1], line);
}
}
s.close();
/* Read votes and parse all information to compare with the
* consensus. */
for (byte[] voteBytes : this.mostRecentVotes.values()) {
String voteConsensusMethods = null, voteKnownFlags = null,
voteClientVersions = null, voteServerVersions = null,
voteParams = null, dirSource = null, voteDirKeyExpires = null;
int voteTotalRelays = 0, voteRunningRelays = 0,
voteContainsBandwidthWeights = 0;
s = new Scanner(new String(voteBytes));
while (s.hasNextLine()) {
String line = s.nextLine();
if (line.startsWith("consensus-methods ")) {
voteConsensusMethods = line;
} else if (line.startsWith("client-versions ")) {
voteClientVersions = line;
} else if (line.startsWith("server-versions ")) {
voteServerVersions = line;
} else if (line.startsWith("known-flags ")) {
voteKnownFlags = line;
} else if (line.startsWith("params ")) {
voteParams = line;
} else if (line.startsWith("dir-source ")) {
dirSource = line.split(" ")[1];
allKnownVotes.add(dirSource);
} else if (line.startsWith("dir-key-expires ")) {
voteDirKeyExpires = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
voteTotalRelays++;
if (line.contains(" Running")) {
voteRunningRelays++;
}
String relayKey = Hex.encodeHexString(Base64.decodeBase64(
rLineTemp.split(" ")[2] + "=")).toUpperCase() + " "
+ rLineTemp.split(" ")[1];
SortedSet<String> sLines = null;
if (votesAssignedFlags.containsKey(relayKey)) {
sLines = votesAssignedFlags.get(relayKey);
} else {
sLines = new TreeSet<String>();
votesAssignedFlags.put(relayKey, sLines);
}
sLines.add(dirSource + " " + line);
} else if (line.startsWith("w ")) {
if (line.contains(" Measured")) {
voteContainsBandwidthWeights++;
}
}
}
s.close();
/* Write known flags. */
knownFlagsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteKnownFlags + "</td>\n"
+ " </tr>\n");
votesKnownFlags.put(dirSource, voteKnownFlags);
for (String flag : voteKnownFlags.substring(
"known-flags ".length()).split(" ")) {
allKnownFlags.add(flag);
}
/* Write number of relays voted about. */
numRelaysVotesResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteTotalRelays + " total</td>\n"
+ " <td>" + voteRunningRelays + " Running</td>\n"
+ " </tr>\n");
/* Write supported consensus methods. */
if (!voteConsensusMethods.contains(consensusConsensusMethod.
split(" ")[1])) {
consensusMethodsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteConsensusMethods + "</font></td>\n"
+ " </tr>\n");
} else {
consensusMethodsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteConsensusMethods + "</td>\n"
+ " </tr>\n");
}
/* Write recommended versions. */
if (voteClientVersions == null) {
/* Not a versioning authority. */
} else if (!voteClientVersions.equals(consensusClientVersions)) {
versionsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteClientVersions + "</font></td>\n"
+ " </tr>\n");
} else {
versionsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteClientVersions + "</td>\n"
+ " </tr>\n");
}
if (voteServerVersions == null) {
/* Not a versioning authority. */
} else if (!voteServerVersions.equals(consensusServerVersions)) {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td><font color=\"red\">"
- + voteClientVersions + "</font></td>\n"
+ + voteServerVersions + "</font></td>\n"
+ " </tr>\n");
} else {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td>" + voteServerVersions + "</td>\n"
+ " </tr>\n");
}
/* Write consensus parameters. */
if (voteParams == null) {
/* Authority doesn't set consensus parameters. */
} else if (!voteParams.equals(consensusParams)) {
paramsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteParams + "</font></td>\n"
+ " </tr>\n");
} else {
paramsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteParams + "</td>\n"
+ " </tr>\n");
}
/* Write authority key expiration date. */
if (voteDirKeyExpires != null) {
boolean expiresIn14Days = false;
try {
expiresIn14Days = (System.currentTimeMillis()
+ 14L * 24L * 60L * 60L * 1000L >
dateTimeFormat.parse(voteDirKeyExpires.substring(
"dir-key-expires ".length())).getTime());
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (expiresIn14Days) {
authorityKeysResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteDirKeyExpires + "</font></td>\n"
+ " </tr>\n");
} else {
authorityKeysResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteDirKeyExpires + "</td>\n"
+ " </tr>\n");
}
}
/* Write results for bandwidth scanner status. */
if (voteContainsBandwidthWeights > 0) {
bandwidthScannersResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteContainsBandwidthWeights
+ " Measured values in w lines<td/>\n"
+ " </tr>\n");
}
}
try {
/* Keep the past two consensus health statuses. */
File file0 = new File("website/consensus-health.html");
File file1 = new File("website/consensus-health-1.html");
File file2 = new File("website/consensus-health-2.html");
if (file2.exists()) {
file2.delete();
}
if (file1.exists()) {
file1.renameTo(file2);
}
if (file0.exists()) {
file0.renameTo(file1);
}
/* Start writing web page. */
BufferedWriter bw = new BufferedWriter(
new FileWriter("website/consensus-health.html"));
bw.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>Tor Metrics Portal: Consensus health</title>\n"
+ " <meta http-equiv=Content-Type content=\"text/html; "
+ "charset=iso-8859-1\">\n"
+ " <link href=\"http://www.torproject.org/stylesheet-"
+ "ltr.css\" type=text/css rel=stylesheet>\n"
+ " <link href=\"http://www.torproject.org/favicon.ico\""
+ " type=image/x-icon rel=\"shortcut icon\">\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"center\">\n"
+ " <table class=\"banner\" border=\"0\" "
+ "cellpadding=\"0\" cellspacing=\"0\" summary=\"\">\n"
+ " <tr>\n"
+ " <td class=\"banner-left\"><a href=\"https://"
+ "www.torproject.org/\"><img src=\"http://www.torproject"
+ ".org/images/top-left.png\" alt=\"Click to go to home "
+ "page\" width=\"193\" height=\"79\"></a></td>\n"
+ " <td class=\"banner-middle\">\n"
+ " <a href=\"/\">Home</a>\n"
+ " <a href=\"graphs.html\">Graphs</a>\n"
+ " <a href=\"reports.html\">Reports</a>\n"
+ " <a href=\"papers.html\">Papers</a>\n"
+ " <a href=\"data.html\">Data</a>\n"
+ " <a href=\"tools.html\">Tools</a>\n"
+ " </td>\n"
+ " <td class=\"banner-right\"></td>\n"
+ " </tr>\n"
+ " </table>\n"
+ " <div class=\"main-column\">\n"
+ " <h2>Tor Metrics Portal: Consensus Health</h2>\n"
+ " <br/>\n"
+ " <p>This page shows statistics about the current "
+ "consensus and votes to facilitate debugging of the "
+ "directory consensus process.</p>\n");
/* Write valid-after time. */
bw.write(" <br/>\n"
+ " <h3>Valid-after time</h3>\n"
+ " <br/>\n"
+ " <p>Consensus was published ");
boolean consensusIsStale = false;
try {
consensusIsStale = System.currentTimeMillis()
- 3L * 60L * 60L * 1000L >
dateTimeFormat.parse(this.mostRecentValidAfterTime).getTime();
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (consensusIsStale) {
bw.write("<font color=\"red\">" + this.mostRecentValidAfterTime
+ "</font>");
} else {
bw.write(this.mostRecentValidAfterTime);
}
bw.write(". <i>Note that it takes "
+ "15 to 30 minutes for the metrics portal to learn about "
+ "new consensus and votes and process them.</i></p>\n");
/* Write known flags. */
bw.write(" <br/>\n"
+ " <h3>Known flags</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (knownFlagsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(knownFlagsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusKnownFlags + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write number of relays voted about. */
bw.write(" <br/>\n"
+ " <h3>Number of relays voted about</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"320\">\n"
+ " <col width=\"320\">\n"
+ " </colgroup>\n");
if (numRelaysVotesResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/><td/></tr>\n");
} else {
bw.write(numRelaysVotesResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusTotalRelays + " total</font></td>\n"
+ " <td><font color=\"blue\">"
+ consensusRunningRelays + " Running</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus methods. */
bw.write(" <br/>\n"
+ " <h3>Consensus methods</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (consensusMethodsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(consensusMethodsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusConsensusMethod + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write recommended versions. */
bw.write(" <br/>\n"
+ " <h3>Recommended versions</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (versionsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(versionsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusClientVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" <td/>\n"
+ " <td><font color=\"blue\">"
+ consensusServerVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus parameters. */
bw.write(" <br/>\n"
+ " <h3>Consensus parameters</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (paramsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(paramsResults.toString());
}
bw.write(" <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusParams + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write authority keys. */
bw.write(" <br/>\n"
+ " <h3>Authority keys</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (authorityKeysResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(authorityKeysResults.toString());
}
bw.write(" </table>\n"
+ " <br/>\n"
+ " <p><i>Note that expiration dates of legacy keys are "
+ "not included in votes and therefore not listed here!</i>"
+ "</p>\n");
/* Write bandwidth scanner status. */
bw.write(" <br/>\n"
+ " <h3>Bandwidth scanner status</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (bandwidthScannersResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(bandwidthScannersResults.toString());
}
bw.write(" </table>\n");
/* Write (huge) table with all flags. */
bw.write(" <br/>\n"
+ " <h3>Relay flags</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of flags written in the table is "
+ "as follows:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " <li><b><font color=\"blue\">In "
+ "consensus:</font></b> Flag in consensus</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <p>See also the summary below the table.</p>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"120\">\n"
+ " <col width=\"80\">\n");
for (int i = 0; i < allKnownVotes.size(); i++) {
bw.write(" <col width=\""
+ (640 / allKnownVotes.size()) + "\">\n");
}
bw.write(" </colgroup>\n");
int linesWritten = 0;
for (Map.Entry<String, SortedSet<String>> e :
votesAssignedFlags.entrySet()) {
if (linesWritten++ % 10 == 0) {
bw.write(" <tr><td/><td/>\n");
for (String dir : allKnownVotes) {
String shortDirName = dir.length() > 6 ?
dir.substring(0, 5) + "." : dir;
bw.write("<td><br/><b>" + shortDirName + "</b></td>");
}
bw.write("<td><br/><b>consensus</b></td></tr>\n");
}
String relayKey = e.getKey();
SortedSet<String> votes = e.getValue();
String fingerprint = relayKey.split(" ")[0].substring(0, 8);
String nickname = relayKey.split(" ")[1];
bw.write(" <tr>\n"
+ " <td>" + fingerprint + "</td>\n"
+ " <td>" + nickname + "</td>\n");
SortedSet<String> relevantFlags = new TreeSet<String>();
for (String vote : votes) {
String[] parts = vote.split(" ");
for (int j = 2; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
String consensusFlags = null;
if (consensusAssignedFlags.containsKey(relayKey)) {
consensusFlags = consensusAssignedFlags.get(relayKey);
String[] parts = consensusFlags.split(" ");
for (int j = 1; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
for (String dir : allKnownVotes) {
String flags = null;
for (String vote : votes) {
if (vote.startsWith(dir)) {
flags = vote;
break;
}
}
if (flags != null) {
votes.remove(flags);
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
SortedMap<String, SortedMap<String, Integer>> sums = null;
if (flags.contains(" " + flag)) {
if (consensusFlags == null ||
consensusFlags.contains(" " + flag)) {
bw.write(flag);
sums = flagsAgree;
} else {
bw.write("<font color=\"red\">" + flag + "</font>");
sums = flagsLost;
}
} else if (consensusFlags != null &&
votesKnownFlags.get(dir).contains(" " + flag) &&
consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"gray\"><s>" + flag
+ "</s></font>");
sums = flagsMissing;
}
if (sums != null) {
SortedMap<String, Integer> sum = null;
if (sums.containsKey(dir)) {
sum = sums.get(dir);
} else {
sum = new TreeMap<String, Integer>();
sums.put(dir, sum);
}
sum.put(flag, sum.containsKey(flag) ?
sum.get(flag) + 1 : 1);
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
}
if (consensusFlags != null) {
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
if (consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"blue\">" + flag + "</font>");
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
bw.write(" </table>\n");
/* Write summary of overlap between votes and consensus. */
bw.write(" <br/>\n"
+ " <h3>Overlap between votes and consensus</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of columns is similar to the "
+ "table above:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " </colgroup>\n");
bw.write(" <tr><td/><td><b>Only in vote</b></td>"
+ "<td><b>In vote and consensus</b></td>"
+ "<td><b>Only in consensus</b></td>\n");
for (String dir : allKnownVotes) {
boolean firstFlagWritten = false;
String[] flags = votesKnownFlags.get(dir).substring(
"known-flags ".length()).split(" ");
for (String flag : flags) {
bw.write(" <tr>\n");
if (firstFlagWritten) {
bw.write(" <td/>\n");
} else {
bw.write(" <td>" + dir + "</td>\n");
firstFlagWritten = true;
}
if (flagsLost.containsKey(dir) &&
flagsLost.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"red\"> "
+ flagsLost.get(dir).get(flag) + " " + flag
+ "</font></td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsAgree.containsKey(dir) &&
flagsAgree.get(dir).containsKey(flag)) {
bw.write(" <td>" + flagsAgree.get(dir).get(flag)
+ " " + flag + "</td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsMissing.containsKey(dir) &&
flagsMissing.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"gray\"><s>"
+ flagsMissing.get(dir).get(flag) + " " + flag
+ "</s></font></td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
}
bw.write(" </table>\n");
/* Finish writing. */
bw.write(" </div>\n"
+ " </div>\n"
+ " <div class=\"bottom\" id=\"bottom\">\n"
+ " <p>\"Tor\" and the \"Onion Logo\" are <a "
+ "href=\"https://www.torproject.org/trademark-faq.html"
+ ".en\">"
+ "registered trademarks</a> of The Tor Project, "
+ "Inc.</p>\n"
+ " </div>\n"
+ " </body>\n"
+ "</html>");
bw.close();
} catch (IOException e) {
}
}
}
| true | true | public void writeStatusWebsite() {
/* If we don't have any consensus, we cannot write useful consensus
* health information to the website. Do not overwrite existing page
* with a warning, because we might just not have learned about a new
* consensus in this execution. */
if (this.mostRecentConsensus == null) {
return;
}
/* Prepare parsing dates. */
SimpleDateFormat dateTimeFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
StringBuilder knownFlagsResults = new StringBuilder();
StringBuilder numRelaysVotesResults = new StringBuilder();
StringBuilder consensusMethodsResults = new StringBuilder();
StringBuilder versionsResults = new StringBuilder();
StringBuilder paramsResults = new StringBuilder();
StringBuilder authorityKeysResults = new StringBuilder();
StringBuilder bandwidthScannersResults = new StringBuilder();
SortedSet<String> allKnownFlags = new TreeSet<String>();
SortedSet<String> allKnownVotes = new TreeSet<String>();
SortedMap<String, String> consensusAssignedFlags =
new TreeMap<String, String>();
SortedMap<String, SortedSet<String>> votesAssignedFlags =
new TreeMap<String, SortedSet<String>>();
SortedMap<String, String> votesKnownFlags =
new TreeMap<String, String>();
SortedMap<String, SortedMap<String, Integer>> flagsAgree =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsLost =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsMissing =
new TreeMap<String, SortedMap<String, Integer>>();
/* Read consensus and parse all information that we want to compare to
* votes. */
String consensusConsensusMethod = null, consensusKnownFlags = null,
consensusClientVersions = null, consensusServerVersions = null,
consensusParams = null, rLineTemp = null;
int consensusTotalRelays = 0, consensusRunningRelays = 0;
Scanner s = new Scanner(new String(this.mostRecentConsensus));
while (s.hasNextLine()) {
String line = s.nextLine();
if (line.startsWith("consensus-method ")) {
consensusConsensusMethod = line;
} else if (line.startsWith("client-versions ")) {
consensusClientVersions = line;
} else if (line.startsWith("server-versions ")) {
consensusServerVersions = line;
} else if (line.startsWith("known-flags ")) {
consensusKnownFlags = line;
} else if (line.startsWith("params ")) {
consensusParams = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
consensusTotalRelays++;
if (line.contains(" Running")) {
consensusRunningRelays++;
}
consensusAssignedFlags.put(Hex.encodeHexString(
Base64.decodeBase64(rLineTemp.split(" ")[2] + "=")).
toUpperCase() + " " + rLineTemp.split(" ")[1], line);
}
}
s.close();
/* Read votes and parse all information to compare with the
* consensus. */
for (byte[] voteBytes : this.mostRecentVotes.values()) {
String voteConsensusMethods = null, voteKnownFlags = null,
voteClientVersions = null, voteServerVersions = null,
voteParams = null, dirSource = null, voteDirKeyExpires = null;
int voteTotalRelays = 0, voteRunningRelays = 0,
voteContainsBandwidthWeights = 0;
s = new Scanner(new String(voteBytes));
while (s.hasNextLine()) {
String line = s.nextLine();
if (line.startsWith("consensus-methods ")) {
voteConsensusMethods = line;
} else if (line.startsWith("client-versions ")) {
voteClientVersions = line;
} else if (line.startsWith("server-versions ")) {
voteServerVersions = line;
} else if (line.startsWith("known-flags ")) {
voteKnownFlags = line;
} else if (line.startsWith("params ")) {
voteParams = line;
} else if (line.startsWith("dir-source ")) {
dirSource = line.split(" ")[1];
allKnownVotes.add(dirSource);
} else if (line.startsWith("dir-key-expires ")) {
voteDirKeyExpires = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
voteTotalRelays++;
if (line.contains(" Running")) {
voteRunningRelays++;
}
String relayKey = Hex.encodeHexString(Base64.decodeBase64(
rLineTemp.split(" ")[2] + "=")).toUpperCase() + " "
+ rLineTemp.split(" ")[1];
SortedSet<String> sLines = null;
if (votesAssignedFlags.containsKey(relayKey)) {
sLines = votesAssignedFlags.get(relayKey);
} else {
sLines = new TreeSet<String>();
votesAssignedFlags.put(relayKey, sLines);
}
sLines.add(dirSource + " " + line);
} else if (line.startsWith("w ")) {
if (line.contains(" Measured")) {
voteContainsBandwidthWeights++;
}
}
}
s.close();
/* Write known flags. */
knownFlagsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteKnownFlags + "</td>\n"
+ " </tr>\n");
votesKnownFlags.put(dirSource, voteKnownFlags);
for (String flag : voteKnownFlags.substring(
"known-flags ".length()).split(" ")) {
allKnownFlags.add(flag);
}
/* Write number of relays voted about. */
numRelaysVotesResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteTotalRelays + " total</td>\n"
+ " <td>" + voteRunningRelays + " Running</td>\n"
+ " </tr>\n");
/* Write supported consensus methods. */
if (!voteConsensusMethods.contains(consensusConsensusMethod.
split(" ")[1])) {
consensusMethodsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteConsensusMethods + "</font></td>\n"
+ " </tr>\n");
} else {
consensusMethodsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteConsensusMethods + "</td>\n"
+ " </tr>\n");
}
/* Write recommended versions. */
if (voteClientVersions == null) {
/* Not a versioning authority. */
} else if (!voteClientVersions.equals(consensusClientVersions)) {
versionsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteClientVersions + "</font></td>\n"
+ " </tr>\n");
} else {
versionsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteClientVersions + "</td>\n"
+ " </tr>\n");
}
if (voteServerVersions == null) {
/* Not a versioning authority. */
} else if (!voteServerVersions.equals(consensusServerVersions)) {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td><font color=\"red\">"
+ voteClientVersions + "</font></td>\n"
+ " </tr>\n");
} else {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td>" + voteServerVersions + "</td>\n"
+ " </tr>\n");
}
/* Write consensus parameters. */
if (voteParams == null) {
/* Authority doesn't set consensus parameters. */
} else if (!voteParams.equals(consensusParams)) {
paramsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteParams + "</font></td>\n"
+ " </tr>\n");
} else {
paramsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteParams + "</td>\n"
+ " </tr>\n");
}
/* Write authority key expiration date. */
if (voteDirKeyExpires != null) {
boolean expiresIn14Days = false;
try {
expiresIn14Days = (System.currentTimeMillis()
+ 14L * 24L * 60L * 60L * 1000L >
dateTimeFormat.parse(voteDirKeyExpires.substring(
"dir-key-expires ".length())).getTime());
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (expiresIn14Days) {
authorityKeysResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteDirKeyExpires + "</font></td>\n"
+ " </tr>\n");
} else {
authorityKeysResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteDirKeyExpires + "</td>\n"
+ " </tr>\n");
}
}
/* Write results for bandwidth scanner status. */
if (voteContainsBandwidthWeights > 0) {
bandwidthScannersResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteContainsBandwidthWeights
+ " Measured values in w lines<td/>\n"
+ " </tr>\n");
}
}
try {
/* Keep the past two consensus health statuses. */
File file0 = new File("website/consensus-health.html");
File file1 = new File("website/consensus-health-1.html");
File file2 = new File("website/consensus-health-2.html");
if (file2.exists()) {
file2.delete();
}
if (file1.exists()) {
file1.renameTo(file2);
}
if (file0.exists()) {
file0.renameTo(file1);
}
/* Start writing web page. */
BufferedWriter bw = new BufferedWriter(
new FileWriter("website/consensus-health.html"));
bw.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>Tor Metrics Portal: Consensus health</title>\n"
+ " <meta http-equiv=Content-Type content=\"text/html; "
+ "charset=iso-8859-1\">\n"
+ " <link href=\"http://www.torproject.org/stylesheet-"
+ "ltr.css\" type=text/css rel=stylesheet>\n"
+ " <link href=\"http://www.torproject.org/favicon.ico\""
+ " type=image/x-icon rel=\"shortcut icon\">\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"center\">\n"
+ " <table class=\"banner\" border=\"0\" "
+ "cellpadding=\"0\" cellspacing=\"0\" summary=\"\">\n"
+ " <tr>\n"
+ " <td class=\"banner-left\"><a href=\"https://"
+ "www.torproject.org/\"><img src=\"http://www.torproject"
+ ".org/images/top-left.png\" alt=\"Click to go to home "
+ "page\" width=\"193\" height=\"79\"></a></td>\n"
+ " <td class=\"banner-middle\">\n"
+ " <a href=\"/\">Home</a>\n"
+ " <a href=\"graphs.html\">Graphs</a>\n"
+ " <a href=\"reports.html\">Reports</a>\n"
+ " <a href=\"papers.html\">Papers</a>\n"
+ " <a href=\"data.html\">Data</a>\n"
+ " <a href=\"tools.html\">Tools</a>\n"
+ " </td>\n"
+ " <td class=\"banner-right\"></td>\n"
+ " </tr>\n"
+ " </table>\n"
+ " <div class=\"main-column\">\n"
+ " <h2>Tor Metrics Portal: Consensus Health</h2>\n"
+ " <br/>\n"
+ " <p>This page shows statistics about the current "
+ "consensus and votes to facilitate debugging of the "
+ "directory consensus process.</p>\n");
/* Write valid-after time. */
bw.write(" <br/>\n"
+ " <h3>Valid-after time</h3>\n"
+ " <br/>\n"
+ " <p>Consensus was published ");
boolean consensusIsStale = false;
try {
consensusIsStale = System.currentTimeMillis()
- 3L * 60L * 60L * 1000L >
dateTimeFormat.parse(this.mostRecentValidAfterTime).getTime();
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (consensusIsStale) {
bw.write("<font color=\"red\">" + this.mostRecentValidAfterTime
+ "</font>");
} else {
bw.write(this.mostRecentValidAfterTime);
}
bw.write(". <i>Note that it takes "
+ "15 to 30 minutes for the metrics portal to learn about "
+ "new consensus and votes and process them.</i></p>\n");
/* Write known flags. */
bw.write(" <br/>\n"
+ " <h3>Known flags</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (knownFlagsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(knownFlagsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusKnownFlags + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write number of relays voted about. */
bw.write(" <br/>\n"
+ " <h3>Number of relays voted about</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"320\">\n"
+ " <col width=\"320\">\n"
+ " </colgroup>\n");
if (numRelaysVotesResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/><td/></tr>\n");
} else {
bw.write(numRelaysVotesResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusTotalRelays + " total</font></td>\n"
+ " <td><font color=\"blue\">"
+ consensusRunningRelays + " Running</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus methods. */
bw.write(" <br/>\n"
+ " <h3>Consensus methods</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (consensusMethodsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(consensusMethodsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusConsensusMethod + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write recommended versions. */
bw.write(" <br/>\n"
+ " <h3>Recommended versions</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (versionsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(versionsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusClientVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" <td/>\n"
+ " <td><font color=\"blue\">"
+ consensusServerVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus parameters. */
bw.write(" <br/>\n"
+ " <h3>Consensus parameters</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (paramsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(paramsResults.toString());
}
bw.write(" <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusParams + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write authority keys. */
bw.write(" <br/>\n"
+ " <h3>Authority keys</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (authorityKeysResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(authorityKeysResults.toString());
}
bw.write(" </table>\n"
+ " <br/>\n"
+ " <p><i>Note that expiration dates of legacy keys are "
+ "not included in votes and therefore not listed here!</i>"
+ "</p>\n");
/* Write bandwidth scanner status. */
bw.write(" <br/>\n"
+ " <h3>Bandwidth scanner status</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (bandwidthScannersResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(bandwidthScannersResults.toString());
}
bw.write(" </table>\n");
/* Write (huge) table with all flags. */
bw.write(" <br/>\n"
+ " <h3>Relay flags</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of flags written in the table is "
+ "as follows:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " <li><b><font color=\"blue\">In "
+ "consensus:</font></b> Flag in consensus</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <p>See also the summary below the table.</p>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"120\">\n"
+ " <col width=\"80\">\n");
for (int i = 0; i < allKnownVotes.size(); i++) {
bw.write(" <col width=\""
+ (640 / allKnownVotes.size()) + "\">\n");
}
bw.write(" </colgroup>\n");
int linesWritten = 0;
for (Map.Entry<String, SortedSet<String>> e :
votesAssignedFlags.entrySet()) {
if (linesWritten++ % 10 == 0) {
bw.write(" <tr><td/><td/>\n");
for (String dir : allKnownVotes) {
String shortDirName = dir.length() > 6 ?
dir.substring(0, 5) + "." : dir;
bw.write("<td><br/><b>" + shortDirName + "</b></td>");
}
bw.write("<td><br/><b>consensus</b></td></tr>\n");
}
String relayKey = e.getKey();
SortedSet<String> votes = e.getValue();
String fingerprint = relayKey.split(" ")[0].substring(0, 8);
String nickname = relayKey.split(" ")[1];
bw.write(" <tr>\n"
+ " <td>" + fingerprint + "</td>\n"
+ " <td>" + nickname + "</td>\n");
SortedSet<String> relevantFlags = new TreeSet<String>();
for (String vote : votes) {
String[] parts = vote.split(" ");
for (int j = 2; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
String consensusFlags = null;
if (consensusAssignedFlags.containsKey(relayKey)) {
consensusFlags = consensusAssignedFlags.get(relayKey);
String[] parts = consensusFlags.split(" ");
for (int j = 1; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
for (String dir : allKnownVotes) {
String flags = null;
for (String vote : votes) {
if (vote.startsWith(dir)) {
flags = vote;
break;
}
}
if (flags != null) {
votes.remove(flags);
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
SortedMap<String, SortedMap<String, Integer>> sums = null;
if (flags.contains(" " + flag)) {
if (consensusFlags == null ||
consensusFlags.contains(" " + flag)) {
bw.write(flag);
sums = flagsAgree;
} else {
bw.write("<font color=\"red\">" + flag + "</font>");
sums = flagsLost;
}
} else if (consensusFlags != null &&
votesKnownFlags.get(dir).contains(" " + flag) &&
consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"gray\"><s>" + flag
+ "</s></font>");
sums = flagsMissing;
}
if (sums != null) {
SortedMap<String, Integer> sum = null;
if (sums.containsKey(dir)) {
sum = sums.get(dir);
} else {
sum = new TreeMap<String, Integer>();
sums.put(dir, sum);
}
sum.put(flag, sum.containsKey(flag) ?
sum.get(flag) + 1 : 1);
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
}
if (consensusFlags != null) {
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
if (consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"blue\">" + flag + "</font>");
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
bw.write(" </table>\n");
/* Write summary of overlap between votes and consensus. */
bw.write(" <br/>\n"
+ " <h3>Overlap between votes and consensus</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of columns is similar to the "
+ "table above:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " </colgroup>\n");
bw.write(" <tr><td/><td><b>Only in vote</b></td>"
+ "<td><b>In vote and consensus</b></td>"
+ "<td><b>Only in consensus</b></td>\n");
for (String dir : allKnownVotes) {
boolean firstFlagWritten = false;
String[] flags = votesKnownFlags.get(dir).substring(
"known-flags ".length()).split(" ");
for (String flag : flags) {
bw.write(" <tr>\n");
if (firstFlagWritten) {
bw.write(" <td/>\n");
} else {
bw.write(" <td>" + dir + "</td>\n");
firstFlagWritten = true;
}
if (flagsLost.containsKey(dir) &&
flagsLost.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"red\"> "
+ flagsLost.get(dir).get(flag) + " " + flag
+ "</font></td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsAgree.containsKey(dir) &&
flagsAgree.get(dir).containsKey(flag)) {
bw.write(" <td>" + flagsAgree.get(dir).get(flag)
+ " " + flag + "</td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsMissing.containsKey(dir) &&
flagsMissing.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"gray\"><s>"
+ flagsMissing.get(dir).get(flag) + " " + flag
+ "</s></font></td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
}
bw.write(" </table>\n");
/* Finish writing. */
bw.write(" </div>\n"
+ " </div>\n"
+ " <div class=\"bottom\" id=\"bottom\">\n"
+ " <p>\"Tor\" and the \"Onion Logo\" are <a "
+ "href=\"https://www.torproject.org/trademark-faq.html"
+ ".en\">"
+ "registered trademarks</a> of The Tor Project, "
+ "Inc.</p>\n"
+ " </div>\n"
+ " </body>\n"
+ "</html>");
bw.close();
} catch (IOException e) {
}
}
| public void writeStatusWebsite() {
/* If we don't have any consensus, we cannot write useful consensus
* health information to the website. Do not overwrite existing page
* with a warning, because we might just not have learned about a new
* consensus in this execution. */
if (this.mostRecentConsensus == null) {
return;
}
/* Prepare parsing dates. */
SimpleDateFormat dateTimeFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
StringBuilder knownFlagsResults = new StringBuilder();
StringBuilder numRelaysVotesResults = new StringBuilder();
StringBuilder consensusMethodsResults = new StringBuilder();
StringBuilder versionsResults = new StringBuilder();
StringBuilder paramsResults = new StringBuilder();
StringBuilder authorityKeysResults = new StringBuilder();
StringBuilder bandwidthScannersResults = new StringBuilder();
SortedSet<String> allKnownFlags = new TreeSet<String>();
SortedSet<String> allKnownVotes = new TreeSet<String>();
SortedMap<String, String> consensusAssignedFlags =
new TreeMap<String, String>();
SortedMap<String, SortedSet<String>> votesAssignedFlags =
new TreeMap<String, SortedSet<String>>();
SortedMap<String, String> votesKnownFlags =
new TreeMap<String, String>();
SortedMap<String, SortedMap<String, Integer>> flagsAgree =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsLost =
new TreeMap<String, SortedMap<String, Integer>>();
SortedMap<String, SortedMap<String, Integer>> flagsMissing =
new TreeMap<String, SortedMap<String, Integer>>();
/* Read consensus and parse all information that we want to compare to
* votes. */
String consensusConsensusMethod = null, consensusKnownFlags = null,
consensusClientVersions = null, consensusServerVersions = null,
consensusParams = null, rLineTemp = null;
int consensusTotalRelays = 0, consensusRunningRelays = 0;
Scanner s = new Scanner(new String(this.mostRecentConsensus));
while (s.hasNextLine()) {
String line = s.nextLine();
if (line.startsWith("consensus-method ")) {
consensusConsensusMethod = line;
} else if (line.startsWith("client-versions ")) {
consensusClientVersions = line;
} else if (line.startsWith("server-versions ")) {
consensusServerVersions = line;
} else if (line.startsWith("known-flags ")) {
consensusKnownFlags = line;
} else if (line.startsWith("params ")) {
consensusParams = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
consensusTotalRelays++;
if (line.contains(" Running")) {
consensusRunningRelays++;
}
consensusAssignedFlags.put(Hex.encodeHexString(
Base64.decodeBase64(rLineTemp.split(" ")[2] + "=")).
toUpperCase() + " " + rLineTemp.split(" ")[1], line);
}
}
s.close();
/* Read votes and parse all information to compare with the
* consensus. */
for (byte[] voteBytes : this.mostRecentVotes.values()) {
String voteConsensusMethods = null, voteKnownFlags = null,
voteClientVersions = null, voteServerVersions = null,
voteParams = null, dirSource = null, voteDirKeyExpires = null;
int voteTotalRelays = 0, voteRunningRelays = 0,
voteContainsBandwidthWeights = 0;
s = new Scanner(new String(voteBytes));
while (s.hasNextLine()) {
String line = s.nextLine();
if (line.startsWith("consensus-methods ")) {
voteConsensusMethods = line;
} else if (line.startsWith("client-versions ")) {
voteClientVersions = line;
} else if (line.startsWith("server-versions ")) {
voteServerVersions = line;
} else if (line.startsWith("known-flags ")) {
voteKnownFlags = line;
} else if (line.startsWith("params ")) {
voteParams = line;
} else if (line.startsWith("dir-source ")) {
dirSource = line.split(" ")[1];
allKnownVotes.add(dirSource);
} else if (line.startsWith("dir-key-expires ")) {
voteDirKeyExpires = line;
} else if (line.startsWith("r ")) {
rLineTemp = line;
} else if (line.startsWith("s ")) {
voteTotalRelays++;
if (line.contains(" Running")) {
voteRunningRelays++;
}
String relayKey = Hex.encodeHexString(Base64.decodeBase64(
rLineTemp.split(" ")[2] + "=")).toUpperCase() + " "
+ rLineTemp.split(" ")[1];
SortedSet<String> sLines = null;
if (votesAssignedFlags.containsKey(relayKey)) {
sLines = votesAssignedFlags.get(relayKey);
} else {
sLines = new TreeSet<String>();
votesAssignedFlags.put(relayKey, sLines);
}
sLines.add(dirSource + " " + line);
} else if (line.startsWith("w ")) {
if (line.contains(" Measured")) {
voteContainsBandwidthWeights++;
}
}
}
s.close();
/* Write known flags. */
knownFlagsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteKnownFlags + "</td>\n"
+ " </tr>\n");
votesKnownFlags.put(dirSource, voteKnownFlags);
for (String flag : voteKnownFlags.substring(
"known-flags ".length()).split(" ")) {
allKnownFlags.add(flag);
}
/* Write number of relays voted about. */
numRelaysVotesResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteTotalRelays + " total</td>\n"
+ " <td>" + voteRunningRelays + " Running</td>\n"
+ " </tr>\n");
/* Write supported consensus methods. */
if (!voteConsensusMethods.contains(consensusConsensusMethod.
split(" ")[1])) {
consensusMethodsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteConsensusMethods + "</font></td>\n"
+ " </tr>\n");
} else {
consensusMethodsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteConsensusMethods + "</td>\n"
+ " </tr>\n");
}
/* Write recommended versions. */
if (voteClientVersions == null) {
/* Not a versioning authority. */
} else if (!voteClientVersions.equals(consensusClientVersions)) {
versionsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteClientVersions + "</font></td>\n"
+ " </tr>\n");
} else {
versionsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteClientVersions + "</td>\n"
+ " </tr>\n");
}
if (voteServerVersions == null) {
/* Not a versioning authority. */
} else if (!voteServerVersions.equals(consensusServerVersions)) {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td><font color=\"red\">"
+ voteServerVersions + "</font></td>\n"
+ " </tr>\n");
} else {
versionsResults.append(" <tr>\n"
+ " <td/>\n"
+ " <td>" + voteServerVersions + "</td>\n"
+ " </tr>\n");
}
/* Write consensus parameters. */
if (voteParams == null) {
/* Authority doesn't set consensus parameters. */
} else if (!voteParams.equals(consensusParams)) {
paramsResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteParams + "</font></td>\n"
+ " </tr>\n");
} else {
paramsResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteParams + "</td>\n"
+ " </tr>\n");
}
/* Write authority key expiration date. */
if (voteDirKeyExpires != null) {
boolean expiresIn14Days = false;
try {
expiresIn14Days = (System.currentTimeMillis()
+ 14L * 24L * 60L * 60L * 1000L >
dateTimeFormat.parse(voteDirKeyExpires.substring(
"dir-key-expires ".length())).getTime());
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (expiresIn14Days) {
authorityKeysResults.append(" <tr>\n"
+ " <td><font color=\"red\">" + dirSource
+ "</font></td>\n"
+ " <td><font color=\"red\">"
+ voteDirKeyExpires + "</font></td>\n"
+ " </tr>\n");
} else {
authorityKeysResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteDirKeyExpires + "</td>\n"
+ " </tr>\n");
}
}
/* Write results for bandwidth scanner status. */
if (voteContainsBandwidthWeights > 0) {
bandwidthScannersResults.append(" <tr>\n"
+ " <td>" + dirSource + "</td>\n"
+ " <td>" + voteContainsBandwidthWeights
+ " Measured values in w lines<td/>\n"
+ " </tr>\n");
}
}
try {
/* Keep the past two consensus health statuses. */
File file0 = new File("website/consensus-health.html");
File file1 = new File("website/consensus-health-1.html");
File file2 = new File("website/consensus-health-2.html");
if (file2.exists()) {
file2.delete();
}
if (file1.exists()) {
file1.renameTo(file2);
}
if (file0.exists()) {
file0.renameTo(file1);
}
/* Start writing web page. */
BufferedWriter bw = new BufferedWriter(
new FileWriter("website/consensus-health.html"));
bw.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>Tor Metrics Portal: Consensus health</title>\n"
+ " <meta http-equiv=Content-Type content=\"text/html; "
+ "charset=iso-8859-1\">\n"
+ " <link href=\"http://www.torproject.org/stylesheet-"
+ "ltr.css\" type=text/css rel=stylesheet>\n"
+ " <link href=\"http://www.torproject.org/favicon.ico\""
+ " type=image/x-icon rel=\"shortcut icon\">\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"center\">\n"
+ " <table class=\"banner\" border=\"0\" "
+ "cellpadding=\"0\" cellspacing=\"0\" summary=\"\">\n"
+ " <tr>\n"
+ " <td class=\"banner-left\"><a href=\"https://"
+ "www.torproject.org/\"><img src=\"http://www.torproject"
+ ".org/images/top-left.png\" alt=\"Click to go to home "
+ "page\" width=\"193\" height=\"79\"></a></td>\n"
+ " <td class=\"banner-middle\">\n"
+ " <a href=\"/\">Home</a>\n"
+ " <a href=\"graphs.html\">Graphs</a>\n"
+ " <a href=\"reports.html\">Reports</a>\n"
+ " <a href=\"papers.html\">Papers</a>\n"
+ " <a href=\"data.html\">Data</a>\n"
+ " <a href=\"tools.html\">Tools</a>\n"
+ " </td>\n"
+ " <td class=\"banner-right\"></td>\n"
+ " </tr>\n"
+ " </table>\n"
+ " <div class=\"main-column\">\n"
+ " <h2>Tor Metrics Portal: Consensus Health</h2>\n"
+ " <br/>\n"
+ " <p>This page shows statistics about the current "
+ "consensus and votes to facilitate debugging of the "
+ "directory consensus process.</p>\n");
/* Write valid-after time. */
bw.write(" <br/>\n"
+ " <h3>Valid-after time</h3>\n"
+ " <br/>\n"
+ " <p>Consensus was published ");
boolean consensusIsStale = false;
try {
consensusIsStale = System.currentTimeMillis()
- 3L * 60L * 60L * 1000L >
dateTimeFormat.parse(this.mostRecentValidAfterTime).getTime();
} catch (ParseException e) {
/* Can't parse the timestamp? Whatever. */
}
if (consensusIsStale) {
bw.write("<font color=\"red\">" + this.mostRecentValidAfterTime
+ "</font>");
} else {
bw.write(this.mostRecentValidAfterTime);
}
bw.write(". <i>Note that it takes "
+ "15 to 30 minutes for the metrics portal to learn about "
+ "new consensus and votes and process them.</i></p>\n");
/* Write known flags. */
bw.write(" <br/>\n"
+ " <h3>Known flags</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (knownFlagsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(knownFlagsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusKnownFlags + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write number of relays voted about. */
bw.write(" <br/>\n"
+ " <h3>Number of relays voted about</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"320\">\n"
+ " <col width=\"320\">\n"
+ " </colgroup>\n");
if (numRelaysVotesResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/><td/></tr>\n");
} else {
bw.write(numRelaysVotesResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusTotalRelays + " total</font></td>\n"
+ " <td><font color=\"blue\">"
+ consensusRunningRelays + " Running</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus methods. */
bw.write(" <br/>\n"
+ " <h3>Consensus methods</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (consensusMethodsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(consensusMethodsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusConsensusMethod + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write recommended versions. */
bw.write(" <br/>\n"
+ " <h3>Recommended versions</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (versionsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(versionsResults.toString());
}
bw.write(" <tr>\n"
+ " <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusClientVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" <td/>\n"
+ " <td><font color=\"blue\">"
+ consensusServerVersions + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write consensus parameters. */
bw.write(" <br/>\n"
+ " <h3>Consensus parameters</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (paramsResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(paramsResults.toString());
}
bw.write(" <td><font color=\"blue\">consensus</font>"
+ "</td>\n"
+ " <td><font color=\"blue\">"
+ consensusParams + "</font></td>\n"
+ " </tr>\n");
bw.write(" </table>\n");
/* Write authority keys. */
bw.write(" <br/>\n"
+ " <h3>Authority keys</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (authorityKeysResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(authorityKeysResults.toString());
}
bw.write(" </table>\n"
+ " <br/>\n"
+ " <p><i>Note that expiration dates of legacy keys are "
+ "not included in votes and therefore not listed here!</i>"
+ "</p>\n");
/* Write bandwidth scanner status. */
bw.write(" <br/>\n"
+ " <h3>Bandwidth scanner status</h3>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"640\">\n"
+ " </colgroup>\n");
if (bandwidthScannersResults.length() < 1) {
bw.write(" <tr><td>(No votes.)</td><td/></tr>\n");
} else {
bw.write(bandwidthScannersResults.toString());
}
bw.write(" </table>\n");
/* Write (huge) table with all flags. */
bw.write(" <br/>\n"
+ " <h3>Relay flags</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of flags written in the table is "
+ "as follows:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " <li><b><font color=\"blue\">In "
+ "consensus:</font></b> Flag in consensus</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <p>See also the summary below the table.</p>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"120\">\n"
+ " <col width=\"80\">\n");
for (int i = 0; i < allKnownVotes.size(); i++) {
bw.write(" <col width=\""
+ (640 / allKnownVotes.size()) + "\">\n");
}
bw.write(" </colgroup>\n");
int linesWritten = 0;
for (Map.Entry<String, SortedSet<String>> e :
votesAssignedFlags.entrySet()) {
if (linesWritten++ % 10 == 0) {
bw.write(" <tr><td/><td/>\n");
for (String dir : allKnownVotes) {
String shortDirName = dir.length() > 6 ?
dir.substring(0, 5) + "." : dir;
bw.write("<td><br/><b>" + shortDirName + "</b></td>");
}
bw.write("<td><br/><b>consensus</b></td></tr>\n");
}
String relayKey = e.getKey();
SortedSet<String> votes = e.getValue();
String fingerprint = relayKey.split(" ")[0].substring(0, 8);
String nickname = relayKey.split(" ")[1];
bw.write(" <tr>\n"
+ " <td>" + fingerprint + "</td>\n"
+ " <td>" + nickname + "</td>\n");
SortedSet<String> relevantFlags = new TreeSet<String>();
for (String vote : votes) {
String[] parts = vote.split(" ");
for (int j = 2; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
String consensusFlags = null;
if (consensusAssignedFlags.containsKey(relayKey)) {
consensusFlags = consensusAssignedFlags.get(relayKey);
String[] parts = consensusFlags.split(" ");
for (int j = 1; j < parts.length; j++) {
relevantFlags.add(parts[j]);
}
}
for (String dir : allKnownVotes) {
String flags = null;
for (String vote : votes) {
if (vote.startsWith(dir)) {
flags = vote;
break;
}
}
if (flags != null) {
votes.remove(flags);
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
SortedMap<String, SortedMap<String, Integer>> sums = null;
if (flags.contains(" " + flag)) {
if (consensusFlags == null ||
consensusFlags.contains(" " + flag)) {
bw.write(flag);
sums = flagsAgree;
} else {
bw.write("<font color=\"red\">" + flag + "</font>");
sums = flagsLost;
}
} else if (consensusFlags != null &&
votesKnownFlags.get(dir).contains(" " + flag) &&
consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"gray\"><s>" + flag
+ "</s></font>");
sums = flagsMissing;
}
if (sums != null) {
SortedMap<String, Integer> sum = null;
if (sums.containsKey(dir)) {
sum = sums.get(dir);
} else {
sum = new TreeMap<String, Integer>();
sums.put(dir, sum);
}
sum.put(flag, sum.containsKey(flag) ?
sum.get(flag) + 1 : 1);
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
}
if (consensusFlags != null) {
bw.write(" <td>");
int flagsWritten = 0;
for (String flag : relevantFlags) {
bw.write(flagsWritten++ > 0 ? "<br/>" : "");
if (consensusFlags.contains(" " + flag)) {
bw.write("<font color=\"blue\">" + flag + "</font>");
}
}
bw.write("</td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
bw.write(" </table>\n");
/* Write summary of overlap between votes and consensus. */
bw.write(" <br/>\n"
+ " <h3>Overlap between votes and consensus</h3>\n"
+ " <br/>\n"
+ " <p>The semantics of columns is similar to the "
+ "table above:</p>\n"
+ " <ul>\n"
+ " <li><b>In vote and consensus:</b> Flag in vote "
+ "matches flag in consensus, or relay is not listed in "
+ "consensus (because it doesn't have the Running "
+ "flag)</li>\n"
+ " <li><b><font color=\"red\">Only in "
+ "vote:</font></b> Flag in vote, but missing in the "
+ "consensus, because there was no majority for the flag or "
+ "the flag was invalidated (e.g., Named gets invalidated by "
+ "Unnamed)</li>\n"
+ " <li><b><font color=\"gray\"><s>Only in "
+ "consensus:</s></font></b> Flag in consensus, but missing "
+ "in a vote of a directory authority voting on this "
+ "flag</li>\n"
+ " </ul>\n"
+ " <br/>\n"
+ " <table border=\"0\" cellpadding=\"4\" "
+ "cellspacing=\"0\" summary=\"\">\n"
+ " <colgroup>\n"
+ " <col width=\"160\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " <col width=\"210\">\n"
+ " </colgroup>\n");
bw.write(" <tr><td/><td><b>Only in vote</b></td>"
+ "<td><b>In vote and consensus</b></td>"
+ "<td><b>Only in consensus</b></td>\n");
for (String dir : allKnownVotes) {
boolean firstFlagWritten = false;
String[] flags = votesKnownFlags.get(dir).substring(
"known-flags ".length()).split(" ");
for (String flag : flags) {
bw.write(" <tr>\n");
if (firstFlagWritten) {
bw.write(" <td/>\n");
} else {
bw.write(" <td>" + dir + "</td>\n");
firstFlagWritten = true;
}
if (flagsLost.containsKey(dir) &&
flagsLost.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"red\"> "
+ flagsLost.get(dir).get(flag) + " " + flag
+ "</font></td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsAgree.containsKey(dir) &&
flagsAgree.get(dir).containsKey(flag)) {
bw.write(" <td>" + flagsAgree.get(dir).get(flag)
+ " " + flag + "</td>\n");
} else {
bw.write(" <td/>\n");
}
if (flagsMissing.containsKey(dir) &&
flagsMissing.get(dir).containsKey(flag)) {
bw.write(" <td><font color=\"gray\"><s>"
+ flagsMissing.get(dir).get(flag) + " " + flag
+ "</s></font></td>\n");
} else {
bw.write(" <td/>\n");
}
bw.write(" </tr>\n");
}
}
bw.write(" </table>\n");
/* Finish writing. */
bw.write(" </div>\n"
+ " </div>\n"
+ " <div class=\"bottom\" id=\"bottom\">\n"
+ " <p>\"Tor\" and the \"Onion Logo\" are <a "
+ "href=\"https://www.torproject.org/trademark-faq.html"
+ ".en\">"
+ "registered trademarks</a> of The Tor Project, "
+ "Inc.</p>\n"
+ " </div>\n"
+ " </body>\n"
+ "</html>");
bw.close();
} catch (IOException e) {
}
}
|
diff --git a/src/main/java/com/onarandombox/multiverseinventories/config/SimpleMVIConfig.java b/src/main/java/com/onarandombox/multiverseinventories/config/SimpleMVIConfig.java
index 933c92e..7739e6a 100644
--- a/src/main/java/com/onarandombox/multiverseinventories/config/SimpleMVIConfig.java
+++ b/src/main/java/com/onarandombox/multiverseinventories/config/SimpleMVIConfig.java
@@ -1,217 +1,222 @@
package com.onarandombox.multiverseinventories.config;
import com.onarandombox.multiverseinventories.group.SimpleWorldGroup;
import com.onarandombox.multiverseinventories.group.WorldGroup;
import com.onarandombox.multiverseinventories.util.DeserializationException;
import com.onarandombox.multiverseinventories.util.MVILog;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Implementation of MVIConfig.
*/
public class SimpleMVIConfig implements MVIConfig {
/**
* Enum for easily keeping track of config paths, defaults and comments.
*/
public enum Path {
/**
* Locale name config path, default and comments.
*/
LANGUAGE_FILE_NAME("settings.locale", "en", "# This is the locale you wish to use."),
/**
* Debug Mode config path, default and comments.
*/
DEBUG_MODE("settings.debug_mode.enable", false, "# Enables debug mode."),
/**
* First Run flag config path, default and comments.
*/
FIRST_RUN("first_run", true, "# If this is true it will generate world groups for you based on MV worlds."),
/**
* Groups section path and comments. No simple default for this.
*/
GROUPS("groups", null, "#This is where you configure your world groups");
private String path;
private Object def;
private String[] comments;
Path(String path, Object def, String... comments) {
this.path = path;
this.def = def;
this.comments = comments;
}
/**
* Retrieves the path for a config option.
*
* @return The path for a config option.
*/
private String getPath() {
return this.path;
}
/**
* Retrieves the default value for a config path.
*
* @return The default value for a config path.
*/
private Object getDefault() {
return this.def;
}
/**
* Retrieves the comment for a config path.
*
* @return The comments for a config path.
*/
private String[] getComments() {
if (this.comments != null) {
return this.comments;
}
String[] emptyComments = new String[1];
emptyComments[0] = "";
return emptyComments;
}
}
private CommentedConfiguration config;
public SimpleMVIConfig(JavaPlugin plugin) throws Exception {
// Make the data folders
plugin.getDataFolder().mkdirs();
// Check if the config file exists. If not, create it.
File configFile = new File(plugin.getDataFolder(), "config.yml");
if (!configFile.exists()) {
configFile.createNewFile();
}
// Load the configuration file into memory
config = new CommentedConfiguration(configFile);
config.load();
// Sets defaults config values
this.setDefaults();
// Saves the configuration from memory to file
config.save();
}
/**
* Loads default settings for any missing config values.
*/
private void setDefaults() {
for (SimpleMVIConfig.Path path : SimpleMVIConfig.Path.values()) {
config.addComment(path.getPath(), path.getComments());
if (config.getString(path.getPath()) == null) {
config.set(path.getPath(), path.getDefault());
}
}
}
private Boolean getBoolean(Path path) {
return this.getConfig().getBoolean(path.getPath(), (Boolean) path.getDefault());
}
private Integer getInt(Path path) {
return this.getConfig().getInt(path.getPath(), (Integer) path.getDefault());
}
private String getString(Path path) {
return this.getConfig().getString(path.getPath(), (String) path.getDefault());
}
/**
* {@inheritDoc}
*/
@Override
public CommentedConfiguration getConfig() {
return this.config;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDebugging() {
return this.getBoolean(Path.DEBUG_MODE);
}
/**
* {@inheritDoc}
*/
@Override
public String getLocale() {
return this.getString(Path.LANGUAGE_FILE_NAME);
}
/**
* {@inheritDoc}
*/
@Override
public List<WorldGroup> getWorldGroups() {
- if (!this.getConfig().contains("groups")) {
+ ConfigurationSection groupsSection = this.getConfig().getConfigurationSection("groups");
+ if (groupsSection == null) {
return null;
}
- ConfigurationSection groupsSection = this.getConfig().getConfigurationSection("groups");
Set<String> groupNames = groupsSection.getKeys(false);
List<WorldGroup> worldGroups = new ArrayList<WorldGroup>(groupNames.size());
for (String groupName : groupNames) {
WorldGroup worldGroup;
try {
- worldGroup = new SimpleWorldGroup(groupName,
- groupsSection.getConfigurationSection(groupName));
+ ConfigurationSection groupSection =
+ this.getConfig().getConfigurationSection("groups." + groupName);
+ if (groupSection == null) {
+ MVILog.warning("Group: '" + groupName + "' is not formatted correctly!");
+ continue;
+ }
+ worldGroup = new SimpleWorldGroup(groupName, groupSection);
} catch (DeserializationException e) {
MVILog.warning("Unable to load world group: " + groupName);
MVILog.warning("Reason: " + e.getMessage());
continue;
}
worldGroups.add(worldGroup);
}
return worldGroups;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isFirstRun() {
return this.getBoolean(Path.FIRST_RUN);
}
/**
* {@inheritDoc}
*/
@Override
public void setFirstRun(boolean firstRun) {
this.getConfig().set(Path.FIRST_RUN.getPath(), firstRun);
}
/**
* {@inheritDoc}
*/
@Override
public void updateWorldGroup(WorldGroup worldGroup) {
ConfigurationSection groupSection = this.getConfig().getConfigurationSection("groups." + worldGroup.getName());
if (groupSection == null) {
groupSection = this.getConfig().createSection("groups." + worldGroup.getName());
}
worldGroup.serialize(groupSection);
}
/**
* {@inheritDoc}
*/
@Override
public void save() {
this.getConfig().save();
}
}
| false | true | public List<WorldGroup> getWorldGroups() {
if (!this.getConfig().contains("groups")) {
return null;
}
ConfigurationSection groupsSection = this.getConfig().getConfigurationSection("groups");
Set<String> groupNames = groupsSection.getKeys(false);
List<WorldGroup> worldGroups = new ArrayList<WorldGroup>(groupNames.size());
for (String groupName : groupNames) {
WorldGroup worldGroup;
try {
worldGroup = new SimpleWorldGroup(groupName,
groupsSection.getConfigurationSection(groupName));
} catch (DeserializationException e) {
MVILog.warning("Unable to load world group: " + groupName);
MVILog.warning("Reason: " + e.getMessage());
continue;
}
worldGroups.add(worldGroup);
}
return worldGroups;
}
| public List<WorldGroup> getWorldGroups() {
ConfigurationSection groupsSection = this.getConfig().getConfigurationSection("groups");
if (groupsSection == null) {
return null;
}
Set<String> groupNames = groupsSection.getKeys(false);
List<WorldGroup> worldGroups = new ArrayList<WorldGroup>(groupNames.size());
for (String groupName : groupNames) {
WorldGroup worldGroup;
try {
ConfigurationSection groupSection =
this.getConfig().getConfigurationSection("groups." + groupName);
if (groupSection == null) {
MVILog.warning("Group: '" + groupName + "' is not formatted correctly!");
continue;
}
worldGroup = new SimpleWorldGroup(groupName, groupSection);
} catch (DeserializationException e) {
MVILog.warning("Unable to load world group: " + groupName);
MVILog.warning("Reason: " + e.getMessage());
continue;
}
worldGroups.add(worldGroup);
}
return worldGroups;
}
|
diff --git a/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/endpoints/OAuthEndpoint.java b/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/endpoints/OAuthEndpoint.java
index 060b1206a..c4879cba7 100644
--- a/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/endpoints/OAuthEndpoint.java
+++ b/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/endpoints/OAuthEndpoint.java
@@ -1,289 +1,290 @@
/*
* � Copyright IBM Corp. 2012
*
* 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.ibm.sbt.services.endpoints;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
import com.ibm.commons.runtime.Context;
import com.ibm.commons.runtime.RuntimeConstants;
import com.ibm.commons.runtime.util.UrlUtil;
import com.ibm.commons.util.PathUtil;
import com.ibm.commons.util.StringUtil;
import com.ibm.sbt.core.configuration.Configuration;
import com.ibm.sbt.security.authentication.oauth.OAuthException;
import com.ibm.sbt.security.authentication.oauth.consumer.AccessToken;
import com.ibm.sbt.security.authentication.oauth.consumer.HMACOAuth1Handler;
import com.ibm.sbt.security.authentication.oauth.consumer.OAProvider;
import com.ibm.sbt.security.authentication.oauth.consumer.OAuthHandler;
import com.ibm.sbt.security.authentication.oauth.consumer.servlet.OAClientAuthentication;
import com.ibm.sbt.services.client.ClientServicesException;
import com.ibm.sbt.services.endpoints.js.JSReference;
import com.ibm.sbt.util.SBTException;
/**
* Bean that provides authentication via OAuth.
* <p>
* </p>
*
* @author Philippe Riand
*/
public class OAuthEndpoint extends AbstractEndpoint {
protected final OAProvider oaProvider = new OAProvider();
// for logging
private static final String sourceClass = OAuthEndpoint.class.getName();
private static final Logger logger = Logger.getLogger(sourceClass);
public OAuthEndpoint() {
}
@Override
public void checkValid() throws SBTException {
super.checkValid();
if (StringUtil.isEmpty(oaProvider.getConsumerKey())) {
throw new SBTException(null, "The Endpoint consumer key is empty, class {0}", getClass());
}
if (StringUtil.isEmpty(oaProvider.getConsumerSecret())) {
throw new SBTException(null, "The Endpoint consumer secret is empty, class {0}", getClass());
}
if (StringUtil.isEmpty(oaProvider.getAuthorizationURL())) {
throw new SBTException(null, "The Endpoint authorization URL is empty, class {0}", getClass());
}
if (StringUtil.isEmpty(oaProvider.getRequestTokenURL())) {
throw new SBTException(null, "The Endpoint request token URL is empty, class {0}", getClass());
}
if (StringUtil.isEmpty(oaProvider.getAccessTokenURL())) {
throw new SBTException(null, "The Endpoint access token URL is empty, class {0}", getClass());
}
}
public OAProvider getOAuthProvider() {
return oaProvider;
}
@Override
public void setUrl(String url) {
super.setUrl(url);
// Make the URL the service name if not already set
if (StringUtil.isEmpty(oaProvider.getServiceName())) {
oaProvider.setServiceName(url);
}
}
public String getConsumerKey() {
return oaProvider.getConsumerKey();
}
public void setConsumerKey(String consumerKey) {
oaProvider.setConsumerKey(consumerKey);
}
public String getConsumerSecret() {
return oaProvider.getConsumerSecret();
}
public void setConsumerSecret(String consumerSecret) {
oaProvider.setConsumerSecret(consumerSecret);
}
@Override
public String getCredentialStore() {
return oaProvider.getCredentialStore();
}
@Override
public void setCredentialStore(String credentialStore) {
oaProvider.setCredentialStore(credentialStore);
}
public String getAppId() {
return oaProvider.getAppId();
}
public void setAppId(String appId) {
oaProvider.setAppId(appId);
}
public String getServiceName() {
return oaProvider.getServiceName();
}
public void setServiceName(String serviceName) {
oaProvider.setServiceName(serviceName);
}
public String getRequestTokenURL() {
return oaProvider.getRequestTokenURL();
}
public void setRequestTokenURL(String requestTokenURL) {
oaProvider.setRequestTokenURL(requestTokenURL);
}
public String getAuthorizationURL() {
return oaProvider.getAuthorizationURL();
}
public void setAuthorizationURL(String authorizationURL) {
oaProvider.setAuthorizationURL(authorizationURL);
}
public String getAccessTokenURL() {
return oaProvider.getAccessTokenURL();
}
public void setAccessTokenURL(String accessTokenURL) {
oaProvider.setAccessTokenURL(accessTokenURL);
}
public String getSignatureMethod() {
return oaProvider.getSignatureMethod();
}
public void setSignatureMethod(String signatureMethod) {
oaProvider.setSignatureMethod(signatureMethod);
}
@Override
public String getAuthType() {
return "oauth1.0a";
}
@Override
public boolean isForceTrustSSLCertificate() {
return oaProvider.getForceTrustSSLCertificate();
}
@Override
public void setForceTrustSSLCertificate(boolean forceTrustSSLCertificate) {
oaProvider.setForceTrustSSLCertificate(forceTrustSSLCertificate);
}
public String getApplicationAccessToken() {
return oaProvider.applicationAccessToken;
}
public void setApplicationAccessToken(String applicationAccessToken) {
oaProvider.applicationAccessToken = applicationAccessToken;
}
@Override
public JSReference getAuthenticator(String endpointName, String sbtUrl) {
Context ctx = Context.get();
JSReference reference = new JSReference("sbt/authenticator/OAuth");
StringBuilder b = new StringBuilder();
RuntimeConstants.get().appendBaseProxyUrl(b, ctx);
b.append("/");
b.append(OAClientAuthentication.URL_PATH);
b.append('/');
b.append(endpointName);
String url = b.toString();
reference.getProperties().put("url", url);
reference.getProperties().put("loginUi", ctx.getProperty("loginUi"));
return reference;
}
@Override
public boolean isAuthenticated() throws ClientServicesException {
try {
return oaProvider.acquireToken() != null;
} catch (OAuthException ex) {
throw new ClientServicesException(ex);
}
}
@Override
public void authenticate(boolean force) throws ClientServicesException {
try {
oaProvider.acquireToken(true, force);
} catch (OAuthException ex) {
throw new ClientServicesException(ex);
}
}
@Override
public void logout() throws OAuthException {
oaProvider.deleteToken();
}
@Override
public void initialize(DefaultHttpClient httpClient) throws ClientServicesException {
try {
AccessToken token = oaProvider.acquireToken(false);
OAuthHandler oaHandler = oaProvider.getOauthHandler();
if ((token != null) && (oaHandler != null)) {
HttpRequestInterceptor oauthInterceptor = new OAuthInterceptor(token, super.getUrl(),oaHandler);
httpClient.addRequestInterceptor(oauthInterceptor, 0);
}
} catch (OAuthException ex) {
throw new ClientServicesException(ex);
}
}
private static class OAuthInterceptor implements HttpRequestInterceptor {
private final AccessToken token;
private final String baseUrl;
private final OAuthHandler oaHandler;
public OAuthInterceptor(AccessToken token, String baseUrl, OAuthHandler oaHandler) {
this.token = token;
this.baseUrl = baseUrl;
this.oaHandler = oaHandler;
}
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
String authorizationheader = null;
if (oaHandler != null) {
if (oaHandler.getClass().equals(HMACOAuth1Handler.class)) {
String requestUri = request.getRequestLine().getUri().toString();
// Using UrlUtil's getParamsMap for creating the ParamsMap
// from the query String Request Uri.
Map<String, String> mapOfParams = UrlUtil.getParamsMap(requestUri);
try {
- requestUri = requestUri.substring(0, requestUri.indexOf("?"));
+ if(StringUtil.isNotEmpty(requestUri)&& requestUri.indexOf("?")!=-1)
+ requestUri = requestUri.substring(0, requestUri.indexOf("?"));
requestUri = PathUtil.concat(baseUrl, requestUri, '/');
// creating authorization header
authorizationheader = ((HMACOAuth1Handler) oaHandler).createAuthorizationHeader(requestUri,
mapOfParams);
} catch (OAuthException e) {
throw new HttpException(
"OAuthException thrown while creating Authorization header in OAuthInterceptor", e);
}
} else {
authorizationheader = oaHandler.createAuthorizationHeader();
}
} else {
logger.log(Level.SEVERE, "Error retrieving OAuth Handler. OAuth Handler is null");
throw new HttpException("Error retrieving OAuth Handler. OAuth Handler is null");
}
request.addHeader("Authorization", authorizationheader);
}
}
}
| true | true | public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
String authorizationheader = null;
if (oaHandler != null) {
if (oaHandler.getClass().equals(HMACOAuth1Handler.class)) {
String requestUri = request.getRequestLine().getUri().toString();
// Using UrlUtil's getParamsMap for creating the ParamsMap
// from the query String Request Uri.
Map<String, String> mapOfParams = UrlUtil.getParamsMap(requestUri);
try {
requestUri = requestUri.substring(0, requestUri.indexOf("?"));
requestUri = PathUtil.concat(baseUrl, requestUri, '/');
// creating authorization header
authorizationheader = ((HMACOAuth1Handler) oaHandler).createAuthorizationHeader(requestUri,
mapOfParams);
} catch (OAuthException e) {
throw new HttpException(
"OAuthException thrown while creating Authorization header in OAuthInterceptor", e);
}
} else {
authorizationheader = oaHandler.createAuthorizationHeader();
}
} else {
logger.log(Level.SEVERE, "Error retrieving OAuth Handler. OAuth Handler is null");
throw new HttpException("Error retrieving OAuth Handler. OAuth Handler is null");
}
request.addHeader("Authorization", authorizationheader);
}
| public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
String authorizationheader = null;
if (oaHandler != null) {
if (oaHandler.getClass().equals(HMACOAuth1Handler.class)) {
String requestUri = request.getRequestLine().getUri().toString();
// Using UrlUtil's getParamsMap for creating the ParamsMap
// from the query String Request Uri.
Map<String, String> mapOfParams = UrlUtil.getParamsMap(requestUri);
try {
if(StringUtil.isNotEmpty(requestUri)&& requestUri.indexOf("?")!=-1)
requestUri = requestUri.substring(0, requestUri.indexOf("?"));
requestUri = PathUtil.concat(baseUrl, requestUri, '/');
// creating authorization header
authorizationheader = ((HMACOAuth1Handler) oaHandler).createAuthorizationHeader(requestUri,
mapOfParams);
} catch (OAuthException e) {
throw new HttpException(
"OAuthException thrown while creating Authorization header in OAuthInterceptor", e);
}
} else {
authorizationheader = oaHandler.createAuthorizationHeader();
}
} else {
logger.log(Level.SEVERE, "Error retrieving OAuth Handler. OAuth Handler is null");
throw new HttpException("Error retrieving OAuth Handler. OAuth Handler is null");
}
request.addHeader("Authorization", authorizationheader);
}
|
diff --git a/src/com/fede/ActiveState.java b/src/com/fede/ActiveState.java
index d3eb4ef..d197636 100644
--- a/src/com/fede/ActiveState.java
+++ b/src/com/fede/ActiveState.java
@@ -1,164 +1,165 @@
/*
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.fede;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import com.fede.MessageException.InvalidCommandException;
import com.fede.Utilities.GeneralUtils;
import com.fede.Utilities.PrefUtils;
import java.util.Date;
public class ActiveState implements ServiceState {
@Override
public boolean getServiceState() {
return true;
}
private void notifyReply(HomeAloneService s, String number, String reply){
String message = String.format(s.getString(R.string.reply_notified_to), reply, number);
GeneralUtils.notifyEvent(s.getString(R.string.reply_notified), message, DroidContentProviderClient.EventType.REPLY, s);
}
public void sendReply(HomeAloneService s, String number) {
String reply = PrefUtils.getReply(s);
if(!reply.equals("") && !number.equals("unknown")){
notifyReply(s, number, reply);
GeneralUtils.sendSms(number, reply, s);
}
}
// Tells caller name from number
private String getCallerNameString(String number, HomeAloneService s){
try{
return GeneralUtils.getNameFromNumber(number, s);
}catch (NameNotFoundException e){
return "";
}
}
// Handle ringing state and store the number to forwards to sms / email later
@Override
public void handleIncomingCall(HomeAloneService s, Bundle b) {
String numberWithQuotes = b.getString(HomeAloneService.NUMBER);
DroidContentProviderClient.addCall(numberWithQuotes, new Date(), s);
}
private void notifyCall(String number, HomeAloneService s){
String callString = s.getString(R.string.call_from);
String msg = String.format(callString, getCallerNameString(number, s), number);
EventForwarder f = new EventForwarder(msg, DroidContentProviderClient.EventType.FORWARDED_CALL, s);
f.forward();
sendReply(s, number);
}
private void notifySkippedCall(String number, HomeAloneService s){
String callString = s.getString(R.string.call_from);
String msg = s.getString(R.string.skipped) + " " + String.format(callString, getCallerNameString(number, s), number);
GeneralUtils.notifyEvent(s.getString(R.string.skipped_call), msg, DroidContentProviderClient.EventType.FORWARDED_CALL , s);
}
@Override
public void handlePhoneIdle(HomeAloneService s){
// when idle I need to check if I have one or more pending calls. This should be done also
// in onidle of inactivestate
Cursor c = DroidContentProviderClient.getAllCall(s);
if (c.moveToFirst()) {
do{
String number = c.getString(DroidContentProvider.CALL_NUMBER_COLUMN_POSITION);
if(number == null){
number = "unknown number";
}
notifyCall(number, s);
} while (c.moveToNext());
}
c.close();
DroidContentProviderClient.removeAllCall(s);
}
private void handleSmsToNotify(HomeAloneService s, Bundle b, String body){
String number = b.getString(HomeAloneService.NUMBER);
String msg = String.format("Sms %s %s:%s", getCallerNameString(number, s),number, body);
EventForwarder f = new EventForwarder(msg, DroidContentProviderClient.EventType.FORWARDED_SMS, s);
f.forward();
sendReply(s, number);
}
private void handleCommandSms(HomeAloneService s, Bundle b, String body) {
String number = b.getString(HomeAloneService.NUMBER);
try{
CommandSms command = new CommandSms(b, body, number, s);
command.execute();
if(command.getStatus() == CommandSms.BoolCommand.DISABLED){
s.setState(new InactiveState());
}
}catch (InvalidCommandException e){
GeneralUtils.sendSms(number, e.getMessage(), s);
}
}
private boolean isDroidAloneMessage(String msg, Context c) {
return msg.startsWith(c.getString(R.string.message_header));
}
@Override
public void handleSms(HomeAloneService s, Bundle b) {
String body = b.getString(HomeAloneService.MESSAGE_BODY);
if(isDroidAloneMessage(body, s)){ // Do nothing to avoid loops
GeneralUtils.notifyEvent(s.getString(R.string.loop_message),
String.format(s.getString(R.string.loop_message_full), body), DroidContentProviderClient.EventType.FAILURE, s);
}else if(CommandSms.isCommandSms(body)){
handleCommandSms(s, b, body);
}else{
handleSmsToNotify(s, b, body);
}
}
@Override
public void handlePhoneOffHook(HomeAloneService s) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(s);
if(!PrefUtils.getBoolPreference(prefs, R.string.skip_handled_key, s))
return;
Cursor c = DroidContentProviderClient.getAllCall(s);
if (c.moveToFirst()) {
do{
String number = c.getString(DroidContentProvider.CALL_NUMBER_COLUMN_POSITION);
if(number == null){
number = "unknown number";
}
notifySkippedCall(number, s);
} while (c.moveToNext());
}
c.close();
+ DroidContentProviderClient.removeAllCall(s);
}
}
| true | true | public void handlePhoneOffHook(HomeAloneService s) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(s);
if(!PrefUtils.getBoolPreference(prefs, R.string.skip_handled_key, s))
return;
Cursor c = DroidContentProviderClient.getAllCall(s);
if (c.moveToFirst()) {
do{
String number = c.getString(DroidContentProvider.CALL_NUMBER_COLUMN_POSITION);
if(number == null){
number = "unknown number";
}
notifySkippedCall(number, s);
} while (c.moveToNext());
}
c.close();
}
| public void handlePhoneOffHook(HomeAloneService s) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(s);
if(!PrefUtils.getBoolPreference(prefs, R.string.skip_handled_key, s))
return;
Cursor c = DroidContentProviderClient.getAllCall(s);
if (c.moveToFirst()) {
do{
String number = c.getString(DroidContentProvider.CALL_NUMBER_COLUMN_POSITION);
if(number == null){
number = "unknown number";
}
notifySkippedCall(number, s);
} while (c.moveToNext());
}
c.close();
DroidContentProviderClient.removeAllCall(s);
}
|
diff --git a/PiiriAhi/src/main/java/ee/itcollege/team24/entities/BaseHistoryEntity.java b/PiiriAhi/src/main/java/ee/itcollege/team24/entities/BaseHistoryEntity.java
index a5ce235..cb58f6d 100644
--- a/PiiriAhi/src/main/java/ee/itcollege/team24/entities/BaseHistoryEntity.java
+++ b/PiiriAhi/src/main/java/ee/itcollege/team24/entities/BaseHistoryEntity.java
@@ -1,132 +1,132 @@
package ee.itcollege.team24.entities;
import java.util.Calendar;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
import javax.validation.constraints.Size;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* Base class for all entities that require modification history
*
*/
@MappedSuperclass
public class BaseHistoryEntity {
@Size(max = 150)
private String kommentaar;
@Size(max = 32)
private String avaja;
@DateTimeFormat(pattern="dd.MM.yyyy")
private Calendar avatud;
@Size(max = 32)
private String muutja;
@DateTimeFormat(pattern="dd.MM.yyyy")
private Calendar muudetud;
@Size(max = 32)
private String sulgeja;
@DateTimeFormat(pattern="dd.MM.yyyy")
private Calendar suletud;
@PrePersist
public void setCreated() {
String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
Calendar now = Calendar.getInstance();
setOpen(currentUser, now);
setModified(currentUser, now);
setTemporaryClosedDate();
}
@PreUpdate
public void setUpdated() {
String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
Calendar now = Calendar.getInstance();
setModified(currentUser, now);
}
@PreRemove
public void preventRemoval() {
throw new SecurityException("Removal of objects from DB is prohibited!");
}
private void setOpen(String user, Calendar date) {
this.avaja = user;
this.avatud = date;
}
private void setModified(String user, Calendar date) {
this.muutja = user;
this.muudetud = date;
}
private void setTemporaryClosedDate() {
Calendar tempDate = Calendar.getInstance();
tempDate.clear();
- tempDate.set(Calendar.YEAR, 9998);
- tempDate.set(Calendar.MONTH, 12);
+ tempDate.set(Calendar.YEAR, 9999);
+ tempDate.set(Calendar.MONTH, Calendar.DECEMBER);
tempDate.set(Calendar.DAY_OF_MONTH, 31);
this.suletud = tempDate;
}
public String getKommentaar() {
return kommentaar;
}
public void setKommentaar(String kommentaar) {
this.kommentaar = kommentaar;
}
public String getAvaja() {
return avaja;
}
public void setAvaja(String avaja) {
this.avaja = avaja;
}
public Calendar getAvatud() {
return avatud;
}
public void setAvatud(Calendar avatud) {
this.avatud = avatud;
}
public String getMuutja() {
return muutja;
}
public void setMuutja(String muutja) {
this.muutja = muutja;
}
public Calendar getMuudetud() {
return muudetud;
}
public void setMuudetud(Calendar muudetud) {
this.muudetud = muudetud;
}
public String getSulgeja() {
return sulgeja;
}
public void setSulgeja(String sulgeja) {
this.sulgeja = sulgeja;
}
public Calendar getSuletud() {
return suletud;
}
public void setSuletud(Calendar suletud) {
this.suletud = suletud;
}
}
| true | true | private void setTemporaryClosedDate() {
Calendar tempDate = Calendar.getInstance();
tempDate.clear();
tempDate.set(Calendar.YEAR, 9998);
tempDate.set(Calendar.MONTH, 12);
tempDate.set(Calendar.DAY_OF_MONTH, 31);
this.suletud = tempDate;
}
| private void setTemporaryClosedDate() {
Calendar tempDate = Calendar.getInstance();
tempDate.clear();
tempDate.set(Calendar.YEAR, 9999);
tempDate.set(Calendar.MONTH, Calendar.DECEMBER);
tempDate.set(Calendar.DAY_OF_MONTH, 31);
this.suletud = tempDate;
}
|
diff --git a/src/org/apache/xerces/util/DOMUtil.java b/src/org/apache/xerces/util/DOMUtil.java
index 9ccfa3ee7..79325fd06 100644
--- a/src/org/apache/xerces/util/DOMUtil.java
+++ b/src/org/apache/xerces/util/DOMUtil.java
@@ -1,899 +1,899 @@
/*
* 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.xerces.util;
import java.util.Hashtable;
import org.apache.xerces.dom.AttrImpl;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xerces.impl.xs.opti.ElementImpl;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.ls.LSException;
/**
* Some useful utility methods.
* This class was modified in Xerces2 with a view to abstracting as
* much as possible away from the representation of the underlying
* parsed structure (i.e., the DOM). This was done so that, if Xerces
* ever adopts an in-memory representation more efficient than the DOM
* (such as a DTM), we should easily be able to convert our schema
* parsing to utilize it.
*
* @version $Id$
*/
public class DOMUtil {
//
// Constructors
//
/** This class cannot be instantiated. */
protected DOMUtil() {}
//
// Public static methods
//
/**
* Copies the source tree into the specified place in a destination
* tree. The source node and its children are appended as children
* of the destination node.
* <p>
* <em>Note:</em> This is an iterative implementation.
*/
public static void copyInto(Node src, Node dest) throws DOMException {
// get node factory
Document factory = dest.getOwnerDocument();
boolean domimpl = factory instanceof DocumentImpl;
// placement variables
Node start = src;
Node parent = src;
Node place = src;
// traverse source tree
while (place != null) {
// copy this node
Node node = null;
int type = place.getNodeType();
switch (type) {
case Node.CDATA_SECTION_NODE: {
node = factory.createCDATASection(place.getNodeValue());
break;
}
case Node.COMMENT_NODE: {
node = factory.createComment(place.getNodeValue());
break;
}
case Node.ELEMENT_NODE: {
Element element = factory.createElement(place.getNodeName());
node = element;
NamedNodeMap attrs = place.getAttributes();
int attrCount = attrs.getLength();
for (int i = 0; i < attrCount; i++) {
Attr attr = (Attr)attrs.item(i);
String attrName = attr.getNodeName();
String attrValue = attr.getNodeValue();
element.setAttribute(attrName, attrValue);
if (domimpl && !attr.getSpecified()) {
((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
}
}
break;
}
case Node.ENTITY_REFERENCE_NODE: {
node = factory.createEntityReference(place.getNodeName());
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: {
node = factory.createProcessingInstruction(place.getNodeName(),
place.getNodeValue());
break;
}
case Node.TEXT_NODE: {
node = factory.createTextNode(place.getNodeValue());
break;
}
default: {
throw new IllegalArgumentException("can't copy node type, "+
type+" ("+
- node.getNodeName()+')');
+ place.getNodeName()+')');
}
}
dest.appendChild(node);
// iterate over children
if (place.hasChildNodes()) {
parent = place;
place = place.getFirstChild();
dest = node;
}
// advance
else {
place = place.getNextSibling();
while (place == null && parent != start) {
place = parent.getNextSibling();
parent = parent.getParentNode();
dest = dest.getParentNode();
}
}
}
} // copyInto(Node,Node)
/** Finds and returns the first child element node. */
public static Element getFirstChildElement(Node parent) {
// search for node
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
return (Element)child;
}
child = child.getNextSibling();
}
// not found
return null;
} // getFirstChildElement(Node):Element
/** Finds and returns the first visible child element node. */
public static Element getFirstVisibleChildElement(Node parent) {
// search for node
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE &&
!isHidden(child)) {
return (Element)child;
}
child = child.getNextSibling();
}
// not found
return null;
} // getFirstChildElement(Node):Element
/** Finds and returns the first visible child element node. */
public static Element getFirstVisibleChildElement(Node parent, Hashtable hiddenNodes) {
// search for node
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE &&
!isHidden(child, hiddenNodes)) {
return (Element)child;
}
child = child.getNextSibling();
}
// not found
return null;
} // getFirstChildElement(Node):Element
/** Finds and returns the last child element node.
* Overload previous method for non-Xerces node impl.
*/
public static Element getLastChildElement(Node parent) {
// search for node
Node child = parent.getLastChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
return (Element)child;
}
child = child.getPreviousSibling();
}
// not found
return null;
} // getLastChildElement(Node):Element
/** Finds and returns the last visible child element node. */
public static Element getLastVisibleChildElement(Node parent) {
// search for node
Node child = parent.getLastChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE &&
!isHidden(child)) {
return (Element)child;
}
child = child.getPreviousSibling();
}
// not found
return null;
} // getLastChildElement(Node):Element
/** Finds and returns the last visible child element node.
* Overload previous method for non-Xerces node impl
*/
public static Element getLastVisibleChildElement(Node parent, Hashtable hiddenNodes) {
// search for node
Node child = parent.getLastChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE &&
!isHidden(child, hiddenNodes)) {
return (Element)child;
}
child = child.getPreviousSibling();
}
// not found
return null;
} // getLastChildElement(Node):Element
/** Finds and returns the next sibling element node. */
public static Element getNextSiblingElement(Node node) {
// search for node
Node sibling = node.getNextSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE) {
return (Element)sibling;
}
sibling = sibling.getNextSibling();
}
// not found
return null;
} // getNextSiblingElement(Node):Element
// get next visible (un-hidden) node.
public static Element getNextVisibleSiblingElement(Node node) {
// search for node
Node sibling = node.getNextSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE &&
!isHidden(sibling)) {
return (Element)sibling;
}
sibling = sibling.getNextSibling();
}
// not found
return null;
} // getNextSiblingdElement(Node):Element
// get next visible (un-hidden) node, overload previous method for non Xerces node impl
public static Element getNextVisibleSiblingElement(Node node, Hashtable hiddenNodes) {
// search for node
Node sibling = node.getNextSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE &&
!isHidden(sibling, hiddenNodes)) {
return (Element)sibling;
}
sibling = sibling.getNextSibling();
}
// not found
return null;
} // getNextSiblingdElement(Node):Element
// set this Node as being hidden
public static void setHidden(Node node) {
if (node instanceof org.apache.xerces.impl.xs.opti.NodeImpl)
((org.apache.xerces.impl.xs.opti.NodeImpl)node).setReadOnly(true, false);
else if (node instanceof org.apache.xerces.dom.NodeImpl)
((org.apache.xerces.dom.NodeImpl)node).setReadOnly(true, false);
} // setHidden(node):void
// set this Node as being hidden, overloaded method
public static void setHidden(Node node, Hashtable hiddenNodes) {
if (node instanceof org.apache.xerces.impl.xs.opti.NodeImpl) {
((org.apache.xerces.impl.xs.opti.NodeImpl)node).setReadOnly(true, false);
}
else {
hiddenNodes.put(node, "");
}
} // setHidden(node):void
// set this Node as being visible
public static void setVisible(Node node) {
if (node instanceof org.apache.xerces.impl.xs.opti.NodeImpl)
((org.apache.xerces.impl.xs.opti.NodeImpl)node).setReadOnly(false, false);
else if (node instanceof org.apache.xerces.dom.NodeImpl)
((org.apache.xerces.dom.NodeImpl)node).setReadOnly(false, false);
} // setVisible(node):void
// set this Node as being visible, overloaded method
public static void setVisible(Node node, Hashtable hiddenNodes) {
if (node instanceof org.apache.xerces.impl.xs.opti.NodeImpl) {
((org.apache.xerces.impl.xs.opti.NodeImpl)node).setReadOnly(false, false);
}
else {
hiddenNodes.remove(node);
}
} // setVisible(node):void
// is this node hidden?
public static boolean isHidden(Node node) {
if (node instanceof org.apache.xerces.impl.xs.opti.NodeImpl)
return ((org.apache.xerces.impl.xs.opti.NodeImpl)node).getReadOnly();
else if (node instanceof org.apache.xerces.dom.NodeImpl)
return ((org.apache.xerces.dom.NodeImpl)node).getReadOnly();
return false;
} // isHidden(Node):boolean
// is this node hidden? overloaded method
public static boolean isHidden(Node node, Hashtable hiddenNodes) {
if (node instanceof org.apache.xerces.impl.xs.opti.NodeImpl) {
return ((org.apache.xerces.impl.xs.opti.NodeImpl)node).getReadOnly();
}
else {
return hiddenNodes.containsKey(node);
}
} // isHidden(Node):boolean
/** Finds and returns the first child node with the given name. */
public static Element getFirstChildElement(Node parent, String elemName) {
// search for node
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
if (child.getNodeName().equals(elemName)) {
return (Element)child;
}
}
child = child.getNextSibling();
}
// not found
return null;
} // getFirstChildElement(Node,String):Element
/** Finds and returns the last child node with the given name. */
public static Element getLastChildElement(Node parent, String elemName) {
// search for node
Node child = parent.getLastChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
if (child.getNodeName().equals(elemName)) {
return (Element)child;
}
}
child = child.getPreviousSibling();
}
// not found
return null;
} // getLastChildElement(Node,String):Element
/** Finds and returns the next sibling node with the given name. */
public static Element getNextSiblingElement(Node node, String elemName) {
// search for node
Node sibling = node.getNextSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE) {
if (sibling.getNodeName().equals(elemName)) {
return (Element)sibling;
}
}
sibling = sibling.getNextSibling();
}
// not found
return null;
} // getNextSiblingdElement(Node,String):Element
/** Finds and returns the first child node with the given qualified name. */
public static Element getFirstChildElementNS(Node parent,
String uri, String localpart) {
// search for node
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
String childURI = child.getNamespaceURI();
if (childURI != null && childURI.equals(uri) &&
child.getLocalName().equals(localpart)) {
return (Element)child;
}
}
child = child.getNextSibling();
}
// not found
return null;
} // getFirstChildElementNS(Node,String,String):Element
/** Finds and returns the last child node with the given qualified name. */
public static Element getLastChildElementNS(Node parent,
String uri, String localpart) {
// search for node
Node child = parent.getLastChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
String childURI = child.getNamespaceURI();
if (childURI != null && childURI.equals(uri) &&
child.getLocalName().equals(localpart)) {
return (Element)child;
}
}
child = child.getPreviousSibling();
}
// not found
return null;
} // getLastChildElementNS(Node,String,String):Element
/** Finds and returns the next sibling node with the given qualified name. */
public static Element getNextSiblingElementNS(Node node,
String uri, String localpart) {
// search for node
Node sibling = node.getNextSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE) {
String siblingURI = sibling.getNamespaceURI();
if (siblingURI != null && siblingURI.equals(uri) &&
sibling.getLocalName().equals(localpart)) {
return (Element)sibling;
}
}
sibling = sibling.getNextSibling();
}
// not found
return null;
} // getNextSiblingdElementNS(Node,String,String):Element
/** Finds and returns the first child node with the given name. */
public static Element getFirstChildElement(Node parent, String elemNames[]) {
// search for node
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
for (int i = 0; i < elemNames.length; i++) {
if (child.getNodeName().equals(elemNames[i])) {
return (Element)child;
}
}
}
child = child.getNextSibling();
}
// not found
return null;
} // getFirstChildElement(Node,String[]):Element
/** Finds and returns the last child node with the given name. */
public static Element getLastChildElement(Node parent, String elemNames[]) {
// search for node
Node child = parent.getLastChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
for (int i = 0; i < elemNames.length; i++) {
if (child.getNodeName().equals(elemNames[i])) {
return (Element)child;
}
}
}
child = child.getPreviousSibling();
}
// not found
return null;
} // getLastChildElement(Node,String[]):Element
/** Finds and returns the next sibling node with the given name. */
public static Element getNextSiblingElement(Node node, String elemNames[]) {
// search for node
Node sibling = node.getNextSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE) {
for (int i = 0; i < elemNames.length; i++) {
if (sibling.getNodeName().equals(elemNames[i])) {
return (Element)sibling;
}
}
}
sibling = sibling.getNextSibling();
}
// not found
return null;
} // getNextSiblingdElement(Node,String[]):Element
/** Finds and returns the first child node with the given qualified name. */
public static Element getFirstChildElementNS(Node parent,
String[][] elemNames) {
// search for node
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
for (int i = 0; i < elemNames.length; i++) {
String uri = child.getNamespaceURI();
if (uri != null && uri.equals(elemNames[i][0]) &&
child.getLocalName().equals(elemNames[i][1])) {
return (Element)child;
}
}
}
child = child.getNextSibling();
}
// not found
return null;
} // getFirstChildElementNS(Node,String[][]):Element
/** Finds and returns the last child node with the given qualified name. */
public static Element getLastChildElementNS(Node parent,
String[][] elemNames) {
// search for node
Node child = parent.getLastChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
for (int i = 0; i < elemNames.length; i++) {
String uri = child.getNamespaceURI();
if (uri != null && uri.equals(elemNames[i][0]) &&
child.getLocalName().equals(elemNames[i][1])) {
return (Element)child;
}
}
}
child = child.getPreviousSibling();
}
// not found
return null;
} // getLastChildElementNS(Node,String[][]):Element
/** Finds and returns the next sibling node with the given qualified name. */
public static Element getNextSiblingElementNS(Node node,
String[][] elemNames) {
// search for node
Node sibling = node.getNextSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE) {
for (int i = 0; i < elemNames.length; i++) {
String uri = sibling.getNamespaceURI();
if (uri != null && uri.equals(elemNames[i][0]) &&
sibling.getLocalName().equals(elemNames[i][1])) {
return (Element)sibling;
}
}
}
sibling = sibling.getNextSibling();
}
// not found
return null;
} // getNextSiblingdElementNS(Node,String[][]):Element
/**
* Finds and returns the first child node with the given name and
* attribute name, value pair.
*/
public static Element getFirstChildElement(Node parent,
String elemName,
String attrName,
String attrValue) {
// search for node
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element)child;
if (element.getNodeName().equals(elemName) &&
element.getAttribute(attrName).equals(attrValue)) {
return element;
}
}
child = child.getNextSibling();
}
// not found
return null;
} // getFirstChildElement(Node,String,String,String):Element
/**
* Finds and returns the last child node with the given name and
* attribute name, value pair.
*/
public static Element getLastChildElement(Node parent,
String elemName,
String attrName,
String attrValue) {
// search for node
Node child = parent.getLastChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element)child;
if (element.getNodeName().equals(elemName) &&
element.getAttribute(attrName).equals(attrValue)) {
return element;
}
}
child = child.getPreviousSibling();
}
// not found
return null;
} // getLastChildElement(Node,String,String,String):Element
/**
* Finds and returns the next sibling node with the given name and
* attribute name, value pair. Since only elements have attributes,
* the node returned will be of type Node.ELEMENT_NODE.
*/
public static Element getNextSiblingElement(Node node,
String elemName,
String attrName,
String attrValue) {
// search for node
Node sibling = node.getNextSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element)sibling;
if (element.getNodeName().equals(elemName) &&
element.getAttribute(attrName).equals(attrValue)) {
return element;
}
}
sibling = sibling.getNextSibling();
}
// not found
return null;
} // getNextSiblingElement(Node,String,String,String):Element
/**
* Returns the concatenated child text of the specified node.
* This method only looks at the immediate children of type
* <code>Node.TEXT_NODE</code> or the children of any child
* node that is of type <code>Node.CDATA_SECTION_NODE</code>
* for the concatenation.
*
* @param node The node to look at.
*/
public static String getChildText(Node node) {
// is there anything to do?
if (node == null) {
return null;
}
// concatenate children text
StringBuffer str = new StringBuffer();
Node child = node.getFirstChild();
while (child != null) {
short type = child.getNodeType();
if (type == Node.TEXT_NODE) {
str.append(child.getNodeValue());
}
else if (type == Node.CDATA_SECTION_NODE) {
str.append(getChildText(child));
}
child = child.getNextSibling();
}
// return text value
return str.toString();
} // getChildText(Node):String
// return the name of this element
public static String getName(Node node) {
return node.getNodeName();
} // getLocalName(Element): String
/** returns local name of this element if not null, otherwise
returns the name of the node
*/
public static String getLocalName(Node node) {
String name = node.getLocalName();
return (name!=null)? name:node.getNodeName();
} // getLocalName(Element): String
public static Element getParent(Element elem) {
Node parent = elem.getParentNode();
if (parent instanceof Element)
return (Element)parent;
return null;
} // getParent(Element):Element
// get the Document of which this Node is a part
public static Document getDocument(Node node) {
return node.getOwnerDocument();
} // getDocument(Node):Document
// return this Document's root node
public static Element getRoot(Document doc) {
return doc.getDocumentElement();
} // getRoot(Document(: Element
// some methods for handling attributes:
// return the right attribute node
public static Attr getAttr(Element elem, String name) {
return elem.getAttributeNode(name);
} // getAttr(Element, String):Attr
// return the right attribute node
public static Attr getAttrNS(Element elem, String nsUri,
String localName) {
return elem.getAttributeNodeNS(nsUri, localName);
} // getAttrNS(Element, String):Attr
// get all the attributes for an Element
public static Attr[] getAttrs(Element elem) {
NamedNodeMap attrMap = elem.getAttributes();
Attr [] attrArray = new Attr[attrMap.getLength()];
for (int i=0; i<attrMap.getLength(); i++)
attrArray[i] = (Attr)attrMap.item(i);
return attrArray;
} // getAttrs(Element): Attr[]
// get attribute's value
public static String getValue(Attr attribute) {
return attribute.getValue();
} // getValue(Attr):String
// It is noteworthy that, because of the way the DOM specs
// work, the next two methods return the empty string (not
// null!) when the attribute with the specified name does not
// exist on an element. Beware!
// return the value of the attribute of the given element
// with the given name
public static String getAttrValue(Element elem, String name) {
return elem.getAttribute(name);
} // getAttr(Element, String):Attr
// return the value of the attribute of the given element
// with the given name
public static String getAttrValueNS(Element elem, String nsUri,
String localName) {
return elem.getAttributeNS(nsUri, localName);
} // getAttrValueNS(Element, String):Attr
// return the prefix
public static String getPrefix(Node node) {
return node.getPrefix();
}
// return the namespace URI
public static String getNamespaceURI(Node node) {
return node.getNamespaceURI();
}
// return annotation
public static String getAnnotation(Node node) {
if (node instanceof ElementImpl) {
return ((ElementImpl)node).getAnnotation();
}
return null;
}
// return synthetic annotation
public static String getSyntheticAnnotation(Node node) {
if (node instanceof ElementImpl) {
return ((ElementImpl)node).getSyntheticAnnotation();
}
return null;
}
/**
* Creates a DOMException. On J2SE 1.4 and above the cause for the exception will be set.
*/
public static DOMException createDOMException(short code, Throwable cause) {
DOMException de = new DOMException(code, cause != null ? cause.getMessage() : null);
if (cause != null && ThrowableMethods.fgThrowableMethodsAvailable) {
try {
ThrowableMethods.fgThrowableInitCauseMethod.invoke(de, new Object [] {cause});
}
// Something went wrong. There's not much we can do about it.
catch (Exception e) {}
}
return de;
}
/**
* Creates an LSException. On J2SE 1.4 and above the cause for the exception will be set.
*/
public static LSException createLSException(short code, Throwable cause) {
LSException lse = new LSException(code, cause != null ? cause.getMessage() : null);
if (cause != null && ThrowableMethods.fgThrowableMethodsAvailable) {
try {
ThrowableMethods.fgThrowableInitCauseMethod.invoke(lse, new Object [] {cause});
}
// Something went wrong. There's not much we can do about it.
catch (Exception e) {}
}
return lse;
}
/**
* Holder of methods from java.lang.Throwable.
*/
static class ThrowableMethods {
// Method: java.lang.Throwable.initCause(java.lang.Throwable)
private static java.lang.reflect.Method fgThrowableInitCauseMethod = null;
// Flag indicating whether or not Throwable methods available.
private static boolean fgThrowableMethodsAvailable = false;
private ThrowableMethods() {}
// Attempt to get methods for java.lang.Throwable on class initialization.
static {
try {
fgThrowableInitCauseMethod = Throwable.class.getMethod("initCause", new Class [] {Throwable.class});
fgThrowableMethodsAvailable = true;
}
// ClassNotFoundException, NoSuchMethodException or SecurityException
// Whatever the case, we cannot use java.lang.Throwable.initCause(java.lang.Throwable).
catch (Exception exc) {
fgThrowableInitCauseMethod = null;
fgThrowableMethodsAvailable = false;
}
}
}
} // class DOMUtil
| true | true | public static void copyInto(Node src, Node dest) throws DOMException {
// get node factory
Document factory = dest.getOwnerDocument();
boolean domimpl = factory instanceof DocumentImpl;
// placement variables
Node start = src;
Node parent = src;
Node place = src;
// traverse source tree
while (place != null) {
// copy this node
Node node = null;
int type = place.getNodeType();
switch (type) {
case Node.CDATA_SECTION_NODE: {
node = factory.createCDATASection(place.getNodeValue());
break;
}
case Node.COMMENT_NODE: {
node = factory.createComment(place.getNodeValue());
break;
}
case Node.ELEMENT_NODE: {
Element element = factory.createElement(place.getNodeName());
node = element;
NamedNodeMap attrs = place.getAttributes();
int attrCount = attrs.getLength();
for (int i = 0; i < attrCount; i++) {
Attr attr = (Attr)attrs.item(i);
String attrName = attr.getNodeName();
String attrValue = attr.getNodeValue();
element.setAttribute(attrName, attrValue);
if (domimpl && !attr.getSpecified()) {
((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
}
}
break;
}
case Node.ENTITY_REFERENCE_NODE: {
node = factory.createEntityReference(place.getNodeName());
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: {
node = factory.createProcessingInstruction(place.getNodeName(),
place.getNodeValue());
break;
}
case Node.TEXT_NODE: {
node = factory.createTextNode(place.getNodeValue());
break;
}
default: {
throw new IllegalArgumentException("can't copy node type, "+
type+" ("+
node.getNodeName()+')');
}
}
dest.appendChild(node);
// iterate over children
if (place.hasChildNodes()) {
parent = place;
place = place.getFirstChild();
dest = node;
}
// advance
else {
place = place.getNextSibling();
while (place == null && parent != start) {
place = parent.getNextSibling();
parent = parent.getParentNode();
dest = dest.getParentNode();
}
}
}
} // copyInto(Node,Node)
| public static void copyInto(Node src, Node dest) throws DOMException {
// get node factory
Document factory = dest.getOwnerDocument();
boolean domimpl = factory instanceof DocumentImpl;
// placement variables
Node start = src;
Node parent = src;
Node place = src;
// traverse source tree
while (place != null) {
// copy this node
Node node = null;
int type = place.getNodeType();
switch (type) {
case Node.CDATA_SECTION_NODE: {
node = factory.createCDATASection(place.getNodeValue());
break;
}
case Node.COMMENT_NODE: {
node = factory.createComment(place.getNodeValue());
break;
}
case Node.ELEMENT_NODE: {
Element element = factory.createElement(place.getNodeName());
node = element;
NamedNodeMap attrs = place.getAttributes();
int attrCount = attrs.getLength();
for (int i = 0; i < attrCount; i++) {
Attr attr = (Attr)attrs.item(i);
String attrName = attr.getNodeName();
String attrValue = attr.getNodeValue();
element.setAttribute(attrName, attrValue);
if (domimpl && !attr.getSpecified()) {
((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
}
}
break;
}
case Node.ENTITY_REFERENCE_NODE: {
node = factory.createEntityReference(place.getNodeName());
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: {
node = factory.createProcessingInstruction(place.getNodeName(),
place.getNodeValue());
break;
}
case Node.TEXT_NODE: {
node = factory.createTextNode(place.getNodeValue());
break;
}
default: {
throw new IllegalArgumentException("can't copy node type, "+
type+" ("+
place.getNodeName()+')');
}
}
dest.appendChild(node);
// iterate over children
if (place.hasChildNodes()) {
parent = place;
place = place.getFirstChild();
dest = node;
}
// advance
else {
place = place.getNextSibling();
while (place == null && parent != start) {
place = parent.getNextSibling();
parent = parent.getParentNode();
dest = dest.getParentNode();
}
}
}
} // copyInto(Node,Node)
|
diff --git a/src/com/binoy/vibhinna/VibhinnaProvider.java b/src/com/binoy/vibhinna/VibhinnaProvider.java
index dca79b0..8800bc5 100644
--- a/src/com/binoy/vibhinna/VibhinnaProvider.java
+++ b/src/com/binoy/vibhinna/VibhinnaProvider.java
@@ -1,378 +1,378 @@
package com.binoy.vibhinna;
import java.io.File;
import java.util.Scanner;
import java.util.regex.Pattern;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
public class VibhinnaProvider extends ContentProvider {
private DatabaseHelper mDatabaseHelper;
private SQLiteDatabase mDatabase;
private Context mContext;
protected static LocalBroadcastManager mLocalBroadcastManager;
public static final String AUTHORITY = "com.binoy.vibhinna.VibhinnaProvider";
private static final String TAG = "VibhinnaProvider";
public static final int VFS = 0;
public static final int VFS_ID = 1;
private static final int VFS_LIST = 2;
private static final int VFS_DETAILS = 3;
private static final int VFS_SCAN = 4;
private static final int WRITE_XML = 5;
private static final int READ_XML = 6;
private static final UriMatcher sURIMatcher = new UriMatcher(
UriMatcher.NO_MATCH);
public static final String VFS_BASE_PATH = "vfs";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + VFS_BASE_PATH);
public static final Uri LIST_DISPLAY_URI = Uri.parse("content://"
+ AUTHORITY + "/" + VFS_BASE_PATH + "/list");
static {
sURIMatcher.addURI(AUTHORITY, VFS_BASE_PATH, VFS);
sURIMatcher.addURI(AUTHORITY, VFS_BASE_PATH + "/#", VFS_ID);
sURIMatcher.addURI(AUTHORITY, VFS_BASE_PATH + "/list", VFS_LIST);
sURIMatcher
.addURI(AUTHORITY, VFS_BASE_PATH + "/details/#", VFS_DETAILS);
sURIMatcher.addURI(AUTHORITY, VFS_BASE_PATH + "/scan", VFS_SCAN);
sURIMatcher.addURI(AUTHORITY, VFS_BASE_PATH + "/write_xml", WRITE_XML);
sURIMatcher.addURI(AUTHORITY, VFS_BASE_PATH + "/read_xml", READ_XML);
}
@Override
public int delete(Uri uri, String where, String[] selectionArgs) {
int count = 0;
switch (sURIMatcher.match(uri)) {
case VFS:
count = mDatabase.delete(DatabaseHelper.VFS_DATABASE_TABLE, where,
selectionArgs);
break;
case VFS_ID:
count = mDatabase.delete(DatabaseHelper.VFS_DATABASE_TABLE,
BaseColumns._ID
+ " = "
+ uri.getPathSegments().get(1)
+ (!TextUtils.isEmpty(where) ? " AND (" + where
+ ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public String getType(Uri uri) {
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case VFS_ID:
return "vnd.android.cursor.item/vnd.vibhinna.vfs";
case VFS:
return "vnd.android.cursor.dir/vnd.vibhinna.vfs_dir";
case VFS_LIST:
return "vnd.android.cursor.dir/vnd.vibhinna.vfs_list";
case VFS_DETAILS:
return "vnd.android.cursor.item/vnd.vibhinna.vfs_details";
case VFS_SCAN:
return "vnd.android.cursor.item/vnd.vibhinna.vfs_scan";
case READ_XML:
return "vnd.android.cursor.item/vnd.vibhinna.vfs_read_xml";
case WRITE_XML:
return "vnd.android.cursor.item/vnd.vibhinna.vfs_write_xml";
default:
throw new IllegalArgumentException("Unknown URI");
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
long rowID = mDatabase.insert(DatabaseHelper.VFS_DATABASE_TABLE, null,
values);
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
// throw new SQLException("Failed to insert row into " + uri);
return uri;
}
@Override
public boolean onCreate() {
mContext = getContext();
mDatabaseHelper = new DatabaseHelper(mContext);
mDatabase = mDatabaseHelper.getWritableDatabase();
mLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext);
return true;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch (sURIMatcher.match(uri)) {
case VFS:
count = mDatabase.update(DatabaseHelper.VFS_DATABASE_TABLE, values,
selection, selectionArgs);
break;
case VFS_ID:
count = mDatabase.update(DatabaseHelper.VFS_DATABASE_TABLE, values,
BaseColumns._ID + " = " + uri.getLastPathSegment(),
selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(DatabaseHelper.VFS_DATABASE_TABLE);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case VFS_ID:
queryBuilder.appendWhere(BaseColumns._ID + "="
+ uri.getLastPathSegment());
break;
case VFS:
// no filter
break;
case VFS_LIST:
Cursor c = query(CONTENT_URI, projection, selection, selectionArgs,
sortOrder);
MatrixCursor cursor = new MatrixCursor(
Constants.MATRIX_COLUMN_NAMES);
if (c.moveToFirst()) {
do {
File root = new File(c.getString(2));
if (root.canRead()) {
Object[] fsii = new Object[8];
String cache = null;
String data = null;
String system = null;
String vdstatus = "0";
File cacheimg = new File(root, "cache.img");
if (cacheimg.exists()) {
cache = mContext.getString(R.string.space_in_mb,
(cacheimg.length() / 1048576));
} else
cache = mContext.getString(R.string.error);
File dataimg = new File(root, "data.img");
if (dataimg.exists()) {
data = mContext.getString(R.string.space_in_mb,
(dataimg.length() / 1048576));
} else
data = mContext.getString(R.string.error);
File systemimg = new File(root, "system.img");
if (systemimg.exists()) {
system = mContext.getString(R.string.space_in_mb,
(systemimg.length() / 1048576));
} else
system = mContext.getString(R.string.error);
if (systemimg.exists() && cacheimg.exists()
&& dataimg.exists()) {
vdstatus = "1";
} else
vdstatus = "0";
fsii[0] = Integer.parseInt(c.getString(0));
fsii[1] = c.getString(1);
fsii[2] = c.getString(4);
fsii[3] = null;
fsii[4] = c.getString(3);
fsii[5] = mContext.getString(R.string.vfs_short_info,
cache, data, system);
fsii[6] = vdstatus;
fsii[7] = c.getString(2);
cursor.addRow(fsii);
}
} while (c.moveToNext());
}
c.close();
return cursor;
case VFS_DETAILS:
String[] vsinfo = new String[29];
Log.d(TAG, "Uri : " + uri.toString());
Cursor databaseCursor = mDatabase.query(
DatabaseHelper.VFS_DATABASE_TABLE, Constants.allColumns,
"_id = ?", new String[] { uri.getLastPathSegment() }, null,
null, null);
databaseCursor.moveToFirst();
vsinfo[0] = databaseCursor.getString(0);
vsinfo[1] = databaseCursor.getString(1);
String vspath = databaseCursor.getString(2);
File vsfolder = new File(vspath);
vsinfo[2] = vsfolder.getName();
vsinfo[3] = databaseCursor.getString(3);
vsinfo[4] = databaseCursor.getString(4);
databaseCursor.close();
for (int i = 5; i < 29; i++) {
vsinfo[i] = mContext.getString(R.string.not_available);
}
for (int i = 7; i < 29; i = i + 8) {
vsinfo[i] = mContext.getString(R.string.corrupted);
}
try {
String[] shellinput = { Constants.CMD_TUNE2FS, vspath,
"/cache.img", "" };
String istr = ProcessManager.inputStreamReader(shellinput, 40);
Scanner scanner = new Scanner(istr).useDelimiter("\\n");
scanner.findWithinHorizon(
Pattern.compile("Filesystem\\sUUID:\\s*(\\S+)"), 0);
String chuuid = scanner.match().group(1);
scanner.findWithinHorizon(Pattern
.compile("Filesystem\\smagic\\snumber:\\s*(\\S+)"), 0);
String chmagicnumber = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\scount:\\s*(\\d+)"), 0);
String chblockcount = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Free\\sblocks:\\s*(\\d+)"), 0);
String chfreeblocks = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\ssize:\\s*(\\d+)"), 0);
String chblocksize = scanner.match().group(1);
vsinfo[5] = chuuid;
vsinfo[6] = chmagicnumber;
if (chmagicnumber.equals("0xEF53")) {
vsinfo[7] = mContext.getString(R.string.healthy);
}
vsinfo[8] = Integer.parseInt(chblockcount)
* Integer.parseInt(chblocksize) / 1048576 + "";
vsinfo[9] = Integer.parseInt(chfreeblocks)
* Integer.parseInt(chblocksize) / 1048576 + "";
vsinfo[10] = chblockcount;
vsinfo[11] = chfreeblocks;
vsinfo[12] = chblocksize;
} catch (Exception e) {
Log.w("Exception", "exception in executing :"
+ Constants.CMD_TUNE2FS + vspath + "/cache.img");
}
try {
String[] shellinput = { Constants.CMD_TUNE2FS, vspath,
"/data.img", "" };
String istr = ProcessManager.inputStreamReader(shellinput, 40);
Scanner scanner = new Scanner(istr).useDelimiter("\\n");
scanner.findWithinHorizon(
Pattern.compile("Filesystem\\sUUID:\\s*(\\S+)"), 0);
String dauuid = scanner.match().group(1);
scanner.findWithinHorizon(Pattern
.compile("Filesystem\\smagic\\snumber:\\s*(\\S+)"), 0);
String damagicnumber = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\scount:\\s*(\\d+)"), 0);
String dablockcount = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Free\\sblocks:\\s*(\\d+)"), 0);
String dafreeblocks = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\ssize:\\s*(\\d+)"), 0);
String dablocksize = scanner.match().group(1);
vsinfo[13] = dauuid;
vsinfo[14] = damagicnumber;
if (damagicnumber.equals("0xEF53")) {
vsinfo[15] = mContext.getString(R.string.healthy);
}
vsinfo[16] = Integer.parseInt(dablockcount)
* Integer.parseInt(dablocksize) / 1048576 + "";
vsinfo[17] = Integer.parseInt(dafreeblocks)
* Integer.parseInt(dablocksize) / 1048576 + "";
vsinfo[18] = dablockcount;
vsinfo[19] = dafreeblocks;
vsinfo[20] = dablocksize;
} catch (Exception e) {
Log.w("Exception", "exception in executing :"
+ Constants.CMD_TUNE2FS + vspath + "/data.img");
}
try {
String[] shellinput = { Constants.CMD_TUNE2FS, vspath,
"/system.img", "" };
String istr = ProcessManager.inputStreamReader(shellinput, 40);
Scanner scanner = new Scanner(istr).useDelimiter("\\n");
scanner.findWithinHorizon(
Pattern.compile("Filesystem\\sUUID:\\s*(\\S+)"), 0);
String syuuid = scanner.match().group(1);
scanner.findWithinHorizon(Pattern
.compile("Filesystem\\smagic\\snumber:\\s*(\\S+)"), 0);
String symagicnumber = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\scount:\\s*(\\d+)"), 0);
String syblockcount = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Free\\sblocks:\\s*(\\d+)"), 0);
String syfreeblocks = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\ssize:\\s*(\\d+)"), 0);
String syblocksize = scanner.match().group(1);
vsinfo[21] = syuuid;
vsinfo[22] = symagicnumber;
if (symagicnumber.equals("0xEF53")) {
vsinfo[23] = mContext.getString(R.string.healthy);
}
vsinfo[24] = Integer.parseInt(syblockcount)
* Integer.parseInt(syblocksize) / 1048576 + "";
vsinfo[25] = Integer.parseInt(syfreeblocks)
* Integer.parseInt(syblocksize) / 1048576 + "";
vsinfo[26] = syblockcount;
vsinfo[27] = syfreeblocks;
vsinfo[28] = syblocksize;
} catch (Exception e) {
Log.w("Exception", "exception in executing :"
+ Constants.CMD_TUNE2FS + vspath + "/system.img");
}
String key[] = new String[29];
for (int i = 0; i < key.length; i++) {
key[i] = "key" + i;
}
MatrixCursor matrixCursor = new MatrixCursor(key);
matrixCursor.addRow(vsinfo);
return matrixCursor;
case VFS_SCAN:
DatabaseUtils.scanFolder(mDatabase, mContext);
Intent vfsListUpdatedIntent = new Intent();
vfsListUpdatedIntent
.setAction(VibhinnaService.ACTION_VFS_LIST_UPDATED);
mLocalBroadcastManager.sendBroadcast(vfsListUpdatedIntent);
- break;
+ return null;
case WRITE_XML:
DatabaseUtils.writeXML(mDatabase);
- break;
+ return null;
case READ_XML:
DatabaseUtils.readXML(mDatabase);
- break;
+ return null;
default:
Log.e(TAG, "unknown uri :" + uri.toString() + ", type : " + uriType);
throw new IllegalArgumentException("Unknown URI");
}
Cursor cursor = queryBuilder.query(mDatabase, projection, selection,
selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(mContext.getContentResolver(), uri);
return cursor;
}
}
| false | true | public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(DatabaseHelper.VFS_DATABASE_TABLE);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case VFS_ID:
queryBuilder.appendWhere(BaseColumns._ID + "="
+ uri.getLastPathSegment());
break;
case VFS:
// no filter
break;
case VFS_LIST:
Cursor c = query(CONTENT_URI, projection, selection, selectionArgs,
sortOrder);
MatrixCursor cursor = new MatrixCursor(
Constants.MATRIX_COLUMN_NAMES);
if (c.moveToFirst()) {
do {
File root = new File(c.getString(2));
if (root.canRead()) {
Object[] fsii = new Object[8];
String cache = null;
String data = null;
String system = null;
String vdstatus = "0";
File cacheimg = new File(root, "cache.img");
if (cacheimg.exists()) {
cache = mContext.getString(R.string.space_in_mb,
(cacheimg.length() / 1048576));
} else
cache = mContext.getString(R.string.error);
File dataimg = new File(root, "data.img");
if (dataimg.exists()) {
data = mContext.getString(R.string.space_in_mb,
(dataimg.length() / 1048576));
} else
data = mContext.getString(R.string.error);
File systemimg = new File(root, "system.img");
if (systemimg.exists()) {
system = mContext.getString(R.string.space_in_mb,
(systemimg.length() / 1048576));
} else
system = mContext.getString(R.string.error);
if (systemimg.exists() && cacheimg.exists()
&& dataimg.exists()) {
vdstatus = "1";
} else
vdstatus = "0";
fsii[0] = Integer.parseInt(c.getString(0));
fsii[1] = c.getString(1);
fsii[2] = c.getString(4);
fsii[3] = null;
fsii[4] = c.getString(3);
fsii[5] = mContext.getString(R.string.vfs_short_info,
cache, data, system);
fsii[6] = vdstatus;
fsii[7] = c.getString(2);
cursor.addRow(fsii);
}
} while (c.moveToNext());
}
c.close();
return cursor;
case VFS_DETAILS:
String[] vsinfo = new String[29];
Log.d(TAG, "Uri : " + uri.toString());
Cursor databaseCursor = mDatabase.query(
DatabaseHelper.VFS_DATABASE_TABLE, Constants.allColumns,
"_id = ?", new String[] { uri.getLastPathSegment() }, null,
null, null);
databaseCursor.moveToFirst();
vsinfo[0] = databaseCursor.getString(0);
vsinfo[1] = databaseCursor.getString(1);
String vspath = databaseCursor.getString(2);
File vsfolder = new File(vspath);
vsinfo[2] = vsfolder.getName();
vsinfo[3] = databaseCursor.getString(3);
vsinfo[4] = databaseCursor.getString(4);
databaseCursor.close();
for (int i = 5; i < 29; i++) {
vsinfo[i] = mContext.getString(R.string.not_available);
}
for (int i = 7; i < 29; i = i + 8) {
vsinfo[i] = mContext.getString(R.string.corrupted);
}
try {
String[] shellinput = { Constants.CMD_TUNE2FS, vspath,
"/cache.img", "" };
String istr = ProcessManager.inputStreamReader(shellinput, 40);
Scanner scanner = new Scanner(istr).useDelimiter("\\n");
scanner.findWithinHorizon(
Pattern.compile("Filesystem\\sUUID:\\s*(\\S+)"), 0);
String chuuid = scanner.match().group(1);
scanner.findWithinHorizon(Pattern
.compile("Filesystem\\smagic\\snumber:\\s*(\\S+)"), 0);
String chmagicnumber = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\scount:\\s*(\\d+)"), 0);
String chblockcount = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Free\\sblocks:\\s*(\\d+)"), 0);
String chfreeblocks = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\ssize:\\s*(\\d+)"), 0);
String chblocksize = scanner.match().group(1);
vsinfo[5] = chuuid;
vsinfo[6] = chmagicnumber;
if (chmagicnumber.equals("0xEF53")) {
vsinfo[7] = mContext.getString(R.string.healthy);
}
vsinfo[8] = Integer.parseInt(chblockcount)
* Integer.parseInt(chblocksize) / 1048576 + "";
vsinfo[9] = Integer.parseInt(chfreeblocks)
* Integer.parseInt(chblocksize) / 1048576 + "";
vsinfo[10] = chblockcount;
vsinfo[11] = chfreeblocks;
vsinfo[12] = chblocksize;
} catch (Exception e) {
Log.w("Exception", "exception in executing :"
+ Constants.CMD_TUNE2FS + vspath + "/cache.img");
}
try {
String[] shellinput = { Constants.CMD_TUNE2FS, vspath,
"/data.img", "" };
String istr = ProcessManager.inputStreamReader(shellinput, 40);
Scanner scanner = new Scanner(istr).useDelimiter("\\n");
scanner.findWithinHorizon(
Pattern.compile("Filesystem\\sUUID:\\s*(\\S+)"), 0);
String dauuid = scanner.match().group(1);
scanner.findWithinHorizon(Pattern
.compile("Filesystem\\smagic\\snumber:\\s*(\\S+)"), 0);
String damagicnumber = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\scount:\\s*(\\d+)"), 0);
String dablockcount = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Free\\sblocks:\\s*(\\d+)"), 0);
String dafreeblocks = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\ssize:\\s*(\\d+)"), 0);
String dablocksize = scanner.match().group(1);
vsinfo[13] = dauuid;
vsinfo[14] = damagicnumber;
if (damagicnumber.equals("0xEF53")) {
vsinfo[15] = mContext.getString(R.string.healthy);
}
vsinfo[16] = Integer.parseInt(dablockcount)
* Integer.parseInt(dablocksize) / 1048576 + "";
vsinfo[17] = Integer.parseInt(dafreeblocks)
* Integer.parseInt(dablocksize) / 1048576 + "";
vsinfo[18] = dablockcount;
vsinfo[19] = dafreeblocks;
vsinfo[20] = dablocksize;
} catch (Exception e) {
Log.w("Exception", "exception in executing :"
+ Constants.CMD_TUNE2FS + vspath + "/data.img");
}
try {
String[] shellinput = { Constants.CMD_TUNE2FS, vspath,
"/system.img", "" };
String istr = ProcessManager.inputStreamReader(shellinput, 40);
Scanner scanner = new Scanner(istr).useDelimiter("\\n");
scanner.findWithinHorizon(
Pattern.compile("Filesystem\\sUUID:\\s*(\\S+)"), 0);
String syuuid = scanner.match().group(1);
scanner.findWithinHorizon(Pattern
.compile("Filesystem\\smagic\\snumber:\\s*(\\S+)"), 0);
String symagicnumber = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\scount:\\s*(\\d+)"), 0);
String syblockcount = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Free\\sblocks:\\s*(\\d+)"), 0);
String syfreeblocks = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\ssize:\\s*(\\d+)"), 0);
String syblocksize = scanner.match().group(1);
vsinfo[21] = syuuid;
vsinfo[22] = symagicnumber;
if (symagicnumber.equals("0xEF53")) {
vsinfo[23] = mContext.getString(R.string.healthy);
}
vsinfo[24] = Integer.parseInt(syblockcount)
* Integer.parseInt(syblocksize) / 1048576 + "";
vsinfo[25] = Integer.parseInt(syfreeblocks)
* Integer.parseInt(syblocksize) / 1048576 + "";
vsinfo[26] = syblockcount;
vsinfo[27] = syfreeblocks;
vsinfo[28] = syblocksize;
} catch (Exception e) {
Log.w("Exception", "exception in executing :"
+ Constants.CMD_TUNE2FS + vspath + "/system.img");
}
String key[] = new String[29];
for (int i = 0; i < key.length; i++) {
key[i] = "key" + i;
}
MatrixCursor matrixCursor = new MatrixCursor(key);
matrixCursor.addRow(vsinfo);
return matrixCursor;
case VFS_SCAN:
DatabaseUtils.scanFolder(mDatabase, mContext);
Intent vfsListUpdatedIntent = new Intent();
vfsListUpdatedIntent
.setAction(VibhinnaService.ACTION_VFS_LIST_UPDATED);
mLocalBroadcastManager.sendBroadcast(vfsListUpdatedIntent);
break;
case WRITE_XML:
DatabaseUtils.writeXML(mDatabase);
break;
case READ_XML:
DatabaseUtils.readXML(mDatabase);
break;
default:
Log.e(TAG, "unknown uri :" + uri.toString() + ", type : " + uriType);
throw new IllegalArgumentException("Unknown URI");
}
Cursor cursor = queryBuilder.query(mDatabase, projection, selection,
selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(mContext.getContentResolver(), uri);
return cursor;
}
| public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(DatabaseHelper.VFS_DATABASE_TABLE);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case VFS_ID:
queryBuilder.appendWhere(BaseColumns._ID + "="
+ uri.getLastPathSegment());
break;
case VFS:
// no filter
break;
case VFS_LIST:
Cursor c = query(CONTENT_URI, projection, selection, selectionArgs,
sortOrder);
MatrixCursor cursor = new MatrixCursor(
Constants.MATRIX_COLUMN_NAMES);
if (c.moveToFirst()) {
do {
File root = new File(c.getString(2));
if (root.canRead()) {
Object[] fsii = new Object[8];
String cache = null;
String data = null;
String system = null;
String vdstatus = "0";
File cacheimg = new File(root, "cache.img");
if (cacheimg.exists()) {
cache = mContext.getString(R.string.space_in_mb,
(cacheimg.length() / 1048576));
} else
cache = mContext.getString(R.string.error);
File dataimg = new File(root, "data.img");
if (dataimg.exists()) {
data = mContext.getString(R.string.space_in_mb,
(dataimg.length() / 1048576));
} else
data = mContext.getString(R.string.error);
File systemimg = new File(root, "system.img");
if (systemimg.exists()) {
system = mContext.getString(R.string.space_in_mb,
(systemimg.length() / 1048576));
} else
system = mContext.getString(R.string.error);
if (systemimg.exists() && cacheimg.exists()
&& dataimg.exists()) {
vdstatus = "1";
} else
vdstatus = "0";
fsii[0] = Integer.parseInt(c.getString(0));
fsii[1] = c.getString(1);
fsii[2] = c.getString(4);
fsii[3] = null;
fsii[4] = c.getString(3);
fsii[5] = mContext.getString(R.string.vfs_short_info,
cache, data, system);
fsii[6] = vdstatus;
fsii[7] = c.getString(2);
cursor.addRow(fsii);
}
} while (c.moveToNext());
}
c.close();
return cursor;
case VFS_DETAILS:
String[] vsinfo = new String[29];
Log.d(TAG, "Uri : " + uri.toString());
Cursor databaseCursor = mDatabase.query(
DatabaseHelper.VFS_DATABASE_TABLE, Constants.allColumns,
"_id = ?", new String[] { uri.getLastPathSegment() }, null,
null, null);
databaseCursor.moveToFirst();
vsinfo[0] = databaseCursor.getString(0);
vsinfo[1] = databaseCursor.getString(1);
String vspath = databaseCursor.getString(2);
File vsfolder = new File(vspath);
vsinfo[2] = vsfolder.getName();
vsinfo[3] = databaseCursor.getString(3);
vsinfo[4] = databaseCursor.getString(4);
databaseCursor.close();
for (int i = 5; i < 29; i++) {
vsinfo[i] = mContext.getString(R.string.not_available);
}
for (int i = 7; i < 29; i = i + 8) {
vsinfo[i] = mContext.getString(R.string.corrupted);
}
try {
String[] shellinput = { Constants.CMD_TUNE2FS, vspath,
"/cache.img", "" };
String istr = ProcessManager.inputStreamReader(shellinput, 40);
Scanner scanner = new Scanner(istr).useDelimiter("\\n");
scanner.findWithinHorizon(
Pattern.compile("Filesystem\\sUUID:\\s*(\\S+)"), 0);
String chuuid = scanner.match().group(1);
scanner.findWithinHorizon(Pattern
.compile("Filesystem\\smagic\\snumber:\\s*(\\S+)"), 0);
String chmagicnumber = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\scount:\\s*(\\d+)"), 0);
String chblockcount = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Free\\sblocks:\\s*(\\d+)"), 0);
String chfreeblocks = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\ssize:\\s*(\\d+)"), 0);
String chblocksize = scanner.match().group(1);
vsinfo[5] = chuuid;
vsinfo[6] = chmagicnumber;
if (chmagicnumber.equals("0xEF53")) {
vsinfo[7] = mContext.getString(R.string.healthy);
}
vsinfo[8] = Integer.parseInt(chblockcount)
* Integer.parseInt(chblocksize) / 1048576 + "";
vsinfo[9] = Integer.parseInt(chfreeblocks)
* Integer.parseInt(chblocksize) / 1048576 + "";
vsinfo[10] = chblockcount;
vsinfo[11] = chfreeblocks;
vsinfo[12] = chblocksize;
} catch (Exception e) {
Log.w("Exception", "exception in executing :"
+ Constants.CMD_TUNE2FS + vspath + "/cache.img");
}
try {
String[] shellinput = { Constants.CMD_TUNE2FS, vspath,
"/data.img", "" };
String istr = ProcessManager.inputStreamReader(shellinput, 40);
Scanner scanner = new Scanner(istr).useDelimiter("\\n");
scanner.findWithinHorizon(
Pattern.compile("Filesystem\\sUUID:\\s*(\\S+)"), 0);
String dauuid = scanner.match().group(1);
scanner.findWithinHorizon(Pattern
.compile("Filesystem\\smagic\\snumber:\\s*(\\S+)"), 0);
String damagicnumber = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\scount:\\s*(\\d+)"), 0);
String dablockcount = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Free\\sblocks:\\s*(\\d+)"), 0);
String dafreeblocks = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\ssize:\\s*(\\d+)"), 0);
String dablocksize = scanner.match().group(1);
vsinfo[13] = dauuid;
vsinfo[14] = damagicnumber;
if (damagicnumber.equals("0xEF53")) {
vsinfo[15] = mContext.getString(R.string.healthy);
}
vsinfo[16] = Integer.parseInt(dablockcount)
* Integer.parseInt(dablocksize) / 1048576 + "";
vsinfo[17] = Integer.parseInt(dafreeblocks)
* Integer.parseInt(dablocksize) / 1048576 + "";
vsinfo[18] = dablockcount;
vsinfo[19] = dafreeblocks;
vsinfo[20] = dablocksize;
} catch (Exception e) {
Log.w("Exception", "exception in executing :"
+ Constants.CMD_TUNE2FS + vspath + "/data.img");
}
try {
String[] shellinput = { Constants.CMD_TUNE2FS, vspath,
"/system.img", "" };
String istr = ProcessManager.inputStreamReader(shellinput, 40);
Scanner scanner = new Scanner(istr).useDelimiter("\\n");
scanner.findWithinHorizon(
Pattern.compile("Filesystem\\sUUID:\\s*(\\S+)"), 0);
String syuuid = scanner.match().group(1);
scanner.findWithinHorizon(Pattern
.compile("Filesystem\\smagic\\snumber:\\s*(\\S+)"), 0);
String symagicnumber = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\scount:\\s*(\\d+)"), 0);
String syblockcount = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Free\\sblocks:\\s*(\\d+)"), 0);
String syfreeblocks = scanner.match().group(1);
scanner.findWithinHorizon(
Pattern.compile("Block\\ssize:\\s*(\\d+)"), 0);
String syblocksize = scanner.match().group(1);
vsinfo[21] = syuuid;
vsinfo[22] = symagicnumber;
if (symagicnumber.equals("0xEF53")) {
vsinfo[23] = mContext.getString(R.string.healthy);
}
vsinfo[24] = Integer.parseInt(syblockcount)
* Integer.parseInt(syblocksize) / 1048576 + "";
vsinfo[25] = Integer.parseInt(syfreeblocks)
* Integer.parseInt(syblocksize) / 1048576 + "";
vsinfo[26] = syblockcount;
vsinfo[27] = syfreeblocks;
vsinfo[28] = syblocksize;
} catch (Exception e) {
Log.w("Exception", "exception in executing :"
+ Constants.CMD_TUNE2FS + vspath + "/system.img");
}
String key[] = new String[29];
for (int i = 0; i < key.length; i++) {
key[i] = "key" + i;
}
MatrixCursor matrixCursor = new MatrixCursor(key);
matrixCursor.addRow(vsinfo);
return matrixCursor;
case VFS_SCAN:
DatabaseUtils.scanFolder(mDatabase, mContext);
Intent vfsListUpdatedIntent = new Intent();
vfsListUpdatedIntent
.setAction(VibhinnaService.ACTION_VFS_LIST_UPDATED);
mLocalBroadcastManager.sendBroadcast(vfsListUpdatedIntent);
return null;
case WRITE_XML:
DatabaseUtils.writeXML(mDatabase);
return null;
case READ_XML:
DatabaseUtils.readXML(mDatabase);
return null;
default:
Log.e(TAG, "unknown uri :" + uri.toString() + ", type : " + uriType);
throw new IllegalArgumentException("Unknown URI");
}
Cursor cursor = queryBuilder.query(mDatabase, projection, selection,
selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(mContext.getContentResolver(), uri);
return cursor;
}
|
diff --git a/src/org/doube/bonej/MeasureSurface.java b/src/org/doube/bonej/MeasureSurface.java
index c7cb8201..9b42e8ff 100644
--- a/src/org/doube/bonej/MeasureSurface.java
+++ b/src/org/doube/bonej/MeasureSurface.java
@@ -1,162 +1,161 @@
package org.doube.bonej;
/**
* MeasureSurface plugin for ImageJ
* Copyright 2009 2010 Michael Doube
*
*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/>.
*/
import java.util.List;
import javax.vecmath.Color3f;
import javax.vecmath.Point3f;
import org.doube.geometry.Vectors;
import org.doube.util.ImageCheck;
import org.doube.util.ResultInserter;
import ij.IJ;
import ij.ImagePlus;
import ij.gui.GenericDialog;
import ij.plugin.PlugIn;
import ij3d.Content;
import ij3d.Image3DUniverse;
import marchingcubes.MCTriangulator;
import customnode.CustomTriangleMesh;
/**
* Make a mesh from a binary or 8-bit image and get surface area measurements
* from it.
*
* @author Michael Doube
*
*/
public class MeasureSurface implements PlugIn {
@SuppressWarnings("unchecked")
public void run(String arg) {
if (!ImageCheck.checkEnvironment())
return;
ImagePlus imp = IJ.getImage();
if (null == imp) {
IJ.noImage();
return;
}
int threshold = 128;
ImageCheck ic = new ImageCheck();
if (ic.isBinary(imp)) {
threshold = 128;
} else if (imp.getBitDepth() == 8) {
ThresholdMinConn tmc = new ThresholdMinConn();
threshold = imp.getProcessor().getAutoThreshold(
tmc.getStackHistogram(imp));
} else {
IJ.error("Isosurface", "Image type not supported");
return;
}
GenericDialog gd = new GenericDialog("Options");
gd.addNumericField("Resampling", 6, 0);
gd.addNumericField("Threshold", threshold, 0);
gd.addCheckbox("Show surface", true);
gd.addHelp("http://bonej.org/isosurface");
gd.showDialog();
int resamplingF = (int) Math.floor(gd.getNextNumber());
threshold = (int) Math.floor(gd.getNextNumber());
boolean doSurfaceRendering = gd.getNextBoolean();
if (gd.wasCanceled())
return;
final boolean[] channels = { true, false, false };
MCTriangulator mct = new MCTriangulator();
List<Point3f> points = mct.getTriangles(imp, threshold, channels,
resamplingF);
IJ.log("Isosurface contains " + (points.size() / 3) + " triangles");
ResultInserter ri = ResultInserter.getInstance();
double area = getSurfaceArea(points);
ri.setResultInRow(imp, "BS (" + imp.getCalibration().getUnits() + "²)",
area);
ri.updateTable();
if (points.size() == 0) {
IJ.error("Isosurface contains no points");
return;
}
if (doSurfaceRendering) {
renderSurface(points, "Surface of " + imp.getTitle());
}
- points.clear();
return;
}
/**
* Show the surface in the ImageJ 3D Viewer
*
* @param points
* @param title
*/
private void renderSurface(List<Point3f> points, String title) {
IJ.showStatus("Rendering surface...");
CustomTriangleMesh mesh = new CustomTriangleMesh(points);
// Create a universe and show it
Image3DUniverse univ = new Image3DUniverse();
univ.show();
// Add the mesh
Content c = univ.addCustomMesh(mesh, title);
Color3f green = new Color3f(0.0f, 0.5f, 0.0f);
c.getColor();
c.setColor(green);
c.setTransparency((float) 0.33);
c.setSelected(true);
}
/**
* Calculate surface area of the isosurface
*
* @param points
* in 3D triangle mesh
* @return surface area
*/
public static double getSurfaceArea(List<Point3f> points) {
double sumArea = 0;
final int nPoints = points.size();
Point3f origin = new Point3f(0.0f, 0.0f, 0.0f);
for (int n = 0; n < nPoints; n += 3) {
IJ.showStatus("Calculating surface area...");
final Point3f point0 = points.get(n);
final Point3f point1 = points.get(n + 1);
final Point3f point2 = points.get(n + 2);
// TODO reject triangle and continue if it is flush
// with a cut face / image side
// area of triangle is half magnitude
// of cross product of 2 edge vectors
Point3f cp = Vectors.crossProduct(point0, point1, point2);
final double deltaArea = 0.5 * cp.distance(origin);
sumArea += deltaArea;
}
return sumArea;
}
}
| true | true | public void run(String arg) {
if (!ImageCheck.checkEnvironment())
return;
ImagePlus imp = IJ.getImage();
if (null == imp) {
IJ.noImage();
return;
}
int threshold = 128;
ImageCheck ic = new ImageCheck();
if (ic.isBinary(imp)) {
threshold = 128;
} else if (imp.getBitDepth() == 8) {
ThresholdMinConn tmc = new ThresholdMinConn();
threshold = imp.getProcessor().getAutoThreshold(
tmc.getStackHistogram(imp));
} else {
IJ.error("Isosurface", "Image type not supported");
return;
}
GenericDialog gd = new GenericDialog("Options");
gd.addNumericField("Resampling", 6, 0);
gd.addNumericField("Threshold", threshold, 0);
gd.addCheckbox("Show surface", true);
gd.addHelp("http://bonej.org/isosurface");
gd.showDialog();
int resamplingF = (int) Math.floor(gd.getNextNumber());
threshold = (int) Math.floor(gd.getNextNumber());
boolean doSurfaceRendering = gd.getNextBoolean();
if (gd.wasCanceled())
return;
final boolean[] channels = { true, false, false };
MCTriangulator mct = new MCTriangulator();
List<Point3f> points = mct.getTriangles(imp, threshold, channels,
resamplingF);
IJ.log("Isosurface contains " + (points.size() / 3) + " triangles");
ResultInserter ri = ResultInserter.getInstance();
double area = getSurfaceArea(points);
ri.setResultInRow(imp, "BS (" + imp.getCalibration().getUnits() + "²)",
area);
ri.updateTable();
if (points.size() == 0) {
IJ.error("Isosurface contains no points");
return;
}
if (doSurfaceRendering) {
renderSurface(points, "Surface of " + imp.getTitle());
}
points.clear();
return;
}
| public void run(String arg) {
if (!ImageCheck.checkEnvironment())
return;
ImagePlus imp = IJ.getImage();
if (null == imp) {
IJ.noImage();
return;
}
int threshold = 128;
ImageCheck ic = new ImageCheck();
if (ic.isBinary(imp)) {
threshold = 128;
} else if (imp.getBitDepth() == 8) {
ThresholdMinConn tmc = new ThresholdMinConn();
threshold = imp.getProcessor().getAutoThreshold(
tmc.getStackHistogram(imp));
} else {
IJ.error("Isosurface", "Image type not supported");
return;
}
GenericDialog gd = new GenericDialog("Options");
gd.addNumericField("Resampling", 6, 0);
gd.addNumericField("Threshold", threshold, 0);
gd.addCheckbox("Show surface", true);
gd.addHelp("http://bonej.org/isosurface");
gd.showDialog();
int resamplingF = (int) Math.floor(gd.getNextNumber());
threshold = (int) Math.floor(gd.getNextNumber());
boolean doSurfaceRendering = gd.getNextBoolean();
if (gd.wasCanceled())
return;
final boolean[] channels = { true, false, false };
MCTriangulator mct = new MCTriangulator();
List<Point3f> points = mct.getTriangles(imp, threshold, channels,
resamplingF);
IJ.log("Isosurface contains " + (points.size() / 3) + " triangles");
ResultInserter ri = ResultInserter.getInstance();
double area = getSurfaceArea(points);
ri.setResultInRow(imp, "BS (" + imp.getCalibration().getUnits() + "²)",
area);
ri.updateTable();
if (points.size() == 0) {
IJ.error("Isosurface contains no points");
return;
}
if (doSurfaceRendering) {
renderSurface(points, "Surface of " + imp.getTitle());
}
return;
}
|
diff --git a/samples/src/main/java/Main.java b/samples/src/main/java/Main.java
index 4087124..4647e53 100644
--- a/samples/src/main/java/Main.java
+++ b/samples/src/main/java/Main.java
@@ -1,19 +1,19 @@
import pojos.Contact;
import pojos.ContactBuilder;
public class Main {
public static void main(String[] args) {
// Build a single contact
Contact james = new ContactBuilder()
.withName("James Bond")
.withEmail("007@secretservice.org")
.build();
- // Build 100 contacts with one of the given names and no email
+ // Build 100 contacts each with one of the given names and no email
Contact[] someContacts = new ContactBuilder()
.withNameFrom("Alice", "Bob", "Charly")
.buildArray( 100);
}
}
| true | true | public static void main(String[] args) {
// Build a single contact
Contact james = new ContactBuilder()
.withName("James Bond")
.withEmail("007@secretservice.org")
.build();
// Build 100 contacts with one of the given names and no email
Contact[] someContacts = new ContactBuilder()
.withNameFrom("Alice", "Bob", "Charly")
.buildArray( 100);
}
| public static void main(String[] args) {
// Build a single contact
Contact james = new ContactBuilder()
.withName("James Bond")
.withEmail("007@secretservice.org")
.build();
// Build 100 contacts each with one of the given names and no email
Contact[] someContacts = new ContactBuilder()
.withNameFrom("Alice", "Bob", "Charly")
.buildArray( 100);
}
|
diff --git a/DataExtractionOSM/src/net/osmand/data/index/WikiIndexer.java b/DataExtractionOSM/src/net/osmand/data/index/WikiIndexer.java
index 9b17e2d9..9c0fee52 100644
--- a/DataExtractionOSM/src/net/osmand/data/index/WikiIndexer.java
+++ b/DataExtractionOSM/src/net/osmand/data/index/WikiIndexer.java
@@ -1,518 +1,518 @@
package net.osmand.data.index;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.sql.SQLException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.apache.commons.logging.Log;
import org.apache.tools.bzip2.CBZip2InputStream;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import net.osmand.Algoritms;
import net.osmand.LogUtil;
import net.osmand.Version;
import net.osmand.data.preparation.IndexCreator;
import net.osmand.impl.ConsoleProgressImplementation;
public class WikiIndexer {
private static final Log log = LogUtil.getLog(WikiIndexer.class);
private final File srcPath;
private final File workPath;
private final File targetPath;
public static class WikiIndexerException extends Exception {
private static final long serialVersionUID = 1L;
public WikiIndexerException(String name) {
super(name);
}
public WikiIndexerException(String string, Exception e) {
super(string, e);
}
}
public WikiIndexer(File srcPath, File targetPath, File workPath) {
this.srcPath = srcPath;
this.targetPath = targetPath;
this.workPath = workPath;
}
public static void main(String[] args) {
try {
File srcPath = extractDirectory(args, 0);
File targetPath = extractDirectory(args, 1);
File workPath = extractDirectory(args, 2);
WikiIndexer wikiIndexer = new WikiIndexer(srcPath, targetPath, workPath);
wikiIndexer.run();
} catch (WikiIndexerException e) {
log.error(e.getMessage());
}
}
private static File extractDirectory(String[] args, int ind) throws WikiIndexerException {
if (args.length <= ind) {
throw new WikiIndexerException("Usage: WikiIndexer src_directory target_directory work_directory [--description={full|normal|minimum}]" + " missing " + (ind + 1));
} else {
File fs = new File(args[ind]);
fs.mkdir();
if(!fs.exists() || !fs.isDirectory()) {
throw new WikiIndexerException("Specified directory doesn't exist : " + args[ind]);
}
return fs;
}
}
public void run() {
File[] listFiles = srcPath.listFiles();
for(File f : listFiles) {
try {
if (f.isFile() && (f.getName().endsWith(".xml") || f.getName().endsWith(".xml.bz2"))) {
log.info("About to process " + f.getName());
File outFile = process(f);
if (outFile != null) {
IndexCreator ic = new IndexCreator(workPath);
ic.setIndexPOI(true);
ic.setIndexMap(false);
ic.setIndexTransport(false);
ic.setIndexAddress(false);
ic.generateIndexes(outFile, new ConsoleProgressImplementation(3), null, null, null, log);
// final step
new File(workPath, ic.getMapFileName()).renameTo(new File(targetPath, ic.getMapFileName()));
}
}
} catch (WikiIndexerException e) {
log.error("Error processing "+f.getName(), e);
} catch (RuntimeException e) {
log.error("Error processing "+f.getName(), e);
} catch (IOException e) {
log.error("Error processing "+f.getName(), e);
} catch (SAXException e) {
log.error("Error processing "+f.getName(), e);
} catch (SQLException e) {
log.error("Error processing "+f.getName(), e);
} catch (InterruptedException e) {
log.error("Error processing "+f.getName(), e);
}
}
}
protected File process(File f) throws WikiIndexerException {
InputStream fi = null;
BufferedWriter out = null;
try {
int in = f.getName().indexOf('.');
File osmOut = new File(workPath, f.getName().substring(0, in) + ".osm");
fi = new BufferedInputStream(new FileInputStream(f));
InputStream progressStream = fi;
if(f.getName().endsWith(".bz2")){
if (fi.read() != 'B' || fi.read() != 'Z') {
throw new RuntimeException("The source stream must start with the characters BZ if it is to be read as a BZip2 stream."); //$NON-NLS-1$
} else {
fi = new CBZip2InputStream(fi);
}
}
ConsoleProgressImplementation progress = new ConsoleProgressImplementation();
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(osmOut), "UTF-8"));
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
WikiOsmHandler wikiOsmHandler = new WikiOsmHandler(saxParser, out, progress, progressStream);
saxParser.parse(fi, wikiOsmHandler);
if(wikiOsmHandler.getCount() < 1){
return null;
}
return osmOut;
} catch (ParserConfigurationException e) {
throw new WikiIndexerException("Parse exception", e);
} catch (SAXException e) {
throw new WikiIndexerException("Parse exception", e);
} catch (IOException e) {
throw new WikiIndexerException("Parse exception", e);
} catch (XMLStreamException e) {
throw new WikiIndexerException("Parse exception", e);
} finally {
Algoritms.closeStream(out);
Algoritms.closeStream(fi);
}
}
public class WikiOsmHandler extends DefaultHandler {
long id = 1;
private final SAXParser saxParser;
private boolean page = false;
private StringBuilder ctext = null;
private StringBuilder title = new StringBuilder();
private StringBuilder text = new StringBuilder();
private final ConsoleProgressImplementation progress;
private final InputStream progIS;
private XMLStreamWriter streamWriter;
WikiOsmHandler(SAXParser saxParser, BufferedWriter outOsm, ConsoleProgressImplementation progress, InputStream progIS) throws IOException, XMLStreamException {
this.saxParser = saxParser;
this.progress = progress;
this.progIS = progIS;
XMLOutputFactory xof = XMLOutputFactory.newInstance();
streamWriter = xof.createXMLStreamWriter(outOsm);
streamWriter.writeStartDocument();
streamWriter.writeCharacters("\n");
streamWriter.writeStartElement("osm");
streamWriter.writeAttribute("version", "0.6");
streamWriter.writeAttribute("generator", Version.APP_MAP_CREATOR_VERSION);
progress.startTask("Parse wiki xml", progIS.available());
}
public int getCount() {
return (int) (id - 1);
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
String name = saxParser.isNamespaceAware() ? localName : qName;
if (!page) {
page = name.equals("page");
} else {
if(name.equals("title")) {
title.setLength(0);
ctext = title;
} else if(name.equals("text")) {
text.setLength(0);
ctext = text;
}
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (page) {
if(ctext != null) {
ctext.append(ch, start, length);
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
String name = saxParser.isNamespaceAware() ? localName : qName;
try {
if (page) {
if(name.equals("page")) {
page = false;
progress.remaining(progIS.available());
} else if(name.equals("title")) {
ctext = null;
} else if(name.equals("text")) {
analyzeTextForGeoInfo();
ctext = null;
}
}
} catch (IOException e) {
throw new SAXException(e);
} catch (XMLStreamException e) {
throw new SAXException(e);
}
}
private String readProperty(String prop, int s, int e){
int res = -1;
for (int i = s; i < e - prop.length(); i++) {
if(prop.charAt(0) == text.charAt(i)) {
boolean neq = false;
for (int j = 0; j < prop.length(); j++) {
if(prop.charAt(j) != text.charAt(i + j)) {
neq = true;
break;
}
}
if (!neq) {
res = i + prop.length();
break;
}
}
}
if(res == -1){
return null;
}
int sr = -1;
int se = e;
for (int i = res; i < e; i++) {
if (text.charAt(i) == '|') {
se = i;
break;
}
if (text.charAt(i) == '=') {
sr = i + 1;
}
}
if(sr != -1) {
String result = text.substring(sr, se);
int commSt = result.indexOf("<!--");
if(commSt != -1) {
int commEnd = result.indexOf("-->");
if(commEnd == -1){
commEnd = result.length();
}
return (result.substring(0, commSt) + result.substring(commEnd)).trim();
}
return result.trim();
}
return null;
}
private float zeroParseFloat(String s) {
return s == null || s.length() == 0 ? 0 : Float.parseFloat(s);
}
private int findOpenBrackets(int i) {
int h = text.indexOf("{{", i);
boolean check = true;
while(check){
int startComment = text.indexOf("<!--", i);
check = false;
if (startComment != -1 && startComment < h) {
i = text.indexOf("-->", startComment);
h = text.indexOf("{{", i);
check = true;
}
}
return h;
}
private int findClosedBrackets(int i){
if(i == -1){
return -1;
}
int stack = 1;
int h = text.indexOf("{{", i+2);
int e = text.indexOf("}}", i+2);
while(stack != 0 && e != -1) {
if(h!= -1 && h<e){
i = h;
stack++;
} else {
i = e;
stack--;
}
if(stack != 0) {
h = text.indexOf("{{", i+2);
e = text.indexOf("}}", i+2);
}
}
if(stack == 0){
return e;
}
return -1;
}
private void analyzeTextForGeoInfo() throws XMLStreamException {
// fast precheck
if(title.toString().endsWith("/doc") || title.toString().startsWith("Шаблон:")) {
// Looks as template article no information in it
return;
}
int ls = text.indexOf("lat_dir");
if(ls != -1 && text.charAt(ls + 1 + "lat_dir".length()) != '|') {
float lat = 0;
float lon = 0;
String subcategory = "";
StringBuilder description = new StringBuilder();
int h = findOpenBrackets(0);
int e = findClosedBrackets(h);
// 1. Find main header section {{ ... lat, lon }}
while (h != -1 && e != -1) {
String lat_dir = readProperty("lat_dir", h, e);
// continue if nothing was found
if (lat_dir != null) {
break;
}
h = findOpenBrackets(e);
e = findClosedBrackets(h);
}
if (h == -1 || e == -1) {
return;
}
// 2. Parse lat lon
try {
String lat_dir = readProperty("lat_dir", h, e);
String lon_dir = readProperty("lon_dir", h, e);
String lat_dg = readProperty("lat_deg", h, e);
String lon_dg = readProperty("lon_deg", h, e);
if(lon_dg == null || lat_dg == null || lat_dg.length() == 0 || lon_dg.length() == 0){
return;
}
float lat_deg = Float.parseFloat(lat_dg);
float lon_deg = Float.parseFloat(lon_dg);
float lat_min = zeroParseFloat(readProperty("lat_min", h, e));
float lon_min = zeroParseFloat(readProperty("lon_min", h, e));
float lat_sec = zeroParseFloat(readProperty("lat_sec", h, e));
float lon_sec = zeroParseFloat(readProperty("lon_sec", h, e));
lat = (("S".equals(lat_dir))? -1 : 1) * (lat_deg + (lat_min + lat_sec/60)/60);
- lon = (("E".equals(lon_dir))? -1 : 1) * (lon_deg + (lon_min + lon_sec/60)/60);
+ lon = (("W".equals(lon_dir))? -1 : 1) * (lon_deg + (lon_min + lon_sec/60)/60);
} catch (RuntimeException es) {
log.error("Article " + title, es);
return;
}
// 3. Parse main subcategory name
for (int j = h + 2; j < e; j++) {
if (Character.isWhitespace(text.charAt(j)) || text.charAt(j) == '|') {
subcategory = text.substring(h + 2, j).trim();
break;
}
}
// Special case
// 4. Parse main subcategory name
processDescription(description, e + 3);
if(description.length() > 0) {
writeNode(lat, lon, subcategory, description);
}
}
}
private int checkAndParse(int i, String start, String end, StringBuilder d, boolean add){
if(text.charAt(i) != start.charAt(0)) {
return -1;
}
for (int j = 1 ; j < start.length(); j++) {
if(text.charAt(i + j) != start.charAt(j)){
return -1;
}
}
int st = i+start.length();
int en = text.length();
boolean colon = false;
for (int j = i + start.length(); j < text.length(); j++) {
if (text.charAt(j) == '|') {
st = j + 1;
if(colon){
// Special case to prevent adding
// [[File:av.png|thumb|220|220]]
add = false;
}
} else if (j + end.length() <= text.length()) {
boolean eq = true;
if (text.charAt(j) == ':') {
colon = true;
}
for (int k = 0; k < end.length(); k++) {
if (text.charAt(j + k) != end.charAt(k)) {
eq = false;
break;
}
}
if (eq) {
en = j;
break;
}
}
}
if(add){
d.append(text, st, en);
}
return en + end.length();
}
private void processDescription(StringBuilder description, int start) {
for (int j = start ; j < text.length();) {
if (text.charAt(j) == '=' && text.charAt(j+1) == '=') {
break;
} else if (text.charAt(j) == '\n' && j - start > 2048) {
break;
} else {
int r = -1;
if(r == -1) {
r = checkAndParse(j, "<ref", "</ref>", description, false);
}
if (r == -1) {
r = checkAndParse(j, "[[", "]]", description, true);
}
if(r == -1) {
r = checkAndParse(j, "{{", "}}", description, true);
}
if(r == -1) {
r = checkAndParse(j, "''", "''", description,true);
}
if(r == -1) {
description.append(text.charAt(j));
j++;
} else {
j = r;
}
}
}
}
private void writeNode(double lat, double lon, String subcategory, StringBuilder description) throws XMLStreamException {
streamWriter.writeCharacters("\n");
streamWriter.writeStartElement("node");
streamWriter.writeAttribute("id", "-" + id++);
streamWriter.writeAttribute("lat", lat+"");
streamWriter.writeAttribute("lon", lon+"");
streamWriter.writeCharacters("\n ");
streamWriter.writeStartElement("tag");
streamWriter.writeAttribute("k", "name");
streamWriter.writeAttribute("v", title.toString());
streamWriter.writeEndElement();
streamWriter.writeCharacters("\n ");
streamWriter.writeStartElement("tag");
streamWriter.writeAttribute("k", "osmwiki");
streamWriter.writeAttribute("v", subcategory);
streamWriter.writeEndElement();
streamWriter.writeCharacters("\n ");
streamWriter.writeStartElement("tag");
streamWriter.writeAttribute("k", "description");
streamWriter.writeAttribute("v", description.toString().trim());
streamWriter.writeEndElement();
streamWriter.writeEndElement();
streamWriter.writeCharacters("\n");
}
@Override
public void endDocument() throws SAXException {
try {
streamWriter.writeEndElement();
streamWriter.writeCharacters("\n");
streamWriter.writeEndDocument();
} catch (XMLStreamException e) {
throw new SAXException(e);
}
}
}
}
| true | true | private void analyzeTextForGeoInfo() throws XMLStreamException {
// fast precheck
if(title.toString().endsWith("/doc") || title.toString().startsWith("Шаблон:")) {
// Looks as template article no information in it
return;
}
int ls = text.indexOf("lat_dir");
if(ls != -1 && text.charAt(ls + 1 + "lat_dir".length()) != '|') {
float lat = 0;
float lon = 0;
String subcategory = "";
StringBuilder description = new StringBuilder();
int h = findOpenBrackets(0);
int e = findClosedBrackets(h);
// 1. Find main header section {{ ... lat, lon }}
while (h != -1 && e != -1) {
String lat_dir = readProperty("lat_dir", h, e);
// continue if nothing was found
if (lat_dir != null) {
break;
}
h = findOpenBrackets(e);
e = findClosedBrackets(h);
}
if (h == -1 || e == -1) {
return;
}
// 2. Parse lat lon
try {
String lat_dir = readProperty("lat_dir", h, e);
String lon_dir = readProperty("lon_dir", h, e);
String lat_dg = readProperty("lat_deg", h, e);
String lon_dg = readProperty("lon_deg", h, e);
if(lon_dg == null || lat_dg == null || lat_dg.length() == 0 || lon_dg.length() == 0){
return;
}
float lat_deg = Float.parseFloat(lat_dg);
float lon_deg = Float.parseFloat(lon_dg);
float lat_min = zeroParseFloat(readProperty("lat_min", h, e));
float lon_min = zeroParseFloat(readProperty("lon_min", h, e));
float lat_sec = zeroParseFloat(readProperty("lat_sec", h, e));
float lon_sec = zeroParseFloat(readProperty("lon_sec", h, e));
lat = (("S".equals(lat_dir))? -1 : 1) * (lat_deg + (lat_min + lat_sec/60)/60);
lon = (("E".equals(lon_dir))? -1 : 1) * (lon_deg + (lon_min + lon_sec/60)/60);
} catch (RuntimeException es) {
log.error("Article " + title, es);
return;
}
// 3. Parse main subcategory name
for (int j = h + 2; j < e; j++) {
if (Character.isWhitespace(text.charAt(j)) || text.charAt(j) == '|') {
subcategory = text.substring(h + 2, j).trim();
break;
}
}
// Special case
// 4. Parse main subcategory name
processDescription(description, e + 3);
if(description.length() > 0) {
writeNode(lat, lon, subcategory, description);
}
}
}
| private void analyzeTextForGeoInfo() throws XMLStreamException {
// fast precheck
if(title.toString().endsWith("/doc") || title.toString().startsWith("Шаблон:")) {
// Looks as template article no information in it
return;
}
int ls = text.indexOf("lat_dir");
if(ls != -1 && text.charAt(ls + 1 + "lat_dir".length()) != '|') {
float lat = 0;
float lon = 0;
String subcategory = "";
StringBuilder description = new StringBuilder();
int h = findOpenBrackets(0);
int e = findClosedBrackets(h);
// 1. Find main header section {{ ... lat, lon }}
while (h != -1 && e != -1) {
String lat_dir = readProperty("lat_dir", h, e);
// continue if nothing was found
if (lat_dir != null) {
break;
}
h = findOpenBrackets(e);
e = findClosedBrackets(h);
}
if (h == -1 || e == -1) {
return;
}
// 2. Parse lat lon
try {
String lat_dir = readProperty("lat_dir", h, e);
String lon_dir = readProperty("lon_dir", h, e);
String lat_dg = readProperty("lat_deg", h, e);
String lon_dg = readProperty("lon_deg", h, e);
if(lon_dg == null || lat_dg == null || lat_dg.length() == 0 || lon_dg.length() == 0){
return;
}
float lat_deg = Float.parseFloat(lat_dg);
float lon_deg = Float.parseFloat(lon_dg);
float lat_min = zeroParseFloat(readProperty("lat_min", h, e));
float lon_min = zeroParseFloat(readProperty("lon_min", h, e));
float lat_sec = zeroParseFloat(readProperty("lat_sec", h, e));
float lon_sec = zeroParseFloat(readProperty("lon_sec", h, e));
lat = (("S".equals(lat_dir))? -1 : 1) * (lat_deg + (lat_min + lat_sec/60)/60);
lon = (("W".equals(lon_dir))? -1 : 1) * (lon_deg + (lon_min + lon_sec/60)/60);
} catch (RuntimeException es) {
log.error("Article " + title, es);
return;
}
// 3. Parse main subcategory name
for (int j = h + 2; j < e; j++) {
if (Character.isWhitespace(text.charAt(j)) || text.charAt(j) == '|') {
subcategory = text.substring(h + 2, j).trim();
break;
}
}
// Special case
// 4. Parse main subcategory name
processDescription(description, e + 3);
if(description.length() > 0) {
writeNode(lat, lon, subcategory, description);
}
}
}
|
diff --git a/src/pl/edu/pw/gis/Cli.java b/src/pl/edu/pw/gis/Cli.java
index 3bd9de7..b45d7fc 100644
--- a/src/pl/edu/pw/gis/Cli.java
+++ b/src/pl/edu/pw/gis/Cli.java
@@ -1,155 +1,164 @@
package pl.edu.pw.gis;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class Cli {
/**
* Entry point for Command Line interface
*
* @param args
*/
public static void main(String[] args) {
Settings settings = parseCliArgs(args);
if (settings == null) {
// cannot go on like that. no settings!
HelpFormatter formatter = new HelpFormatter();
formatter.setWidth(160);
// aaargh, cannot print on stderr...
formatter.printHelp("gis.jar", buildCliOptions());
System.exit(1);
}
// we got a nice settings object. let's read the file into some graph
// object.
RunnableFuture<FindCentralsImpl> rf = new FutureTask<FindCentralsImpl>(
new FindCentralsImpl(settings));
ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(rf);
FindCentralsImpl result = null;
try {
if (settings.limit > 0)
result = rf.get(settings.limit, TimeUnit.SECONDS);
else
result = rf.get();
} catch (TimeoutException te) {
// computation did not made it...
rf.cancel(true);
System.out
.println("[!!] Timeout of "
+ settings.limit
+ "s reached. Computation abandoned. Progam will exit now.");
System.exit(3);
- } catch (Exception e) {
- System.out.println(e.getMessage());
+ }
+ catch (OutOfMemoryError e ) {
+ System.out.println("[!!] Program run out of memory, increase heap size (-Xmx size) and try again");
+ System.exit(4);
+ }
+ catch (Exception e) {
+ // Evil, unhandled exception!
+ System.out.println("[!!] System error: " + e.getMessage());
e.printStackTrace();
+ System.exit(666);
+ }
+ finally {
+ es.shutdown();
}
- es.shutdown();
if (!settings.graphx) {
ArrayList<String> printCentrals = new ArrayList<String>();
for (String s : result.getCentrals().getCentrals()) {
printCentrals.add(s);
}
Collections.sort(printCentrals, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return Integer.parseInt(o1) - Integer.parseInt(o2);
}
});
System.out.println("Centrals found: " + printCentrals);
} else {
System.err.println("Visual result presentation not implemented");
}
}
@SuppressWarnings("static-access")
private static Options buildCliOptions() {
// create Options object
Options options = new Options();
// add t option
options.addOption("l", true,
"time limit for finding solution, in seconds. Default: no limit");
options.addOption("v", false, "be more verbose");
options.addOption("t", false,
"launch accurate tests to verify the solution. May be time consuming!");
options.addOption("x", false, "present solution in graphical way");
options.addOption(OptionBuilder
.withArgName("radius")
.withDescription(
"max distance from any vertex to the closest central")
.hasArg().isRequired().withLongOpt("radius").create("r"));
options.addOption(OptionBuilder
.withArgName("limit")
.withDescription(
"time limit for finding solution, in seconds. Default: no limit")
.hasArg().withLongOpt("limit").create("l"));
options.addOption(OptionBuilder.withArgName("file")
.withDescription("path to GML file with graph definition")
.hasArg().isRequired().withType(String.class)
.withLongOpt("file").create("f"));
return options;
}
public static Settings parseCliArgs(String[] args) {
Options options = buildCliOptions();
Settings settings = null;
CommandLineParser parser = new GnuParser();
try {
// parse the command line arguments
CommandLine line = parser.parse(options, args);
settings = new Settings();
settings.filePath = line.getOptionValue("f");
settings.radius = Long.parseLong(line.getOptionValue("r"));
settings.verbose = line.hasOption("v");
settings.test = line.hasOption("t");
settings.graphx = line.hasOption("x");
settings.limit = -1;
if (line.hasOption("l")) {
settings.limit = Long.parseLong(line.getOptionValue("l"));
}
if (settings.verbose) {
System.out.println("[I] Input parameters parsed successfully:");
System.out.println("[I] r=" + settings.radius + ", file="
+ settings.filePath);
}
}
catch (ParseException exp) {
// oops, something went wrong
System.err.println("Error parsing input parameters: "
+ exp.getMessage());
settings = null;
} catch (NumberFormatException ex) {
System.err.println("Error parsing numbers: " + ex.getMessage());
settings = null;
}
return settings;
}
}
| false | true | public static void main(String[] args) {
Settings settings = parseCliArgs(args);
if (settings == null) {
// cannot go on like that. no settings!
HelpFormatter formatter = new HelpFormatter();
formatter.setWidth(160);
// aaargh, cannot print on stderr...
formatter.printHelp("gis.jar", buildCliOptions());
System.exit(1);
}
// we got a nice settings object. let's read the file into some graph
// object.
RunnableFuture<FindCentralsImpl> rf = new FutureTask<FindCentralsImpl>(
new FindCentralsImpl(settings));
ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(rf);
FindCentralsImpl result = null;
try {
if (settings.limit > 0)
result = rf.get(settings.limit, TimeUnit.SECONDS);
else
result = rf.get();
} catch (TimeoutException te) {
// computation did not made it...
rf.cancel(true);
System.out
.println("[!!] Timeout of "
+ settings.limit
+ "s reached. Computation abandoned. Progam will exit now.");
System.exit(3);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
es.shutdown();
if (!settings.graphx) {
ArrayList<String> printCentrals = new ArrayList<String>();
for (String s : result.getCentrals().getCentrals()) {
printCentrals.add(s);
}
Collections.sort(printCentrals, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return Integer.parseInt(o1) - Integer.parseInt(o2);
}
});
System.out.println("Centrals found: " + printCentrals);
} else {
System.err.println("Visual result presentation not implemented");
}
}
| public static void main(String[] args) {
Settings settings = parseCliArgs(args);
if (settings == null) {
// cannot go on like that. no settings!
HelpFormatter formatter = new HelpFormatter();
formatter.setWidth(160);
// aaargh, cannot print on stderr...
formatter.printHelp("gis.jar", buildCliOptions());
System.exit(1);
}
// we got a nice settings object. let's read the file into some graph
// object.
RunnableFuture<FindCentralsImpl> rf = new FutureTask<FindCentralsImpl>(
new FindCentralsImpl(settings));
ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(rf);
FindCentralsImpl result = null;
try {
if (settings.limit > 0)
result = rf.get(settings.limit, TimeUnit.SECONDS);
else
result = rf.get();
} catch (TimeoutException te) {
// computation did not made it...
rf.cancel(true);
System.out
.println("[!!] Timeout of "
+ settings.limit
+ "s reached. Computation abandoned. Progam will exit now.");
System.exit(3);
}
catch (OutOfMemoryError e ) {
System.out.println("[!!] Program run out of memory, increase heap size (-Xmx size) and try again");
System.exit(4);
}
catch (Exception e) {
// Evil, unhandled exception!
System.out.println("[!!] System error: " + e.getMessage());
e.printStackTrace();
System.exit(666);
}
finally {
es.shutdown();
}
if (!settings.graphx) {
ArrayList<String> printCentrals = new ArrayList<String>();
for (String s : result.getCentrals().getCentrals()) {
printCentrals.add(s);
}
Collections.sort(printCentrals, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return Integer.parseInt(o1) - Integer.parseInt(o2);
}
});
System.out.println("Centrals found: " + printCentrals);
} else {
System.err.println("Visual result presentation not implemented");
}
}
|
diff --git a/src/test/java/com/mathieubolla/processing/S3ProcessorTest.java b/src/test/java/com/mathieubolla/processing/S3ProcessorTest.java
index fe0b821..c5992fa 100644
--- a/src/test/java/com/mathieubolla/processing/S3ProcessorTest.java
+++ b/src/test/java/com/mathieubolla/processing/S3ProcessorTest.java
@@ -1,122 +1,121 @@
package com.mathieubolla.processing;
import static java.util.Arrays.asList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.io.File;
import java.util.Date;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicInteger;
import org.fest.assertions.Fail;
import org.junit.Before;
import org.junit.Test;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.mathieubolla.UploadConfiguration;
import com.mathieubolla.io.DirectoryScanner;
import com.mathieubolla.io.S3Scanner;
public class S3ProcessorTest {
S3Processor s3Processor;
S3Scanner mockS3Scanner;
DirectoryScanner mockDirectoryScanner;
AmazonS3 mockAmazonS3;
Queue<WorkUnit> mockQueue;
UploadConfiguration mockUploadConfiguration;
@Before
@SuppressWarnings("unchecked")
public void setup() {
mockS3Scanner = mock(S3Scanner.class);
mockDirectoryScanner = mock(DirectoryScanner.class);
mockAmazonS3 = mock(AmazonS3.class);
mockQueue = mock(Queue.class);
mockUploadConfiguration = mock(UploadConfiguration.class);
s3Processor = new S3Processor(mockAmazonS3, mockS3Scanner,
mockDirectoryScanner, mockQueue);
}
@Test
public void shouldAcceptDeleteCommands() {
UploadConfiguration mockUploadConfiguration = mock(UploadConfiguration.class);
S3ObjectSummary mockS3ObjectSummary = mock(S3ObjectSummary.class);
when(mockUploadConfiguration.getBucketName()).thenReturn("bucket");
when(mockS3Scanner.listObjects("bucket")).thenReturn(asList(mockS3ObjectSummary));
when(mockUploadConfiguration.isClearBucketBeforeUpload()).thenReturn(true);
s3Processor.clearBucket(mockUploadConfiguration);
verify(mockQueue).add(new DeleteUnit(mockS3ObjectSummary));
}
@Test
public void shouldRefuseDeleteCommands() {
S3ObjectSummary mockS3ObjectSummary = mock(S3ObjectSummary.class);
when(mockUploadConfiguration.getBucketName()).thenReturn("bucket");
when(mockS3Scanner.listObjects("bucket")).thenReturn(asList(mockS3ObjectSummary));
when(mockUploadConfiguration.isClearBucketBeforeUpload()).thenReturn(false);
s3Processor.clearBucket(mockUploadConfiguration);
verifyNoMoreInteractions(mockQueue);
}
@Test
public void shouldAcceptUploadCommands() {
Date mockDate = mock(Date.class);
UploadUnit mockUploadUnit = mock(UploadUnit.class);
File mockFile = mock(File.class);
File mockDirectory = mock(File.class);
when(mockDirectoryScanner.scanRegularFiles(mockDirectory)).thenReturn(asList(mockFile));
when(mockUploadConfiguration.getBaseDirectory()).thenReturn(mockDirectory);
when(mockUploadConfiguration.uploadUnitFor(mockFile, mockDate)).thenReturn(mockUploadUnit);
s3Processor.uploadBucket(mockUploadConfiguration, mockDate);
verify(mockQueue).add(mockUploadUnit);
}
@Test(timeout = 1000)
public void shouldProcessQueueWith10Threads() {
s3Processor = new S3Processor(mockAmazonS3, mockS3Scanner, mockDirectoryScanner, buildNDependentTasks(10));
s3Processor.processQueue();
}
private Queue<WorkUnit> buildNDependentTasks(int n) {
final AtomicInteger sharedLock = new AtomicInteger(0);
Queue<WorkUnit> queue = new LinkedBlockingDeque<WorkUnit>();
for (int i = 0; i < n; i++) {
queue.add(lockNThreadsTask(sharedLock, n));
}
return queue;
}
private WorkUnit lockNThreadsTask(final AtomicInteger lock, final int n) {
return new WorkUnit() {
@Override
public void doJob(AmazonS3 s3) {
synchronized (lock) {
- System.out.println(lock);
if(lock.incrementAndGet() < n) {
try {
lock.wait();
} catch (InterruptedException e) {
Fail.fail("Should not get interrupted");
}
} else {
lock.notifyAll();
}
}
}
};
}
}
| true | true | private WorkUnit lockNThreadsTask(final AtomicInteger lock, final int n) {
return new WorkUnit() {
@Override
public void doJob(AmazonS3 s3) {
synchronized (lock) {
System.out.println(lock);
if(lock.incrementAndGet() < n) {
try {
lock.wait();
} catch (InterruptedException e) {
Fail.fail("Should not get interrupted");
}
} else {
lock.notifyAll();
}
}
}
};
}
| private WorkUnit lockNThreadsTask(final AtomicInteger lock, final int n) {
return new WorkUnit() {
@Override
public void doJob(AmazonS3 s3) {
synchronized (lock) {
if(lock.incrementAndGet() < n) {
try {
lock.wait();
} catch (InterruptedException e) {
Fail.fail("Should not get interrupted");
}
} else {
lock.notifyAll();
}
}
}
};
}
|
diff --git a/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java b/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java
index 8289c9f46..b1f02e810 100644
--- a/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java
+++ b/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java
@@ -1,1596 +1,1595 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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 distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.loader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.lang.model.type.TypeKind;
import com.redhat.ceylon.compiler.java.util.Util;
import com.redhat.ceylon.compiler.loader.mirror.AnnotatedMirror;
import com.redhat.ceylon.compiler.loader.mirror.AnnotationMirror;
import com.redhat.ceylon.compiler.loader.mirror.ClassMirror;
import com.redhat.ceylon.compiler.loader.mirror.FieldMirror;
import com.redhat.ceylon.compiler.loader.mirror.MethodMirror;
import com.redhat.ceylon.compiler.loader.mirror.TypeMirror;
import com.redhat.ceylon.compiler.loader.mirror.TypeParameterMirror;
import com.redhat.ceylon.compiler.loader.mirror.VariableMirror;
import com.redhat.ceylon.compiler.loader.model.FieldValue;
import com.redhat.ceylon.compiler.loader.model.JavaBeanValue;
import com.redhat.ceylon.compiler.loader.model.JavaMethod;
import com.redhat.ceylon.compiler.loader.model.LazyClass;
import com.redhat.ceylon.compiler.loader.model.LazyContainer;
import com.redhat.ceylon.compiler.loader.model.LazyElement;
import com.redhat.ceylon.compiler.loader.model.LazyInterface;
import com.redhat.ceylon.compiler.loader.model.LazyMethod;
import com.redhat.ceylon.compiler.loader.model.LazyModule;
import com.redhat.ceylon.compiler.loader.model.LazyPackage;
import com.redhat.ceylon.compiler.loader.model.LazyValue;
import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager;
import com.redhat.ceylon.compiler.typechecker.io.VirtualFile;
import com.redhat.ceylon.compiler.typechecker.model.Annotation;
import com.redhat.ceylon.compiler.typechecker.model.BottomType;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Element;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.ModuleImport;
import com.redhat.ceylon.compiler.typechecker.model.Modules;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.model.UnknownType;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.model.ValueParameter;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
/**
* Abstract class of a model loader that can load a model from a compiled Java representation,
* while being agnostic of the reflection API used to load the compiled Java representation.
*
* @author Stéphane Épardaud <stef@epardaud.fr>
*/
public abstract class AbstractModelLoader implements ModelCompleter, ModelLoader {
private static final String CEYLON_CEYLON_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Ceylon";
private static final String CEYLON_MODULE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Module";
private static final String CEYLON_PACKAGE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Package";
private static final String CEYLON_IGNORE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Ignore";
private static final String CEYLON_CLASS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Class";
private static final String CEYLON_NAME_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Name";
private static final String CEYLON_SEQUENCED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Sequenced";
private static final String CEYLON_DEFAULTED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Defaulted";
private static final String CEYLON_SATISFIED_TYPES_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes";
private static final String CEYLON_CASE_TYPES_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CaseTypes";
private static final String CEYLON_TYPE_PARAMETERS = "com.redhat.ceylon.compiler.java.metadata.TypeParameters";
private static final String CEYLON_TYPE_INFO_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.TypeInfo";
public static final String CEYLON_ATTRIBUTE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Attribute";
public static final String CEYLON_OBJECT_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Object";
public static final String CEYLON_METHOD_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Method";
private static final String CEYLON_ANNOTATIONS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Annotations";
private static final TypeMirror OBJECT_TYPE = simpleObjectType("java.lang.Object");
private static final TypeMirror CEYLON_OBJECT_TYPE = simpleObjectType("ceylon.language.Object");
private static final TypeMirror CEYLON_IDENTIFIABLE_OBJECT_TYPE = simpleObjectType("ceylon.language.IdentifiableObject");
private static final TypeMirror CEYLON_EXCEPTION_TYPE = simpleObjectType("ceylon.language.Exception");;
private static final TypeMirror STRING_TYPE = simpleObjectType("java.lang.String");
private static final TypeMirror CEYLON_STRING_TYPE = simpleObjectType("ceylon.language.String");
private static final TypeMirror PRIM_BOOLEAN_TYPE = simpleObjectType("boolean", TypeKind.BOOLEAN);
private static final TypeMirror BOOLEAN_TYPE = simpleObjectType("java.lang.Boolean");
private static final TypeMirror CEYLON_BOOLEAN_TYPE = simpleObjectType("ceylon.language.Boolean");
private static final TypeMirror PRIM_BYTE_TYPE = simpleObjectType("byte", TypeKind.BYTE);
private static final TypeMirror BYTE_TYPE = simpleObjectType("java.lang.Byte");
private static final TypeMirror PRIM_SHORT_TYPE = simpleObjectType("short", TypeKind.SHORT);
private static final TypeMirror SHORT_TYPE = simpleObjectType("java.lang.Short");
private static final TypeMirror PRIM_INT_TYPE = simpleObjectType("int", TypeKind.INT);
private static final TypeMirror INTEGER_TYPE = simpleObjectType("java.lang.Integer");
private static final TypeMirror PRIM_LONG_TYPE = simpleObjectType("long", TypeKind.LONG);
private static final TypeMirror LONG_TYPE = simpleObjectType("java.lang.Long");
private static final TypeMirror CEYLON_INTEGER_TYPE = simpleObjectType("ceylon.language.Integer");
private static final TypeMirror PRIM_FLOAT_TYPE = simpleObjectType("float", TypeKind.FLOAT);
private static final TypeMirror FLOAT_TYPE = simpleObjectType("java.lang.Float");
private static final TypeMirror PRIM_DOUBLE_TYPE = simpleObjectType("double", TypeKind.DOUBLE);
private static final TypeMirror DOUBLE_TYPE = simpleObjectType("java.lang.Double");
private static final TypeMirror CEYLON_FLOAT_TYPE = simpleObjectType("ceylon.language.Float");
private static final TypeMirror PRIM_CHAR_TYPE = simpleObjectType("char", TypeKind.CHAR);
private static final TypeMirror CHARACTER_TYPE = simpleObjectType("java.lang.Character");
private static final TypeMirror CEYLON_CHARACTER_TYPE = simpleObjectType("ceylon.language.Character");
private static final TypeMirror CEYLON_ARRAY_TYPE = simpleObjectType("ceylon.language.Array");
private static TypeMirror simpleObjectType(String name) {
return new SimpleReflType(name, TypeKind.DECLARED);
}
private static TypeMirror simpleObjectType(String name, TypeKind kind) {
return new SimpleReflType(name, TypeKind.DECLARED);
}
protected Map<String, Declaration> declarationsByName = new HashMap<String, Declaration>();
protected Map<Package, Unit> unitsByPackage = new HashMap<Package, Unit>();
protected TypeParser typeParser;
protected Unit typeFactory;
protected final Set<String> loadedPackages = new HashSet<String>();
protected final Map<String,LazyPackage> packagesByName = new HashMap<String,LazyPackage>();
protected boolean packageDescriptorsNeedLoading = false;
protected boolean isBootstrap;
protected ModuleManager moduleManager;
protected Modules modules;
protected Map<String, ClassMirror> classMirrorCache = new HashMap<String, ClassMirror>();
/**
* Loads a given package, if required. This is mostly useful for the javac reflection impl.
*
* @param packageName the package name to load
* @param loadDeclarations true to load all the declarations in this package.
*/
public abstract void loadPackage(String packageName, boolean loadDeclarations);
/**
* Looks up a ClassMirror by name. Uses cached results, and caches the result of calling lookupNewClassMirror
* on cache misses.
*
* @param name the name of the Class to load
* @return a ClassMirror for the specified class, or null if not found.
*/
public final ClassMirror lookupClassMirror(String name){
// we use containsKey to be able to cache null results
if(classMirrorCache.containsKey(name))
return classMirrorCache.get(name);
ClassMirror mirror = lookupNewClassMirror(name);
// we even cache null results
classMirrorCache.put(name, mirror);
return mirror;
}
/**
* Looks up a ClassMirror by name. Called by lookupClassMirror on cache misses.
*
* @param name the name of the Class to load
* @return a ClassMirror for the specified class, or null if not found.
*/
public abstract ClassMirror lookupNewClassMirror(String name);
/**
* Adds the given module to the set of modules from which we can load classes.
*
* @param module the module
* @param artifact the module's artifact, if any. Can be null.
*/
public abstract void addModuleToClassPath(Module module, VirtualFile artifact);
/**
* Returns true if the given method is overriding an inherited method (from super class or interfaces).
*/
protected abstract boolean isOverridingMethod(MethodMirror methodMirror);
/**
* Logs a warning.
*/
protected abstract void logWarning(String message);
/**
* Logs a debug message.
*/
protected abstract void logVerbose(String message);
/**
* Logs an error
*/
protected abstract void logError(String message);
public void loadStandardModules(){
// set up the type factory
Module languageModule = findOrCreateModule("ceylon.language");
addModuleToClassPath(languageModule, null);
Package languagePackage = findOrCreatePackage(languageModule, "ceylon.language");
typeFactory.setPackage(languagePackage);
/*
* We start by loading java.lang and ceylon.language because we will need them no matter what.
*/
loadPackage("java.lang", false);
loadPackage("com.redhat.ceylon.compiler.java.metadata", false);
/*
* We do not load the ceylon.language module from class files if we're bootstrapping it
*/
if(!isBootstrap){
loadPackage("ceylon.language", true);
loadPackage("ceylon.language.descriptor", true);
}
}
enum ClassType {
ATTRIBUTE, METHOD, OBJECT, CLASS, INTERFACE;
}
private ClassMirror loadClass(String pkgName, String className) {
ClassMirror moduleClass = null;
try{
loadPackage(pkgName, false);
moduleClass = lookupClassMirror(className);
}catch(Exception x){
logVerbose("[Failed to complete class "+className+"]");
}
return moduleClass;
}
private Declaration convertToDeclaration(TypeMirror type, Scope scope, DeclarationType declarationType) {
String typeName;
switch(type.getKind()){
case VOID: typeName = "ceylon.language.Void"; break;
case BOOLEAN: typeName = "java.lang.Boolean"; break;
case BYTE: typeName = "java.lang.Byte"; break;
case CHAR: typeName = "java.lang.Character"; break;
case SHORT: typeName = "java.lang.Short"; break;
case INT: typeName = "java.lang.Integer"; break;
case LONG: typeName = "java.lang.Long"; break;
case FLOAT: typeName = "java.lang.Float"; break;
case DOUBLE: typeName = "java.lang.Double"; break;
case ARRAY:
TypeMirror componentType = type.getComponentType();
//throw new RuntimeException("Array type not implemented");
//UnionType[Empty|Sequence<Natural>] casetypes
// producedtypes.typearguments: typeparam[element]->type[natural]
TypeDeclaration emptyDecl = (TypeDeclaration)convertToDeclaration("ceylon.language.Empty", DeclarationType.TYPE);
TypeDeclaration sequenceDecl = (TypeDeclaration)convertToDeclaration("ceylon.language.Sequence", DeclarationType.TYPE);
UnionType unionType = new UnionType(typeFactory);
List<ProducedType> caseTypes = new ArrayList<ProducedType>(2);
caseTypes.add(emptyDecl.getType());
List<ProducedType> typeArguments = new ArrayList<ProducedType>(1);
typeArguments.add(getType(componentType, scope));
caseTypes.add(sequenceDecl.getProducedType(null, typeArguments));
unionType.setCaseTypes(caseTypes);
return unionType;
case DECLARED:
typeName = type.getQualifiedName();
break;
case TYPEVAR:
return safeLookupTypeParameter(scope, type.getQualifiedName());
case WILDCARD:
// FIXME: we shouldn't even get there, because if something contains a wildcard (Foo<?>) we erase it to
// IdentifiableObject, so this shouldn't be reachable.
typeName = "ceylon.language.Bottom";
break;
default:
throw new RuntimeException("Failed to handle type "+type);
}
return convertToDeclaration(typeName, declarationType);
}
protected Declaration convertToDeclaration(ClassMirror classMirror, DeclarationType declarationType) {
String className = classMirror.getQualifiedName();
ClassType type;
String prefix;
if(classMirror.isCeylonToplevelAttribute()){
type = ClassType.ATTRIBUTE;
prefix = "V";
}else if(classMirror.isCeylonToplevelMethod()){
type = ClassType.METHOD;
prefix = "V";
}else if(classMirror.isCeylonToplevelObject()){
type = ClassType.OBJECT;
// depends on which one we want
prefix = declarationType == DeclarationType.TYPE ? "C" : "V";
}else if(classMirror.isInterface()){
type = ClassType.INTERFACE;
prefix = "C";
}else{
type = ClassType.CLASS;
prefix = "C";
}
String key = prefix + className;
// see if we already have it
if(declarationsByName.containsKey(key)){
return declarationsByName.get(key);
}
// make it
Declaration decl = null;
List<Declaration> decls = new ArrayList<Declaration>(2);
switch(type){
case ATTRIBUTE:
decl = makeToplevelAttribute(classMirror);
break;
case METHOD:
decl = makeToplevelMethod(classMirror);
break;
case OBJECT:
// we first make a class
Declaration objectClassDecl = makeLazyClass(classMirror, null, null, true);
declarationsByName.put("C"+className, objectClassDecl);
decls.add(objectClassDecl);
// then we make a value for it
Declaration objectDecl = makeToplevelAttribute(classMirror);
declarationsByName.put("V"+className, objectDecl);
decls.add(objectDecl);
// which one did we want?
decl = declarationType == DeclarationType.TYPE ? objectClassDecl : objectDecl;
break;
case CLASS:
List<MethodMirror> constructors = getClassConstructors(classMirror);
if (!constructors.isEmpty()) {
if (constructors.size() > 1) {
// If the class has multiple constructors we make a copy of the class
// for each one (each with it's own single constructor) and make them
// a subclass of the original
Class supercls = makeLazyClass(classMirror, null, null, false);
supercls.setAbstraction(true);
for (MethodMirror constructor : constructors) {
Declaration subdecl = makeLazyClass(classMirror, supercls, constructor, false);
decls.add(subdecl);
}
decl = supercls;
} else {
MethodMirror constructor = constructors.get(0);
decl = makeLazyClass(classMirror, null, constructor, false);
}
} else {
decl = makeLazyClass(classMirror, null, null, false);
}
break;
case INTERFACE:
decl = makeLazyInterface(classMirror);
break;
}
// objects have special handling above
if(type != ClassType.OBJECT){
declarationsByName.put(key, decl);
decls.add(decl);
}
// find its module
String pkgName = classMirror.getPackage().getQualifiedName();
Module module = findOrCreateModule(pkgName);
LazyPackage pkg = findOrCreatePackage(module, pkgName);
// find/make its Unit
Unit unit = getCompiledUnit(pkg);
for(Declaration d : decls){
d.setShared(classMirror.isPublic());
// add it to its package if it's not an inner class
if(!classMirror.isInnerClass()){
pkg.addMember(d);
d.setContainer(pkg);
}
// add it to its Unit
d.setUnit(unit);
unit.getDeclarations().add(d);
}
return decl;
}
private List<MethodMirror> getClassConstructors(ClassMirror classMirror) {
LinkedList<MethodMirror> constructors = new LinkedList<MethodMirror>();
for(MethodMirror methodMirror : classMirror.getDirectMethods()){
// We skip members marked with @Ignore
if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(methodMirror.isConstructor()) {
constructors.add(methodMirror);
}
}
return constructors;
}
private Unit getCompiledUnit(LazyPackage pkg) {
Unit unit = unitsByPackage.get(pkg);
if(unit == null){
unit = new Unit();
unit.setPackage(pkg);
unitsByPackage.put(pkg, unit);
}
return unit;
}
private Declaration makeToplevelAttribute(ClassMirror classMirror) {
Value value = new LazyValue(classMirror, this);
return value;
}
private Declaration makeToplevelMethod(ClassMirror classMirror) {
LazyMethod method = new LazyMethod(classMirror, this);
return method;
}
private Class makeLazyClass(ClassMirror classMirror, Class superClass, MethodMirror constructor, boolean forTopLevelObject) {
return new LazyClass(classMirror, this, superClass, constructor, forTopLevelObject);
}
private Interface makeLazyInterface(ClassMirror classMirror) {
return new LazyInterface(classMirror, this);
}
public Declaration convertToDeclaration(String typeName, DeclarationType declarationType) {
if ("ceylon.language.Bottom".equals(typeName)) {
return new BottomType(typeFactory);
} else if ("java.lang.Exception".equals(typeName)) {
return convertToDeclaration("ceylon.language.Exception", declarationType);
}
ClassMirror classMirror = lookupClassMirror(typeName);
if (classMirror == null) {
Declaration languageModuleDeclaration = typeFactory.getLanguageModuleDeclaration(typeName);
if (languageModuleDeclaration != null) {
return languageModuleDeclaration;
}
throw new RuntimeException("Failed to resolve "+typeName);
}
return convertToDeclaration(classMirror, declarationType);
}
protected TypeParameter safeLookupTypeParameter(Scope scope, String name) {
TypeParameter param = lookupTypeParameter(scope, name);
if(param == null)
throw new RuntimeException("Type param "+name+" not found in "+scope);
return param;
}
private TypeParameter lookupTypeParameter(Scope scope, String name) {
if(scope instanceof Method){
Method m = (Method) scope;
for(TypeParameter param : m.getTypeParameters()){
if(param.getName().equals(name))
return param;
}
if (!m.isToplevel()) {
// look it up in its container
return lookupTypeParameter(scope.getContainer(), name);
} else {
// not found
return null;
}
}else if(scope instanceof ClassOrInterface){
ClassOrInterface klass = (ClassOrInterface) scope;
for(TypeParameter param : klass.getTypeParameters()){
if(param.getName().equals(name))
return param;
}
if (!klass.isToplevel()) {
// look it up in its container
return lookupTypeParameter(scope.getContainer(), name);
} else {
// not found
return null;
}
}else
throw new RuntimeException("Type param "+name+" lookup not supported for scope "+scope);
}
//
// Packages
public Package findPackage(String pkgName) {
pkgName = Util.quoteJavaKeywords(pkgName);
return packagesByName.get(pkgName);
}
public LazyPackage findOrCreatePackage(Module module, final String pkgName) {
String quotedPkgName = Util.quoteJavaKeywords(pkgName);
LazyPackage pkg = packagesByName.get(quotedPkgName);
if(pkg != null)
return pkg;
pkg = new LazyPackage(this);
packagesByName.put(quotedPkgName, pkg);
// FIXME: some refactoring needed
pkg.setName(pkgName == null ? Collections.<String>emptyList() : Arrays.asList(pkgName.split("\\.")));
// only bind it if we already have a module
if(module != null){
pkg.setModule(module);
module.getPackages().add(pkg);
}
// only load package descriptors for new packages after a certain phase
if(packageDescriptorsNeedLoading)
loadPackageDescriptor(pkg);
return pkg;
}
public void loadPackageDescriptors() {
for(Package pkg : packagesByName.values()){
loadPackageDescriptor(pkg);
}
packageDescriptorsNeedLoading = true;
}
private void loadPackageDescriptor(Package pkg) {
// let's not load package descriptors for Java modules
if(pkg.getModule() != null
&& ((LazyModule)pkg.getModule()).isJava()){
pkg.setShared(true);
return;
}
String quotedQualifiedName = Util.quoteJavaKeywords(pkg.getQualifiedNameString());
String className = quotedQualifiedName + ".$package";
logVerbose("[Trying to look up package from "+className+"]");
ClassMirror packageClass = loadClass(quotedQualifiedName, className);
if(packageClass == null){
logVerbose("[Failed to complete "+className+"]");
// missing: leave it private
return;
}
// did we compile it from source or class?
if(packageClass.isLoadedFromSource()){
// must have come from source, in which case we walked it and
// loaded its values already
logVerbose("[We are compiling the package "+className+"]");
return;
}
loadCompiledPackage(packageClass, pkg);
}
private void loadCompiledPackage(ClassMirror packageClass, Package pkg) {
String name = getAnnotationStringValue(packageClass, CEYLON_PACKAGE_ANNOTATION, "name");
Boolean shared = getAnnotationBooleanValue(packageClass, CEYLON_PACKAGE_ANNOTATION, "shared");
// FIXME: validate the name?
if(name == null || name.isEmpty()){
logWarning("Package class "+pkg.getQualifiedNameString()+" contains no name, ignoring it");
return;
}
if(shared == null){
logWarning("Package class "+pkg.getQualifiedNameString()+" contains no shared, ignoring it");
return;
}
pkg.setShared(shared);
}
//
// Modules
public Module findOrCreateModule(String pkgName) {
java.util.List<String> moduleName;
boolean isJava = false;
boolean defaultModule = false;
// FIXME: this is a rather simplistic view of the world
if(pkgName == null){
moduleName = Arrays.asList(Module.DEFAULT_MODULE_NAME);
defaultModule = true;
}else if(pkgName.startsWith("java.")){
moduleName = Arrays.asList("java");
isJava = true;
} else if(pkgName.startsWith("sun.")){
moduleName = Arrays.asList("sun");
isJava = true;
} else if(pkgName.startsWith("ceylon.language."))
moduleName = Arrays.asList("ceylon","language");
else
moduleName = Arrays.asList(pkgName.split("\\."));
Module module = moduleManager.getOrCreateModule(moduleName, null);
// make sure that when we load the ceylon language module we set it to where
// the typechecker will look for it
if(pkgName != null
&& pkgName.startsWith("ceylon.language.")
&& modules.getLanguageModule() == null){
modules.setLanguageModule(module);
}
if (module instanceof LazyModule) {
((LazyModule)module).setJava(isJava);
}
// FIXME: this can't be that easy.
module.setAvailable(true);
module.setDefault(defaultModule);
return module;
}
public Module loadCompiledModule(String pkgName) {
if(pkgName.isEmpty())
return null;
String moduleClassName = pkgName + ".module";
logVerbose("[Trying to look up module from "+moduleClassName+"]");
ClassMirror moduleClass = loadClass(pkgName, moduleClassName);
if(moduleClass != null){
// load its module annotation
Module module = loadCompiledModule(moduleClass, moduleClassName);
if(module != null)
return module;
}
// keep looking up
int lastDot = pkgName.lastIndexOf(".");
if(lastDot == -1)
return null;
String parentPackageName = pkgName.substring(0, lastDot);
return loadCompiledModule(parentPackageName);
}
private Module loadCompiledModule(ClassMirror moduleClass, String moduleClassName) {
String name = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, "name");
String version = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, "version");
// FIXME: validate the name?
if(name == null || name.isEmpty()){
logWarning("Module class "+moduleClassName+" contains no name, ignoring it");
return null;
}
if(version == null || version.isEmpty()){
logWarning("Module class "+moduleClassName+" contains no version, ignoring it");
return null;
}
Module module = moduleManager.getOrCreateModule(Arrays.asList(name.split("\\.")), version);
List<AnnotationMirror> imports = getAnnotationArrayValue(moduleClass, CEYLON_MODULE_ANNOTATION, "dependencies");
for (AnnotationMirror importAttribute : imports) {
String dependencyName = (String) importAttribute.getValue("name");
if (dependencyName != null) {
if (! dependencyName.equals("java")) {
String dependencyVersion = (String) importAttribute.getValue("version");
Module dependency = moduleManager.getOrCreateModule(ModuleManager.splitModuleName(dependencyName), dependencyVersion);
Boolean optionalVal = (Boolean) importAttribute.getValue("optional");
Boolean exportVal = (Boolean) importAttribute.getValue("export");
ModuleImport moduleImport = moduleManager.findImport(module, dependency);
if (moduleImport == null) {
boolean optional = optionalVal != null && optionalVal;
boolean export = exportVal != null && exportVal;
moduleImport = new ModuleImport(dependency, optional, export);
module.getImports().add(moduleImport);
}
}
}
}
module.setAvailable(true);
modules.getListOfModules().add(module);
Module languageModule = modules.getLanguageModule();
module.setLanguageModule(languageModule);
if(module != languageModule){
ModuleImport moduleImport = moduleManager.findImport(module, languageModule);
if (moduleImport == null) {
moduleImport = new ModuleImport(languageModule, false, false);
module.getImports().add(moduleImport);
}
}
return module;
}
//
// Utils for loading type info from the model
@SuppressWarnings("unchecked")
private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type, String field) {
return (List<T>) getAnnotationValue(mirror, type, field);
}
@SuppressWarnings("unchecked")
private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type) {
return (List<T>) getAnnotationValue(mirror, type);
}
private String getAnnotationStringValue(AnnotatedMirror mirror, String type) {
return getAnnotationStringValue(mirror, type, "value");
}
private String getAnnotationStringValue(AnnotatedMirror mirror, String type, String field) {
return (String) getAnnotationValue(mirror, type, field);
}
private Boolean getAnnotationBooleanValue(AnnotatedMirror mirror, String type, String field) {
return (Boolean) getAnnotationValue(mirror, type, field);
}
private Object getAnnotationValue(AnnotatedMirror mirror, String type) {
return getAnnotationValue(mirror, type, "value");
}
private Object getAnnotationValue(AnnotatedMirror mirror, String type, String fieldName) {
AnnotationMirror annotation = mirror.getAnnotation(type);
if(annotation != null){
return annotation.getValue(fieldName);
}
return null;
}
//
// ModelCompleter
@Override
public void complete(LazyInterface iface) {
complete(iface, iface.classMirror);
}
@Override
public void completeTypeParameters(LazyInterface iface) {
completeTypeParameters(iface, iface.classMirror);
}
@Override
public void complete(LazyClass klass) {
complete(klass, klass.classMirror);
}
@Override
public void completeTypeParameters(LazyClass klass) {
completeTypeParameters(klass, klass.classMirror);
}
private void completeTypeParameters(ClassOrInterface klass, ClassMirror classMirror) {
setTypeParameters(klass, classMirror);
}
private void complete(ClassOrInterface klass, ClassMirror classMirror) {
Map<MethodMirror, List<MethodMirror>> variables = new HashMap<MethodMirror, List<MethodMirror>>();
String qualifiedName = classMirror.getQualifiedName();
boolean isJava = qualifiedName.startsWith("java.");
boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null);
// Java classes with multiple constructors get turned into multiple Ceylon classes
// Here we get the specific constructor that was assigned to us (if any)
MethodMirror constructor = null;
if (klass instanceof LazyClass) {
constructor = ((LazyClass)klass).getConstructor();
}
// Turn a list of possibly overloaded methods into a map
// of lists that contain methods with the same name
Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>();
for(MethodMirror methodMirror : classMirror.getDirectMethods()){
// We skip members marked with @Ignore
if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(methodMirror.isStaticInit())
continue;
if(isCeylon && methodMirror.isStatic())
continue;
// FIXME: temporary, because some private classes from the jdk are
// referenced in private methods but not available
if(isJava && !methodMirror.isPublic())
continue;
String methodName = methodMirror.getName();
List<MethodMirror> homonyms = methods.get(methodName);
if (homonyms == null) {
homonyms = new LinkedList<MethodMirror>();
methods.put(methodName, homonyms);
}
homonyms.add(methodMirror);
}
// Add the methods
for(List<MethodMirror> methodMirrors : methods.values()){
boolean isOverloaded = methodMirrors.size() > 1;
boolean first = true;
for (MethodMirror methodMirror : methodMirrors) {
String methodName = methodMirror.getName();
if(methodMirror.isConstructor()) {
if (methodMirror == constructor) {
((Class)klass).setOverloaded(isOverloaded);
if(!(klass instanceof LazyClass) || !((LazyClass)klass).isTopLevelObjectType())
setParameters((Class)klass, methodMirror, isCeylon);
}
} else if(isGetter(methodMirror)) {
// simple attribute
addValue(klass, methodMirror, getJavaAttributeName(methodName));
} else if(isSetter(methodMirror)) {
// We skip setters for now and handle them later
variables.put(methodMirror, methodMirrors);
} else if(isHashAttribute(methodMirror)) {
// ERASURE
// Un-erasing 'hash' attribute from 'hashCode' method
addValue(klass, methodMirror, "hash");
} else if(isStringAttribute(methodMirror)) {
// ERASURE
// Un-erasing 'string' attribute from 'toString' method
addValue(klass, methodMirror, "string");
} else {
if (first && isOverloaded) {
// We create an extra "abstraction" method for overloaded methods
Method abstractionMethod = addMethod(klass, methodMirror, false, false);
abstractionMethod.setAbstraction(true);
abstractionMethod.setType(new UnknownType(typeFactory).getType());
first = false;
}
// normal method
addMethod(klass, methodMirror, isCeylon, isOverloaded);
}
}
}
for(FieldMirror fieldMirror : classMirror.getDirectFields()){
// We skip members marked with @Ignore
if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
- // FIXME: Skip static fields for now
- if(fieldMirror.isStatic())
+ if(isCeylon && fieldMirror.isStatic())
continue;
String name = fieldMirror.getName();
// skip the field if "we've already got one"
if(klass.getDirectMember(name, null) != null)
continue;
addValue(klass, fieldMirror);
}
// Now mark all Values for which Setters exist as variable
for(Entry<MethodMirror, List<MethodMirror>> setterEntry : variables.entrySet()){
MethodMirror setter = setterEntry.getKey();
String name = getJavaAttributeName(setter.getName());
Declaration decl = klass.getMember(name, null);
boolean foundGetter = false;
if (decl != null && decl instanceof Value) {
Value value = (Value)decl;
VariableMirror setterParam = setter.getParameters().get(0);
ProducedType paramType = obtainType(setterParam.getType(), setterParam, klass);
// only add the setter if it has exactly the same type as the getter
if(paramType.isExactly(value.getType())){
foundGetter = true;
value.setVariable(true);
if(decl instanceof JavaBeanValue)
((JavaBeanValue)decl).setSetterName(setter.getName());
}else
logWarning("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method");
}
if(!foundGetter){
// it was not a setter, it was a method, let's add it as such
addMethod(klass, setter, isCeylon, false);
}
}
klass.setStaticallyImportable(!isCeylon && (classMirror.isStatic() || (classMirror instanceof LazyClass)));
setExtendedType(klass, classMirror);
setSatisfiedTypes(klass, classMirror);
setCaseTypes(klass, classMirror);
fillRefinedDeclarations(klass);
addInnerClasses(klass, classMirror);
setAnnotations(klass, classMirror);
}
private void setAnnotations(Declaration decl, AnnotatedMirror classMirror) {
List<AnnotationMirror> annotations = getAnnotationArrayValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION);
if(annotations == null)
return;
for(AnnotationMirror annotation : annotations){
decl.getAnnotations().add(readModelAnnotation(annotation));
}
}
private Annotation readModelAnnotation(AnnotationMirror annotation) {
Annotation modelAnnotation = new Annotation();
modelAnnotation.setName((String) annotation.getValue());
@SuppressWarnings("unchecked")
List<String> arguments = (List<String>) annotation.getValue("arguments");
if(arguments != null){
modelAnnotation.getPositionalArguments().addAll(arguments);
}else{
@SuppressWarnings("unchecked")
List<AnnotationMirror> namedArguments = (List<AnnotationMirror>) annotation.getValue("namedArguments");
if(namedArguments != null){
for(AnnotationMirror namedArgument : namedArguments){
String argName = (String) namedArgument.getValue("name");
String argValue = (String) namedArgument.getValue("value");
modelAnnotation.getNamedArguments().put(argName, argValue);
}
}
}
return modelAnnotation;
}
private void addInnerClasses(ClassOrInterface klass, ClassMirror classMirror) {
for(ClassMirror innerClass : classMirror.getDirectInnerClasses()){
// We skip members marked with @Ignore
if(innerClass.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
Declaration innerDecl = convertToDeclaration(innerClass, DeclarationType.TYPE);
innerDecl.setContainer(klass);
// let's not trigger lazy-loading
((LazyContainer)klass).addMember(innerDecl);
}
}
private Method addMethod(ClassOrInterface klass, MethodMirror methodMirror, boolean isCeylon, boolean isOverloaded) {
JavaMethod method = new JavaMethod();
method.setContainer(klass);
method.setRealName(methodMirror.getName());
method.setName(Util.strip(methodMirror.getName()));
method.setUnit(klass.getUnit());
method.setOverloaded(isOverloaded);
setMethodOrValueFlags(klass, methodMirror, method);
// type params first
setTypeParameters(method, methodMirror);
// now its parameters
if(isEqualsMethod(methodMirror))
setEqualsParameters(method, methodMirror);
else
setParameters(method, methodMirror, isCeylon);
// and its return type
ProducedType type = obtainType(methodMirror.getReturnType(), methodMirror, method);
method.setType(type);
markUnboxed(method, methodMirror.getReturnType());
setAnnotations(method, methodMirror);
klass.getMembers().add(method);
return method;
}
private void fillRefinedDeclarations(ClassOrInterface klass) {
for(Declaration member : klass.getMembers()){
if(member.isActual()){
member.setRefinedDeclaration(findRefinedDeclaration(klass, member.getName(), getSignature(member)));
}
}
}
private List<ProducedType> getSignature(Declaration decl) {
List<ProducedType> result = null;
if (decl instanceof Functional) {
Functional func = (Functional)decl;
if (func.getParameterLists().size() > 0) {
List<Parameter> params = func.getParameterLists().get(0).getParameters();
result = new ArrayList<ProducedType>(params.size());
for (Parameter p : params) {
result.add(p.getType());
}
}
}
return result;
}
private Declaration findRefinedDeclaration(ClassOrInterface decl, String name, List<ProducedType> signature) {
Declaration refinedDeclaration = decl.getRefinedMember(name, signature);
if(refinedDeclaration == null)
throw new RuntimeException("Failed to find refined declaration for "+name);
return refinedDeclaration;
}
private boolean isGetter(MethodMirror methodMirror) {
String name = methodMirror.getName();
boolean matchesGet = name.length() > 3 && name.startsWith("get") && Character.isUpperCase(name.charAt(3));
boolean matchesIs = name.length() > 2 && name.startsWith("is") && Character.isUpperCase(name.charAt(2));
boolean hasNoParams = methodMirror.getParameters().size() == 0;
boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID);
return (matchesGet || matchesIs) && hasNoParams && hasNonVoidReturn;
}
private boolean isSetter(MethodMirror methodMirror) {
String name = methodMirror.getName();
boolean matchesSet = name.length() > 3 && name.startsWith("set") && Character.isUpperCase(name.charAt(3));
boolean hasOneParam = methodMirror.getParameters().size() == 1;
boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID);
return matchesSet && hasOneParam && hasVoidReturn;
}
private boolean isHashAttribute(MethodMirror methodMirror) {
String name = methodMirror.getName();
boolean matchesName = "hashCode".equals(name);
boolean hasNoParams = methodMirror.getParameters().size() == 0;
return matchesName && hasNoParams;
}
private boolean isStringAttribute(MethodMirror methodMirror) {
String name = methodMirror.getName();
boolean matchesName = "toString".equals(name);
boolean hasNoParams = methodMirror.getParameters().size() == 0;
return matchesName && hasNoParams;
}
private boolean isEqualsMethod(MethodMirror methodMirror) {
String name = methodMirror.getName();
if(!"equals".equals(name)
|| methodMirror.getParameters().size() != 1)
return false;
VariableMirror param = methodMirror.getParameters().get(0);
return sameType(param.getType(), OBJECT_TYPE);
}
private void setEqualsParameters(Method decl, MethodMirror methodMirror) {
ParameterList parameters = new ParameterList();
decl.addParameterList(parameters);
ValueParameter parameter = new ValueParameter();
parameter.setUnit(decl.getUnit());
parameter.setContainer((Scope) decl);
parameter.setName("that");
parameter.setType(getType(CEYLON_OBJECT_TYPE, decl));
parameter.setDeclaration((Declaration) decl);
parameters.getParameters().add(parameter);
}
private String getJavaAttributeName(String getterName) {
if (getterName.startsWith("get") || getterName.startsWith("set")) {
return getJavaBeanName(getterName.substring(3));
} else if (getterName.startsWith("is")) {
// Starts with "is"
return getJavaBeanName(getterName.substring(2));
} else {
throw new RuntimeException("Illegal java getter/setter name");
}
}
private String getJavaBeanName(String name) {
// See https://github.com/ceylon/ceylon-compiler/issues/340
// make it lowercase until the first non-uppercase
char[] newName = name.toCharArray();
for(int i=0;i<newName.length;i++){
char c = newName[i];
if(Character.isLowerCase(c)){
// if we had more than one upper-case, we leave the last uppercase: getURLDecoder -> urlDecoder
if(i > 1){
newName[i-1] = Character.toUpperCase(newName[i-1]);
}
break;
}
newName[i] = Character.toLowerCase(c);
}
return new String(newName);
}
private void addValue(ClassOrInterface klass, FieldMirror fieldMirror) {
// make sure it's a FieldValue so we can figure it out in the backend
Value value = new FieldValue();
value.setContainer(klass);
value.setName(fieldMirror.getName());
value.setUnit(klass.getUnit());
value.setShared(fieldMirror.isPublic() || fieldMirror.isProtected());
value.setProtectedVisibility(fieldMirror.isProtected());
value.setStaticallyImportable(fieldMirror.isStatic());
// field can't be abstract or interface, so not formal
// can we override fields? good question. Not really, but from an external point of view?
// FIXME: figure this out: (default)
// FIXME: for the same reason, can it be an overriding field? (actual)
value.setVariable(!fieldMirror.isFinal());
value.setType(obtainType(fieldMirror.getType(), fieldMirror, klass));
markUnboxed(value, fieldMirror.getType());
klass.getMembers().add(value);
}
private void addValue(ClassOrInterface klass, MethodMirror methodMirror, String methodName) {
JavaBeanValue value = new JavaBeanValue();
value.setGetterName(methodMirror.getName());
value.setContainer(klass);
value.setName(methodName);
value.setUnit(klass.getUnit());
setMethodOrValueFlags(klass, methodMirror, value);
value.setType(obtainType(methodMirror.getReturnType(), methodMirror, klass));
markUnboxed(value, methodMirror.getReturnType());
setAnnotations(value, methodMirror);
klass.getMembers().add(value);
}
private void setMethodOrValueFlags(ClassOrInterface klass, MethodMirror methodMirror, MethodOrValue decl) {
decl.setShared(methodMirror.isPublic() || methodMirror.isProtected());
decl.setProtectedVisibility(methodMirror.isProtected());
if(methodMirror.isAbstract() || klass instanceof Interface) {
decl.setFormal(true);
} else {
if (!methodMirror.isFinal()) {
decl.setDefault(true);
}
}
decl.setStaticallyImportable(methodMirror.isStatic());
if(isOverridingMethod(methodMirror)){
decl.setActual(true);
}
}
private void setExtendedType(ClassOrInterface klass, ClassMirror classMirror) {
// look at its super type
TypeMirror superClass = classMirror.getSuperclass();
ProducedType extendedType;
if(klass instanceof Interface){
// interfaces need to have their superclass set to Object
if(superClass == null || superClass.getKind() == TypeKind.NONE)
extendedType = getType(CEYLON_OBJECT_TYPE, klass);
else
extendedType = getType(superClass, klass);
}else{
String className = classMirror.getQualifiedName();
String superClassName = superClass == null ? null : superClass.getQualifiedName();
if(className.equals("ceylon.language.Void")){
// ceylon.language.Void has no super type
extendedType = null;
}else if(className.equals("java.lang.Object")){
// we pretend its superclass is something else, but note that in theory we shouldn't
// be seeing j.l.Object at all due to unerasure
extendedType = getType(CEYLON_IDENTIFIABLE_OBJECT_TYPE, klass);
}else if("java.lang.Exception".equals(superClassName)){
// we pretend that a subclass of j.l.Excpetion is really a subclass of c.l.Excpetion
extendedType = getType(CEYLON_EXCEPTION_TYPE, klass);
}else{
// read it from annotation first
String annotationSuperClassName = getAnnotationStringValue(classMirror, CEYLON_CLASS_ANNOTATION, "extendsType");
if(annotationSuperClassName != null && !annotationSuperClassName.isEmpty()){
extendedType = decodeType(annotationSuperClassName, klass);
}else{
// read it from the Java super type
// now deal with type erasure, avoid having Object as superclass
if("java.lang.Object".equals(superClassName)){
extendedType = getType(CEYLON_IDENTIFIABLE_OBJECT_TYPE, klass);
}else{
extendedType = getType(superClass, klass);
}
}
}
}
if(extendedType != null)
klass.setExtendedType(extendedType);
}
private void setParameters(Functional decl, MethodMirror methodMirror, boolean isCeylon) {
ParameterList parameters = new ParameterList();
decl.addParameterList(parameters);
for(VariableMirror paramMirror : methodMirror.getParameters()){
ValueParameter parameter = new ValueParameter();
parameter.setContainer((Scope) decl);
parameter.setUnit(((Element)decl).getUnit());
if(decl instanceof Class){
((Class)decl).getMembers().add(parameter);
}
String paramName = getAnnotationStringValue(paramMirror, CEYLON_NAME_ANNOTATION);
// use whatever param name we find as default
if(paramName == null)
paramName = paramMirror.getName();
parameter.setName(paramName);
TypeMirror typeMirror = paramMirror.getType();
ProducedType type = obtainType(typeMirror, paramMirror, (Scope) decl);
if(!isCeylon && !typeMirror.isPrimitive()){
// Java parameters are all optional unless primitives
ProducedType optionalType = typeFactory.getOptionalType(type);
optionalType.setUnderlyingType(type.getUnderlyingType());
type = optionalType;
}
parameter.setType(type );
if(paramMirror.getAnnotation(CEYLON_SEQUENCED_ANNOTATION) != null)
parameter.setSequenced(true);
if(paramMirror.getAnnotation(CEYLON_DEFAULTED_ANNOTATION) != null)
parameter.setDefaulted(true);
markUnboxed(parameter, paramMirror.getType());
parameter.setDeclaration((Declaration) decl);
parameters.getParameters().add(parameter);
}
}
private void markUnboxed(TypedDeclaration decl, TypeMirror type) {
boolean unboxed = false;
if(type.isPrimitive() || type.getKind() == TypeKind.ARRAY
|| sameType(type, STRING_TYPE)) {
unboxed = true;
}
decl.setUnboxed(unboxed);
}
@Override
public void complete(LazyValue value) {
MethodMirror meth = null;
for (MethodMirror m : value.classMirror.getDirectMethods()) {
// We skip members marked with @Ignore
if(m.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if (m.getName().equals(
Util.getGetterName(value.getName()))
&& m.isStatic() && m.getParameters().size() == 0) {
meth = m;
}
if (m.getName().equals(
Util.getSetterName(value.getName()))
&& m.isStatic() && m.getParameters().size() == 1) {
value.setVariable(true);
}
}
if(meth == null || meth.getReturnType() == null)
throw new RuntimeException("Failed to find toplevel attribute "+value.getName());
value.setType(obtainType(meth.getReturnType(), meth, null));
setAnnotations(value, meth);
markUnboxed(value, meth.getReturnType());
}
@Override
public void complete(LazyMethod method) {
MethodMirror meth = null;
String lookupName = Util.quoteIfJavaKeyword(method.getName());
for(MethodMirror m : method.classMirror.getDirectMethods()){
// We skip members marked with @Ignore
if(m.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(m.getName().equals(lookupName)){
meth = m;
break;
}
}
if(meth == null || meth.getReturnType() == null)
throw new RuntimeException("Failed to find toplevel method "+method.getName());
// type params first
setTypeParameters(method, meth);
// now its parameters
setParameters(method, meth, true /* toplevel methods are always Ceylon */);
method.setType(obtainType(meth.getReturnType(), meth, method));
markUnboxed(method, meth.getReturnType());
setAnnotations(method, meth);
}
//
// Satisfied Types
private List<String> getSatisfiedTypesFromAnnotations(AnnotatedMirror symbol) {
return getAnnotationArrayValue(symbol, CEYLON_SATISFIED_TYPES_ANNOTATION);
}
private void setSatisfiedTypes(ClassOrInterface klass, ClassMirror classMirror) {
List<String> satisfiedTypes = getSatisfiedTypesFromAnnotations(classMirror);
if(satisfiedTypes != null){
klass.getSatisfiedTypes().addAll(getTypesList(satisfiedTypes, klass));
}else{
for(TypeMirror iface : classMirror.getInterfaces()){
klass.getSatisfiedTypes().add(getType(iface, klass));
}
}
}
//
// Case Types
private List<String> getCaseTypesFromAnnotations(AnnotatedMirror symbol) {
return getAnnotationArrayValue(symbol, CEYLON_CASE_TYPES_ANNOTATION);
}
private void setCaseTypes(ClassOrInterface klass, ClassMirror classMirror) {
List<String> caseTypes = getCaseTypesFromAnnotations(classMirror);
if(caseTypes != null){
klass.setCaseTypes(getTypesList(caseTypes, klass));
}
}
private List<ProducedType> getTypesList(List<String> caseTypes, Scope scope) {
List<ProducedType> producedTypes = new LinkedList<ProducedType>();
for(String type : caseTypes){
producedTypes.add(decodeType(type, scope));
}
return producedTypes;
}
//
// Type parameters loading
@SuppressWarnings("unchecked")
private List<AnnotationMirror> getTypeParametersFromAnnotations(AnnotatedMirror symbol) {
return (List<AnnotationMirror>) getAnnotationValue(symbol, CEYLON_TYPE_PARAMETERS);
}
// from our annotation
@SuppressWarnings("deprecation")
private void setTypeParametersFromAnnotations(Scope scope, List<TypeParameter> params, List<AnnotationMirror> typeParameters) {
// We must first add every type param, before we resolve the bounds, which can
// refer to type params.
for(AnnotationMirror typeParam : typeParameters){
TypeParameter param = new TypeParameter();
param.setUnit(((Element)scope).getUnit());
param.setContainer(scope);
// let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface
if(scope instanceof LazyContainer)
((LazyContainer)scope).addMember(param);
else // must be a method
scope.getMembers().add(param);
param.setName((String)typeParam.getValue("value"));
param.setExtendedType(typeFactory.getVoidDeclaration().getType());
params.add(param);
String varianceName = (String) typeParam.getValue("variance");
if(varianceName != null){
if(varianceName.equals("IN")){
param.setContravariant(true);
}else if(varianceName.equals("OUT"))
param.setCovariant(true);
}
}
// Now all type params have been set, we can resolve the references parts
Iterator<TypeParameter> paramsIterator = params.iterator();
for(AnnotationMirror typeParam : typeParameters){
TypeParameter param = paramsIterator.next();
@SuppressWarnings("unchecked")
List<String> satisfiesAttribute = (List<String>)typeParam.getValue("satisfies");
if(satisfiesAttribute != null){
for (String satisfy : satisfiesAttribute) {
ProducedType satisfiesType = decodeType(satisfy, scope);
param.getSatisfiedTypes().add(satisfiesType);
}
}
}
}
// from java type info
@SuppressWarnings("deprecation")
private void setTypeParameters(Scope scope, List<TypeParameter> params, List<TypeParameterMirror> typeParameters) {
// We must first add every type param, before we resolve the bounds, which can
// refer to type params.
for(TypeParameterMirror typeParam : typeParameters){
TypeParameter param = new TypeParameter();
param.setUnit(((Element)scope).getUnit());
param.setContainer(scope);
// let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface
if(scope instanceof LazyContainer)
((LazyContainer)scope).addMember(param);
else // must be a method
scope.getMembers().add(param);
param.setName(typeParam.getName());
param.setExtendedType(typeFactory.getVoidDeclaration().getType());
params.add(param);
}
// Now all type params have been set, we can resolve the references parts
Iterator<TypeParameter> paramsIterator = params.iterator();
for(TypeParameterMirror typeParam : typeParameters){
TypeParameter param = paramsIterator.next();
List<TypeMirror> bounds = typeParam.getBounds();
for(TypeMirror bound : bounds){
ProducedType boundType;
// we turn java's default upper bound java.lang.Object into ceylon.language.Object
if(sameType(bound, OBJECT_TYPE)){
// avoid adding java's default upper bound if it's just there with no meaning
if(bounds.size() == 1)
break;
boundType = getType(CEYLON_OBJECT_TYPE, scope);
}else
boundType = getType(bound, scope);
param.getSatisfiedTypes().add(boundType);
}
}
}
// method
private void setTypeParameters(Method method, MethodMirror methodMirror) {
List<TypeParameter> params = new LinkedList<TypeParameter>();
method.setTypeParameters(params);
List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(methodMirror);
if(typeParameters != null)
setTypeParametersFromAnnotations(method, params, typeParameters);
else
setTypeParameters(method, params, methodMirror.getTypeParameters());
}
// class
private void setTypeParameters(ClassOrInterface klass, ClassMirror classMirror) {
List<TypeParameter> params = new LinkedList<TypeParameter>();
klass.setTypeParameters(params);
List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(classMirror);
if(typeParameters != null)
setTypeParametersFromAnnotations(klass, params, typeParameters);
else
setTypeParameters(klass, params, classMirror.getTypeParameters());
}
//
// TypeParsing and ModelLoader
private ProducedType decodeType(String value, Scope scope) {
return typeParser.decodeType(value, scope);
}
private ProducedType obtainType(TypeMirror type, AnnotatedMirror symbol, Scope scope) {
String typeName = getAnnotationStringValue(symbol, CEYLON_TYPE_INFO_ANNOTATION);
if (typeName != null) {
return decodeType(typeName, scope);
} else {
return obtainType(type, scope);
}
}
private ProducedType obtainType(TypeMirror type, Scope scope) {
String underlyingType = null;
// ERASURE
if (sameType(type, STRING_TYPE)) {
underlyingType = type.getQualifiedName();
type = CEYLON_STRING_TYPE;
} else if (sameType(type, PRIM_BOOLEAN_TYPE)) {
type = CEYLON_BOOLEAN_TYPE;
} else if (sameType(type, PRIM_BYTE_TYPE)) {
underlyingType = type.getQualifiedName();
type = CEYLON_INTEGER_TYPE;
} else if (sameType(type, PRIM_SHORT_TYPE)) {
underlyingType = type.getQualifiedName();
type = CEYLON_INTEGER_TYPE;
} else if (sameType(type, PRIM_INT_TYPE)) {
underlyingType = type.getQualifiedName();
type = CEYLON_INTEGER_TYPE;
} else if (sameType(type, PRIM_LONG_TYPE)) {
type = CEYLON_INTEGER_TYPE;
} else if (sameType(type, PRIM_FLOAT_TYPE)) {
underlyingType = type.getQualifiedName();
type = CEYLON_FLOAT_TYPE;
} else if (sameType(type, PRIM_DOUBLE_TYPE)) {
type = CEYLON_FLOAT_TYPE;
} else if (sameType(type, PRIM_CHAR_TYPE)) {
underlyingType = type.getQualifiedName();
type = CEYLON_CHARACTER_TYPE;
} else if (sameType(type, OBJECT_TYPE)) {
type = CEYLON_OBJECT_TYPE;
}
ProducedType ret = getType(type, scope);
if(underlyingType != null)
ret.setUnderlyingType(underlyingType);
return ret;
}
private boolean sameType(TypeMirror t1, TypeMirror t2) {
return t1.getQualifiedName().equals(t2.getQualifiedName());
}
@Override
public Declaration getDeclaration(String typeName, DeclarationType declarationType) {
return convertToDeclaration(typeName, declarationType);
}
private ProducedType getType(TypeMirror type, Scope scope) {
if (type.getKind() == TypeKind.ARRAY) {
Declaration decl = convertToDeclaration(CEYLON_ARRAY_TYPE, scope, DeclarationType.TYPE);
TypeDeclaration declaration = (TypeDeclaration) decl;
List<ProducedType> typeArguments = new ArrayList<ProducedType>(1);
typeArguments.add((ProducedType) obtainType(type.getComponentType(), scope));
return declaration.getProducedType(null, typeArguments);
} else {
Declaration decl = convertToDeclaration(type, scope, DeclarationType.TYPE);
TypeDeclaration declaration = (TypeDeclaration) decl;
List<TypeMirror> javacTypeArguments = type.getTypeArguments();
if(!javacTypeArguments.isEmpty()){
List<ProducedType> typeArguments = new ArrayList<ProducedType>(javacTypeArguments.size());
for(TypeMirror typeArgument : javacTypeArguments){
// if a single type argument is a wildcard, we erase to Object
if(typeArgument.getKind() == TypeKind.WILDCARD)
return typeFactory.getObjectDeclaration().getType();
typeArguments.add((ProducedType) getType(typeArgument, scope));
}
return declaration.getProducedType(null, typeArguments);
}
return declaration.getType();
}
}
@Override
public ProducedType getType(String name, Scope scope) {
if(scope != null){
TypeParameter typeParameter = lookupTypeParameter(scope, name);
if(typeParameter != null)
return typeParameter.getType();
}
if(!isBootstrap || !name.startsWith("ceylon.language"))
return ((TypeDeclaration)convertToDeclaration(name, DeclarationType.TYPE)).getType();
// we're bootstrapping ceylon.language so we need to return the ProducedTypes straight from the model we're compiling
Module languageModule = modules.getLanguageModule();
String simpleName = name.substring(name.lastIndexOf(".")+1);
for(Package pkg : languageModule.getPackages()){
Declaration member = pkg.getDirectMember(simpleName, null);
if(member != null)
return ((TypeDeclaration)member).getType();
}
throw new RuntimeException("Failed to look up given type in language module while bootstrapping: "+name);
}
protected static abstract class SourceDeclarationVisitor extends Visitor{
abstract public void loadFromSource(Tree.Declaration decl);
@Override
public void visit(Tree.ClassDefinition that) {
loadFromSource(that);
}
@Override
public void visit(Tree.InterfaceDefinition that) {
loadFromSource(that);
}
@Override
public void visit(Tree.ObjectDefinition that) {
loadFromSource(that);
}
@Override
public void visit(Tree.MethodDefinition that) {
loadFromSource(that);
}
@Override
public void visit(Tree.AttributeDeclaration that) {
loadFromSource(that);
}
@Override
public void visit(Tree.AttributeGetterDefinition that) {
loadFromSource(that);
}
}
public void printStats(){
int loaded = 0;
class Stats {
int loaded, total;
}
Map<Package, Stats> loadedByPackage = new HashMap<Package, Stats>();
for(Declaration decl : declarationsByName.values()){
if(decl instanceof LazyElement){
Package pkg = Util.getPackage(decl);
Stats stats = loadedByPackage.get(pkg);
if(stats == null){
stats = new Stats();
loadedByPackage.put(pkg, stats);
}
stats.total++;
if(((LazyElement)decl).isLoaded()){
loaded++;
stats.loaded++;
}
}
}
logVerbose("[Model loader: "+loaded+"(loaded)/"+declarationsByName.size()+"(total) declarations]");
for(Entry<Package, Stats> packageEntry : loadedByPackage.entrySet()){
logVerbose("[ Package "+packageEntry.getKey().getNameAsString()+": "
+packageEntry.getValue().loaded+"(loaded)/"+packageEntry.getValue().total+"(total) declarations]");
}
}
}
| true | true | private void complete(ClassOrInterface klass, ClassMirror classMirror) {
Map<MethodMirror, List<MethodMirror>> variables = new HashMap<MethodMirror, List<MethodMirror>>();
String qualifiedName = classMirror.getQualifiedName();
boolean isJava = qualifiedName.startsWith("java.");
boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null);
// Java classes with multiple constructors get turned into multiple Ceylon classes
// Here we get the specific constructor that was assigned to us (if any)
MethodMirror constructor = null;
if (klass instanceof LazyClass) {
constructor = ((LazyClass)klass).getConstructor();
}
// Turn a list of possibly overloaded methods into a map
// of lists that contain methods with the same name
Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>();
for(MethodMirror methodMirror : classMirror.getDirectMethods()){
// We skip members marked with @Ignore
if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(methodMirror.isStaticInit())
continue;
if(isCeylon && methodMirror.isStatic())
continue;
// FIXME: temporary, because some private classes from the jdk are
// referenced in private methods but not available
if(isJava && !methodMirror.isPublic())
continue;
String methodName = methodMirror.getName();
List<MethodMirror> homonyms = methods.get(methodName);
if (homonyms == null) {
homonyms = new LinkedList<MethodMirror>();
methods.put(methodName, homonyms);
}
homonyms.add(methodMirror);
}
// Add the methods
for(List<MethodMirror> methodMirrors : methods.values()){
boolean isOverloaded = methodMirrors.size() > 1;
boolean first = true;
for (MethodMirror methodMirror : methodMirrors) {
String methodName = methodMirror.getName();
if(methodMirror.isConstructor()) {
if (methodMirror == constructor) {
((Class)klass).setOverloaded(isOverloaded);
if(!(klass instanceof LazyClass) || !((LazyClass)klass).isTopLevelObjectType())
setParameters((Class)klass, methodMirror, isCeylon);
}
} else if(isGetter(methodMirror)) {
// simple attribute
addValue(klass, methodMirror, getJavaAttributeName(methodName));
} else if(isSetter(methodMirror)) {
// We skip setters for now and handle them later
variables.put(methodMirror, methodMirrors);
} else if(isHashAttribute(methodMirror)) {
// ERASURE
// Un-erasing 'hash' attribute from 'hashCode' method
addValue(klass, methodMirror, "hash");
} else if(isStringAttribute(methodMirror)) {
// ERASURE
// Un-erasing 'string' attribute from 'toString' method
addValue(klass, methodMirror, "string");
} else {
if (first && isOverloaded) {
// We create an extra "abstraction" method for overloaded methods
Method abstractionMethod = addMethod(klass, methodMirror, false, false);
abstractionMethod.setAbstraction(true);
abstractionMethod.setType(new UnknownType(typeFactory).getType());
first = false;
}
// normal method
addMethod(klass, methodMirror, isCeylon, isOverloaded);
}
}
}
for(FieldMirror fieldMirror : classMirror.getDirectFields()){
// We skip members marked with @Ignore
if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
// FIXME: Skip static fields for now
if(fieldMirror.isStatic())
continue;
String name = fieldMirror.getName();
// skip the field if "we've already got one"
if(klass.getDirectMember(name, null) != null)
continue;
addValue(klass, fieldMirror);
}
// Now mark all Values for which Setters exist as variable
for(Entry<MethodMirror, List<MethodMirror>> setterEntry : variables.entrySet()){
MethodMirror setter = setterEntry.getKey();
String name = getJavaAttributeName(setter.getName());
Declaration decl = klass.getMember(name, null);
boolean foundGetter = false;
if (decl != null && decl instanceof Value) {
Value value = (Value)decl;
VariableMirror setterParam = setter.getParameters().get(0);
ProducedType paramType = obtainType(setterParam.getType(), setterParam, klass);
// only add the setter if it has exactly the same type as the getter
if(paramType.isExactly(value.getType())){
foundGetter = true;
value.setVariable(true);
if(decl instanceof JavaBeanValue)
((JavaBeanValue)decl).setSetterName(setter.getName());
}else
logWarning("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method");
}
if(!foundGetter){
// it was not a setter, it was a method, let's add it as such
addMethod(klass, setter, isCeylon, false);
}
}
klass.setStaticallyImportable(!isCeylon && (classMirror.isStatic() || (classMirror instanceof LazyClass)));
setExtendedType(klass, classMirror);
setSatisfiedTypes(klass, classMirror);
setCaseTypes(klass, classMirror);
fillRefinedDeclarations(klass);
addInnerClasses(klass, classMirror);
setAnnotations(klass, classMirror);
}
| private void complete(ClassOrInterface klass, ClassMirror classMirror) {
Map<MethodMirror, List<MethodMirror>> variables = new HashMap<MethodMirror, List<MethodMirror>>();
String qualifiedName = classMirror.getQualifiedName();
boolean isJava = qualifiedName.startsWith("java.");
boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null);
// Java classes with multiple constructors get turned into multiple Ceylon classes
// Here we get the specific constructor that was assigned to us (if any)
MethodMirror constructor = null;
if (klass instanceof LazyClass) {
constructor = ((LazyClass)klass).getConstructor();
}
// Turn a list of possibly overloaded methods into a map
// of lists that contain methods with the same name
Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>();
for(MethodMirror methodMirror : classMirror.getDirectMethods()){
// We skip members marked with @Ignore
if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(methodMirror.isStaticInit())
continue;
if(isCeylon && methodMirror.isStatic())
continue;
// FIXME: temporary, because some private classes from the jdk are
// referenced in private methods but not available
if(isJava && !methodMirror.isPublic())
continue;
String methodName = methodMirror.getName();
List<MethodMirror> homonyms = methods.get(methodName);
if (homonyms == null) {
homonyms = new LinkedList<MethodMirror>();
methods.put(methodName, homonyms);
}
homonyms.add(methodMirror);
}
// Add the methods
for(List<MethodMirror> methodMirrors : methods.values()){
boolean isOverloaded = methodMirrors.size() > 1;
boolean first = true;
for (MethodMirror methodMirror : methodMirrors) {
String methodName = methodMirror.getName();
if(methodMirror.isConstructor()) {
if (methodMirror == constructor) {
((Class)klass).setOverloaded(isOverloaded);
if(!(klass instanceof LazyClass) || !((LazyClass)klass).isTopLevelObjectType())
setParameters((Class)klass, methodMirror, isCeylon);
}
} else if(isGetter(methodMirror)) {
// simple attribute
addValue(klass, methodMirror, getJavaAttributeName(methodName));
} else if(isSetter(methodMirror)) {
// We skip setters for now and handle them later
variables.put(methodMirror, methodMirrors);
} else if(isHashAttribute(methodMirror)) {
// ERASURE
// Un-erasing 'hash' attribute from 'hashCode' method
addValue(klass, methodMirror, "hash");
} else if(isStringAttribute(methodMirror)) {
// ERASURE
// Un-erasing 'string' attribute from 'toString' method
addValue(klass, methodMirror, "string");
} else {
if (first && isOverloaded) {
// We create an extra "abstraction" method for overloaded methods
Method abstractionMethod = addMethod(klass, methodMirror, false, false);
abstractionMethod.setAbstraction(true);
abstractionMethod.setType(new UnknownType(typeFactory).getType());
first = false;
}
// normal method
addMethod(klass, methodMirror, isCeylon, isOverloaded);
}
}
}
for(FieldMirror fieldMirror : classMirror.getDirectFields()){
// We skip members marked with @Ignore
if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(isCeylon && fieldMirror.isStatic())
continue;
String name = fieldMirror.getName();
// skip the field if "we've already got one"
if(klass.getDirectMember(name, null) != null)
continue;
addValue(klass, fieldMirror);
}
// Now mark all Values for which Setters exist as variable
for(Entry<MethodMirror, List<MethodMirror>> setterEntry : variables.entrySet()){
MethodMirror setter = setterEntry.getKey();
String name = getJavaAttributeName(setter.getName());
Declaration decl = klass.getMember(name, null);
boolean foundGetter = false;
if (decl != null && decl instanceof Value) {
Value value = (Value)decl;
VariableMirror setterParam = setter.getParameters().get(0);
ProducedType paramType = obtainType(setterParam.getType(), setterParam, klass);
// only add the setter if it has exactly the same type as the getter
if(paramType.isExactly(value.getType())){
foundGetter = true;
value.setVariable(true);
if(decl instanceof JavaBeanValue)
((JavaBeanValue)decl).setSetterName(setter.getName());
}else
logWarning("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method");
}
if(!foundGetter){
// it was not a setter, it was a method, let's add it as such
addMethod(klass, setter, isCeylon, false);
}
}
klass.setStaticallyImportable(!isCeylon && (classMirror.isStatic() || (classMirror instanceof LazyClass)));
setExtendedType(klass, classMirror);
setSatisfiedTypes(klass, classMirror);
setCaseTypes(klass, classMirror);
fillRefinedDeclarations(klass);
addInnerClasses(klass, classMirror);
setAnnotations(klass, classMirror);
}
|
diff --git a/Android/src/org/libsdl/app/SDLActivity.java b/Android/src/org/libsdl/app/SDLActivity.java
index 2c2f109a..61e3b2bc 100644
--- a/Android/src/org/libsdl/app/SDLActivity.java
+++ b/Android/src/org/libsdl/app/SDLActivity.java
@@ -1,607 +1,606 @@
// Modified by Lasse Oorni for Urho3D
package org.libsdl.app;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.egl.*;
import android.app.*;
import android.content.*;
import android.view.*;
import android.os.*;
import android.util.Log;
import android.graphics.*;
import android.text.method.*;
import android.text.*;
import android.media.*;
import android.hardware.*;
import android.content.*;
import android.content.res.*;
import java.lang.*;
/**
SDL Activity
*/
public class SDLActivity extends Activity {
// Main components
private static SDLActivity mSingleton;
private static SDLSurface mSurface;
// This is what SDL runs in. It invokes SDL_main(), eventually
private static Thread mSDLThread;
// Audio
private static Thread mAudioThread;
private static AudioTrack mAudioTrack;
// EGL private objects
private EGLContext mEGLContext;
private EGLSurface mEGLSurface;
private EGLDisplay mEGLDisplay;
private EGLConfig mEGLConfig;
private int mGLMajor, mGLMinor;
private boolean mFinished = false;
// Load the .so
static {
System.loadLibrary("Urho3D");
}
// Setup
protected void onCreate(Bundle savedInstanceState) {
Log.v("SDL", "onCreate()");
super.onCreate(savedInstanceState);
// So we can call stuff from static callbacks
mSingleton = this;
// Set up the surface
mSurface = new SDLSurface(getApplication());
setContentView(mSurface);
SurfaceHolder holder = mSurface.getHolder();
}
// Events
protected void onPause() {
Log.v("SDL", "onPause()");
super.onPause();
SDLActivity.nativePause();
}
protected void onResume() {
Log.v("SDL", "onResume()");
super.onResume();
SDLActivity.nativeResume();
}
protected void onDestroy() {
Log.v("SDL", "onDestroy()");
super.onDestroy();
mFinished = true;
// Send a quit message to the application
SDLActivity.nativeQuit();
// Now wait for the SDL thread to quit
if (mSDLThread != null) {
try {
mSDLThread.join();
} catch(Exception e) {
Log.v("SDL", "Problem stopping thread: " + e);
}
mSDLThread = null;
//Log.v("SDL", "Finished waiting for SDL thread");
}
mSingleton = null;
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public static SDLActivity getSingleton() {
return mSingleton;
}
// Messages from the SDLMain thread
static int COMMAND_CHANGE_TITLE = 1;
static int COMMAND_FINISH = 2;
// Handler for the messages
Handler commandHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.arg1 == COMMAND_CHANGE_TITLE) {
setTitle((String)msg.obj);
}
if (msg.arg1 == COMMAND_FINISH) {
if (mFinished == false) {
mFinished = true;
finish();
}
}
}
};
// Send a message from the SDLMain thread
void sendCommand(int command, Object data) {
Message msg = commandHandler.obtainMessage();
msg.arg1 = command;
msg.obj = data;
commandHandler.sendMessage(msg);
}
// C functions we call
public static native void nativeInit(String filesDir);
public static native void nativeQuit();
public static native void nativePause();
public static native void nativeResume();
public static native void onNativeResize(int x, int y, int format);
public static native void onNativeKeyDown(int keycode);
public static native void onNativeKeyUp(int keycode);
public static native void onNativeTouch(int touchDevId, int pointerFingerId,
int action, float x,
float y, float p);
public static native void onNativeAccel(float x, float y, float z);
public static native void nativeRunAudioThread();
// Java functions called from C
public static boolean createGLContext(int majorVersion, int minorVersion) {
return initEGL(majorVersion, minorVersion);
}
public static void flipBuffers() {
flipEGL();
}
public static void setActivityTitle(String title) {
// Called from SDLMain() thread and can't directly affect the view
mSingleton.sendCommand(COMMAND_CHANGE_TITLE, title);
}
public static void finishActivity() {
mSingleton.sendCommand(COMMAND_FINISH, null);
}
public static Context getContext() {
return mSingleton;
}
public static void startApp() {
// Start up the C app thread
if (mSDLThread == null) {
mSDLThread = new Thread(new SDLMain(), "SDLThread");
mSDLThread.start();
}
else {
SDLActivity.nativeResume();
}
}
// EGL functions
public static boolean initEGL(int majorVersion, int minorVersion) {
if (SDLActivity.mSingleton.mEGLDisplay == null) {
//Log.v("SDL", "Starting up OpenGL ES " + majorVersion + "." + minorVersion);
try {
EGL10 egl = (EGL10)EGLContext.getEGL();
EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
egl.eglInitialize(dpy, version);
int EGL_OPENGL_ES_BIT = 1;
int EGL_OPENGL_ES2_BIT = 4;
int renderableType = 0;
if (majorVersion == 2) {
renderableType = EGL_OPENGL_ES2_BIT;
} else if (majorVersion == 1) {
renderableType = EGL_OPENGL_ES_BIT;
}
int[] configSpec = {
EGL10.EGL_DEPTH_SIZE, 16,
- EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_RENDERABLE_TYPE, renderableType,
EGL10.EGL_NONE
};
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
if (!egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config) || num_config[0] == 0) {
Log.e("SDL", "No EGL config available");
return false;
}
EGLConfig config = configs[0];
/*int EGL_CONTEXT_CLIENT_VERSION=0x3098;
int contextAttrs[] = new int[] { EGL_CONTEXT_CLIENT_VERSION, majorVersion, EGL10.EGL_NONE };
EGLContext ctx = egl.eglCreateContext(dpy, config, EGL10.EGL_NO_CONTEXT, contextAttrs);
if (ctx == EGL10.EGL_NO_CONTEXT) {
Log.e("SDL", "Couldn't create context");
return false;
}
SDLActivity.mEGLContext = ctx;*/
SDLActivity.mSingleton.mEGLDisplay = dpy;
SDLActivity.mSingleton.mEGLConfig = config;
SDLActivity.mSingleton.mGLMajor = majorVersion;
SDLActivity.mSingleton.mGLMinor = minorVersion;
SDLActivity.createEGLSurface();
} catch(Exception e) {
Log.v("SDL", e + "");
for (StackTraceElement s : e.getStackTrace()) {
Log.v("SDL", s.toString());
}
}
}
else SDLActivity.createEGLSurface();
return true;
}
public static boolean createEGLContext() {
EGL10 egl = (EGL10)EGLContext.getEGL();
int EGL_CONTEXT_CLIENT_VERSION=0x3098;
int contextAttrs[] = new int[] { EGL_CONTEXT_CLIENT_VERSION, SDLActivity.mSingleton.mGLMajor, EGL10.EGL_NONE };
SDLActivity.mSingleton.mEGLContext = egl.eglCreateContext(SDLActivity.mSingleton.mEGLDisplay, SDLActivity.mSingleton.mEGLConfig, EGL10.EGL_NO_CONTEXT, contextAttrs);
if (SDLActivity.mSingleton.mEGLContext == EGL10.EGL_NO_CONTEXT) {
Log.e("SDL", "Couldn't create context");
return false;
}
return true;
}
public static boolean createEGLSurface() {
if (SDLActivity.mSingleton.mEGLDisplay != null && SDLActivity.mSingleton.mEGLConfig != null) {
EGL10 egl = (EGL10)EGLContext.getEGL();
if (SDLActivity.mSingleton.mEGLContext == null) createEGLContext();
Log.v("SDL", "Creating new EGL Surface");
EGLSurface surface = egl.eglCreateWindowSurface(SDLActivity.mSingleton.mEGLDisplay, SDLActivity.mSingleton.mEGLConfig, SDLActivity.mSingleton.mSurface, null);
if (surface == EGL10.EGL_NO_SURFACE) {
Log.e("SDL", "Couldn't create surface");
return false;
}
if (!egl.eglMakeCurrent(SDLActivity.mSingleton.mEGLDisplay, surface, surface, SDLActivity.mSingleton.mEGLContext)) {
Log.e("SDL", "Old EGL Context doesnt work, trying with a new one");
createEGLContext();
if (!egl.eglMakeCurrent(SDLActivity.mSingleton.mEGLDisplay, surface, surface, SDLActivity.mSingleton.mEGLContext)) {
Log.e("SDL", "Failed making EGL Context current");
return false;
}
}
SDLActivity.mSingleton.mEGLSurface = surface;
return true;
}
return false;
}
// EGL buffer flip
public static void flipEGL() {
try {
EGL10 egl = (EGL10)EGLContext.getEGL();
egl.eglWaitNative(EGL10.EGL_CORE_NATIVE_ENGINE, null);
// drawing here
egl.eglWaitGL();
egl.eglSwapBuffers(SDLActivity.mSingleton.mEGLDisplay, SDLActivity.mSingleton.mEGLSurface);
} catch(Exception e) {
Log.v("SDL", "flipEGL(): " + e);
for (StackTraceElement s : e.getStackTrace()) {
Log.v("SDL", s.toString());
}
}
}
// Audio
private static Object buf;
public static Object audioInit(int sampleRate, boolean is16Bit, boolean isStereo, int desiredFrames) {
int channelConfig = isStereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioFormat = is16Bit ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT;
int frameSize = (isStereo ? 2 : 1) * (is16Bit ? 2 : 1);
Log.v("SDL", "SDL audio: wanted " + (isStereo ? "stereo" : "mono") + " " + (is16Bit ? "16-bit" : "8-bit") + " " + ((float)sampleRate / 1000f) + "kHz, " + desiredFrames + " frames buffer");
// Let the user pick a larger buffer if they really want -- but ye
// gods they probably shouldn't, the minimums are horrifyingly high
// latency already
desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize);
mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM);
audioStartThread();
Log.v("SDL", "SDL audio: got " + ((mAudioTrack.getChannelCount() >= 2) ? "stereo" : "mono") + " " + ((mAudioTrack.getAudioFormat() == AudioFormat.ENCODING_PCM_16BIT) ? "16-bit" : "8-bit") + " " + ((float)mAudioTrack.getSampleRate() / 1000f) + "kHz, " + desiredFrames + " frames buffer");
if (is16Bit) {
buf = new short[desiredFrames * (isStereo ? 2 : 1)];
} else {
buf = new byte[desiredFrames * (isStereo ? 2 : 1)];
}
return buf;
}
public static void audioStartThread() {
mAudioThread = new Thread(new Runnable() {
public void run() {
mAudioTrack.play();
nativeRunAudioThread();
}
});
// I'd take REALTIME if I could get it!
mAudioThread.setPriority(Thread.MAX_PRIORITY);
mAudioThread.start();
}
public static void audioWriteShortBuffer(short[] buffer) {
for (int i = 0; i < buffer.length; ) {
int result = mAudioTrack.write(buffer, i, buffer.length - i);
if (result > 0) {
i += result;
} else if (result == 0) {
try {
Thread.sleep(1);
} catch(InterruptedException e) {
// Nom nom
}
} else {
Log.w("SDL", "SDL audio: error return from write(short)");
return;
}
}
}
public static void audioWriteByteBuffer(byte[] buffer) {
for (int i = 0; i < buffer.length; ) {
int result = mAudioTrack.write(buffer, i, buffer.length - i);
if (result > 0) {
i += result;
} else if (result == 0) {
try {
Thread.sleep(1);
} catch(InterruptedException e) {
// Nom nom
}
} else {
Log.w("SDL", "SDL audio: error return from write(short)");
return;
}
}
}
public static void audioQuit() {
if (mAudioThread != null) {
try {
mAudioThread.join();
} catch(Exception e) {
Log.v("SDL", "Problem stopping audio thread: " + e);
}
mAudioThread = null;
//Log.v("SDL", "Finished waiting for audio thread");
}
if (mAudioTrack != null) {
mAudioTrack.stop();
mAudioTrack = null;
}
}
}
/**
Simple nativeInit() runnable
*/
class SDLMain implements Runnable {
public void run() {
// Runs SDL_main()
SDLActivity.nativeInit(SDLActivity.getSingleton().getFilesDir().getAbsolutePath());
//Log.v("SDL", "SDL thread terminated");
SDLActivity.finishActivity();
}
}
/**
SDLSurface. This is what we draw on, so we need to know when it's created
in order to do anything useful.
Because of this, that's where we set up the SDL thread
*/
class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
View.OnKeyListener, View.OnTouchListener, SensorEventListener {
// Sensors
private static SensorManager mSensorManager;
// Startup
public SDLSurface(Context context) {
super(context);
getHolder().addCallback(this);
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
setOnKeyListener(this);
setOnTouchListener(this);
mSensorManager = (SensorManager)context.getSystemService("sensor");
}
// Called when we have a valid drawing surface
public void surfaceCreated(SurfaceHolder holder) {
Log.v("SDL", "surfaceCreated()");
holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
SDLActivity.createEGLSurface();
enableSensor(Sensor.TYPE_ACCELEROMETER, true);
}
// Called when we lose the surface
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v("SDL", "surfaceDestroyed()");
SDLActivity.nativePause();
enableSensor(Sensor.TYPE_ACCELEROMETER, false);
}
// Called when the surface is resized
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
Log.v("SDL", "surfaceChanged()");
int sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 by default
switch (format) {
case PixelFormat.A_8:
Log.v("SDL", "pixel format A_8");
break;
case PixelFormat.LA_88:
Log.v("SDL", "pixel format LA_88");
break;
case PixelFormat.L_8:
Log.v("SDL", "pixel format L_8");
break;
case PixelFormat.RGBA_4444:
Log.v("SDL", "pixel format RGBA_4444");
sdlFormat = 0x85421002; // SDL_PIXELFORMAT_RGBA4444
break;
case PixelFormat.RGBA_5551:
Log.v("SDL", "pixel format RGBA_5551");
sdlFormat = 0x85441002; // SDL_PIXELFORMAT_RGBA5551
break;
case PixelFormat.RGBA_8888:
Log.v("SDL", "pixel format RGBA_8888");
sdlFormat = 0x86462004; // SDL_PIXELFORMAT_RGBA8888
break;
case PixelFormat.RGBX_8888:
Log.v("SDL", "pixel format RGBX_8888");
sdlFormat = 0x86262004; // SDL_PIXELFORMAT_RGBX8888
break;
case PixelFormat.RGB_332:
Log.v("SDL", "pixel format RGB_332");
sdlFormat = 0x84110801; // SDL_PIXELFORMAT_RGB332
break;
case PixelFormat.RGB_565:
Log.v("SDL", "pixel format RGB_565");
sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565
break;
case PixelFormat.RGB_888:
Log.v("SDL", "pixel format RGB_888");
// Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
sdlFormat = 0x86161804; // SDL_PIXELFORMAT_RGB888
break;
default:
Log.v("SDL", "pixel format unknown " + format);
break;
}
SDLActivity.onNativeResize(width, height, sdlFormat);
Log.v("SDL", "Window size:" + width + "x"+height);
SDLActivity.startApp();
}
// unused
public void onDraw(Canvas canvas) {}
// Key events
public boolean onKey(View v, int keyCode, KeyEvent event) {
// Urho3D: let the home & volume keys be handled by the system
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_HOME)
return false;
if (event.getAction() == KeyEvent.ACTION_DOWN) {
//Log.v("SDL", "key down: " + keyCode);
SDLActivity.onNativeKeyDown(keyCode);
return true;
}
else if (event.getAction() == KeyEvent.ACTION_UP) {
//Log.v("SDL", "key up: " + keyCode);
SDLActivity.onNativeKeyUp(keyCode);
return true;
}
return false;
}
// Touch events
public boolean onTouch(View v, MotionEvent event) {
{
final int touchDevId = event.getDeviceId();
final int pointerCount = event.getPointerCount();
// touchId, pointerId, action, x, y, pressure
int actionPointerIndex = event.getActionIndex();
int pointerFingerId = event.getPointerId(actionPointerIndex);
int action = event.getActionMasked();
float x = event.getX(actionPointerIndex);
float y = event.getY(actionPointerIndex);
float p = event.getPressure(actionPointerIndex);
if (action == MotionEvent.ACTION_MOVE && pointerCount > 1) {
// TODO send motion to every pointer if its position has
// changed since prev event.
for (int i = 0; i < pointerCount; i++) {
pointerFingerId = event.getPointerId(i);
x = event.getX(i);
y = event.getY(i);
p = event.getPressure(i);
SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
}
} else {
SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
}
}
return true;
}
// Sensor events
public void enableSensor(int sensortype, boolean enabled) {
// TODO: This uses getDefaultSensor - what if we have >1 accels?
if (enabled) {
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(sensortype),
SensorManager.SENSOR_DELAY_GAME, null);
} else {
mSensorManager.unregisterListener(this,
mSensorManager.getDefaultSensor(sensortype));
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
SDLActivity.onNativeAccel(event.values[0] / SensorManager.GRAVITY_EARTH,
event.values[1] / SensorManager.GRAVITY_EARTH,
event.values[2] / SensorManager.GRAVITY_EARTH);
}
}
}
| true | true | public static boolean initEGL(int majorVersion, int minorVersion) {
if (SDLActivity.mSingleton.mEGLDisplay == null) {
//Log.v("SDL", "Starting up OpenGL ES " + majorVersion + "." + minorVersion);
try {
EGL10 egl = (EGL10)EGLContext.getEGL();
EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
egl.eglInitialize(dpy, version);
int EGL_OPENGL_ES_BIT = 1;
int EGL_OPENGL_ES2_BIT = 4;
int renderableType = 0;
if (majorVersion == 2) {
renderableType = EGL_OPENGL_ES2_BIT;
} else if (majorVersion == 1) {
renderableType = EGL_OPENGL_ES_BIT;
}
int[] configSpec = {
EGL10.EGL_DEPTH_SIZE, 16,
EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_RENDERABLE_TYPE, renderableType,
EGL10.EGL_NONE
};
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
if (!egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config) || num_config[0] == 0) {
Log.e("SDL", "No EGL config available");
return false;
}
EGLConfig config = configs[0];
/*int EGL_CONTEXT_CLIENT_VERSION=0x3098;
int contextAttrs[] = new int[] { EGL_CONTEXT_CLIENT_VERSION, majorVersion, EGL10.EGL_NONE };
EGLContext ctx = egl.eglCreateContext(dpy, config, EGL10.EGL_NO_CONTEXT, contextAttrs);
if (ctx == EGL10.EGL_NO_CONTEXT) {
Log.e("SDL", "Couldn't create context");
return false;
}
SDLActivity.mEGLContext = ctx;*/
SDLActivity.mSingleton.mEGLDisplay = dpy;
SDLActivity.mSingleton.mEGLConfig = config;
SDLActivity.mSingleton.mGLMajor = majorVersion;
SDLActivity.mSingleton.mGLMinor = minorVersion;
SDLActivity.createEGLSurface();
} catch(Exception e) {
Log.v("SDL", e + "");
for (StackTraceElement s : e.getStackTrace()) {
Log.v("SDL", s.toString());
}
}
}
else SDLActivity.createEGLSurface();
return true;
}
| public static boolean initEGL(int majorVersion, int minorVersion) {
if (SDLActivity.mSingleton.mEGLDisplay == null) {
//Log.v("SDL", "Starting up OpenGL ES " + majorVersion + "." + minorVersion);
try {
EGL10 egl = (EGL10)EGLContext.getEGL();
EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
egl.eglInitialize(dpy, version);
int EGL_OPENGL_ES_BIT = 1;
int EGL_OPENGL_ES2_BIT = 4;
int renderableType = 0;
if (majorVersion == 2) {
renderableType = EGL_OPENGL_ES2_BIT;
} else if (majorVersion == 1) {
renderableType = EGL_OPENGL_ES_BIT;
}
int[] configSpec = {
EGL10.EGL_DEPTH_SIZE, 16,
EGL10.EGL_RENDERABLE_TYPE, renderableType,
EGL10.EGL_NONE
};
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
if (!egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config) || num_config[0] == 0) {
Log.e("SDL", "No EGL config available");
return false;
}
EGLConfig config = configs[0];
/*int EGL_CONTEXT_CLIENT_VERSION=0x3098;
int contextAttrs[] = new int[] { EGL_CONTEXT_CLIENT_VERSION, majorVersion, EGL10.EGL_NONE };
EGLContext ctx = egl.eglCreateContext(dpy, config, EGL10.EGL_NO_CONTEXT, contextAttrs);
if (ctx == EGL10.EGL_NO_CONTEXT) {
Log.e("SDL", "Couldn't create context");
return false;
}
SDLActivity.mEGLContext = ctx;*/
SDLActivity.mSingleton.mEGLDisplay = dpy;
SDLActivity.mSingleton.mEGLConfig = config;
SDLActivity.mSingleton.mGLMajor = majorVersion;
SDLActivity.mSingleton.mGLMinor = minorVersion;
SDLActivity.createEGLSurface();
} catch(Exception e) {
Log.v("SDL", e + "");
for (StackTraceElement s : e.getStackTrace()) {
Log.v("SDL", s.toString());
}
}
}
else SDLActivity.createEGLSurface();
return true;
}
|
diff --git a/lucene/src/java/org/apache/lucene/search/BooleanQuery.java b/lucene/src/java/org/apache/lucene/search/BooleanQuery.java
index b1c643f47..d1f3ebcae 100644
--- a/lucene/src/java/org/apache/lucene/search/BooleanQuery.java
+++ b/lucene/src/java/org/apache/lucene/search/BooleanQuery.java
@@ -1,484 +1,489 @@
package org.apache.lucene.search;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.util.ToStringUtils;
import org.apache.lucene.search.BooleanClause.Occur;
import java.io.IOException;
import java.util.*;
/** A Query that matches documents matching boolean combinations of other
* queries, e.g. {@link TermQuery}s, {@link PhraseQuery}s or other
* BooleanQuerys.
*/
public class BooleanQuery extends Query implements Iterable<BooleanClause> {
private static int maxClauseCount = 1024;
/** Thrown when an attempt is made to add more than {@link
* #getMaxClauseCount()} clauses. This typically happens if
* a PrefixQuery, FuzzyQuery, WildcardQuery, or TermRangeQuery
* is expanded to many terms during search.
*/
public static class TooManyClauses extends RuntimeException {
public TooManyClauses() {}
@Override
public String getMessage() {
return "maxClauseCount is set to " + maxClauseCount;
}
}
/** Return the maximum number of clauses permitted, 1024 by default.
* Attempts to add more than the permitted number of clauses cause {@link
* TooManyClauses} to be thrown.
* @see #setMaxClauseCount(int)
*/
public static int getMaxClauseCount() { return maxClauseCount; }
/**
* Set the maximum number of clauses permitted per BooleanQuery.
* Default value is 1024.
*/
public static void setMaxClauseCount(int maxClauseCount) {
if (maxClauseCount < 1)
throw new IllegalArgumentException("maxClauseCount must be >= 1");
BooleanQuery.maxClauseCount = maxClauseCount;
}
private ArrayList<BooleanClause> clauses = new ArrayList<BooleanClause>();
private boolean disableCoord;
/** Constructs an empty boolean query. */
public BooleanQuery() {}
/** Constructs an empty boolean query.
*
* {@link Similarity#coord(int,int)} may be disabled in scoring, as
* appropriate. For example, this score factor does not make sense for most
* automatically generated queries, like {@link WildcardQuery} and {@link
* FuzzyQuery}.
*
* @param disableCoord disables {@link Similarity#coord(int,int)} in scoring.
*/
public BooleanQuery(boolean disableCoord) {
this.disableCoord = disableCoord;
}
/** Returns true iff {@link Similarity#coord(int,int)} is disabled in
* scoring for this query instance.
* @see #BooleanQuery(boolean)
*/
public boolean isCoordDisabled() { return disableCoord; }
// Implement coord disabling.
// Inherit javadoc.
@Override
public Similarity getSimilarity(Searcher searcher) {
Similarity result = super.getSimilarity(searcher);
if (disableCoord) { // disable coord as requested
result = new SimilarityDelegator(result) {
@Override
public float coord(int overlap, int maxOverlap) {
return 1.0f;
}
};
}
return result;
}
/**
* Specifies a minimum number of the optional BooleanClauses
* which must be satisfied.
*
* <p>
* By default no optional clauses are necessary for a match
* (unless there are no required clauses). If this method is used,
* then the specified number of clauses is required.
* </p>
* <p>
* Use of this method is totally independent of specifying that
* any specific clauses are required (or prohibited). This number will
* only be compared against the number of matching optional clauses.
* </p>
*
* @param min the number of optional clauses that must match
*/
public void setMinimumNumberShouldMatch(int min) {
this.minNrShouldMatch = min;
}
protected int minNrShouldMatch = 0;
/**
* Gets the minimum number of the optional BooleanClauses
* which must be satisfied.
*/
public int getMinimumNumberShouldMatch() {
return minNrShouldMatch;
}
/** Adds a clause to a boolean query.
*
* @throws TooManyClauses if the new number of clauses exceeds the maximum clause number
* @see #getMaxClauseCount()
*/
public void add(Query query, BooleanClause.Occur occur) {
add(new BooleanClause(query, occur));
}
/** Adds a clause to a boolean query.
* @throws TooManyClauses if the new number of clauses exceeds the maximum clause number
* @see #getMaxClauseCount()
*/
public void add(BooleanClause clause) {
if (clauses.size() >= maxClauseCount)
throw new TooManyClauses();
clauses.add(clause);
}
/** Returns the set of clauses in this query. */
public BooleanClause[] getClauses() {
return clauses.toArray(new BooleanClause[clauses.size()]);
}
/** Returns the list of clauses in this query. */
public List<BooleanClause> clauses() { return clauses; }
/** Returns an iterator on the clauses in this query. It implements the {@link Iterable} interface to
* make it possible to do:
* <pre>for (BooleanClause clause : booleanQuery) {}</pre>
*/
public final Iterator<BooleanClause> iterator() { return clauses().iterator(); }
/**
* Expert: the Weight for BooleanQuery, used to
* normalize, score and explain these queries.
*
* <p>NOTE: this API and implementation is subject to
* change suddenly in the next release.</p>
*/
protected class BooleanWeight extends Weight {
/** The Similarity implementation. */
protected Similarity similarity;
protected ArrayList<Weight> weights;
protected int maxCoord; // num optional + num required
public BooleanWeight(Searcher searcher)
throws IOException {
this.similarity = getSimilarity(searcher);
weights = new ArrayList<Weight>(clauses.size());
for (int i = 0 ; i < clauses.size(); i++) {
BooleanClause c = clauses.get(i);
weights.add(c.getQuery().createWeight(searcher));
if (!c.isProhibited()) maxCoord++;
}
}
@Override
public Query getQuery() { return BooleanQuery.this; }
@Override
public float getValue() { return getBoost(); }
@Override
public float sumOfSquaredWeights() throws IOException {
float sum = 0.0f;
for (int i = 0 ; i < weights.size(); i++) {
// call sumOfSquaredWeights for all clauses in case of side effects
float s = weights.get(i).sumOfSquaredWeights(); // sum sub weights
if (!clauses.get(i).isProhibited())
// only add to sum for non-prohibited clauses
sum += s;
}
sum *= getBoost() * getBoost(); // boost each sub-weight
return sum ;
}
@Override
public void normalize(float norm) {
norm *= getBoost(); // incorporate boost
for (Weight w : weights) {
// normalize all clauses, (even if prohibited in case of side affects)
w.normalize(norm);
}
}
@Override
public Explanation explain(IndexReader reader, int doc)
throws IOException {
final int minShouldMatch =
BooleanQuery.this.getMinimumNumberShouldMatch();
ComplexExplanation sumExpl = new ComplexExplanation();
sumExpl.setDescription("sum of:");
int coord = 0;
float sum = 0.0f;
boolean fail = false;
int shouldMatchCount = 0;
Iterator<BooleanClause> cIter = clauses.iterator();
for (Iterator<Weight> wIter = weights.iterator(); wIter.hasNext();) {
Weight w = wIter.next();
BooleanClause c = cIter.next();
if (w.scorer(reader, true, true) == null) {
+ if (c.isRequired()) {
+ fail = true;
+ Explanation r = new Explanation(0.0f, "no match on required clause (" + c.getQuery().toString() + ")");
+ sumExpl.addDetail(r);
+ }
continue;
}
Explanation e = w.explain(reader, doc);
if (e.isMatch()) {
if (!c.isProhibited()) {
sumExpl.addDetail(e);
sum += e.getValue();
coord++;
} else {
Explanation r =
new Explanation(0.0f, "match on prohibited clause (" + c.getQuery().toString() + ")");
r.addDetail(e);
sumExpl.addDetail(r);
fail = true;
}
if (c.getOccur() == Occur.SHOULD)
shouldMatchCount++;
} else if (c.isRequired()) {
Explanation r = new Explanation(0.0f, "no match on required clause (" + c.getQuery().toString() + ")");
r.addDetail(e);
sumExpl.addDetail(r);
fail = true;
}
}
if (fail) {
sumExpl.setMatch(Boolean.FALSE);
sumExpl.setValue(0.0f);
sumExpl.setDescription
("Failure to meet condition(s) of required/prohibited clause(s)");
return sumExpl;
} else if (shouldMatchCount < minShouldMatch) {
sumExpl.setMatch(Boolean.FALSE);
sumExpl.setValue(0.0f);
sumExpl.setDescription("Failure to match minimum number "+
"of optional clauses: " + minShouldMatch);
return sumExpl;
}
sumExpl.setMatch(0 < coord ? Boolean.TRUE : Boolean.FALSE);
sumExpl.setValue(sum);
float coordFactor = similarity.coord(coord, maxCoord);
if (coordFactor == 1.0f) // coord is no-op
return sumExpl; // eliminate wrapper
else {
ComplexExplanation result = new ComplexExplanation(sumExpl.isMatch(),
sum*coordFactor,
"product of:");
result.addDetail(sumExpl);
result.addDetail(new Explanation(coordFactor,
"coord("+coord+"/"+maxCoord+")"));
return result;
}
}
@Override
public Scorer scorer(IndexReader reader, boolean scoreDocsInOrder, boolean topScorer)
throws IOException {
List<Scorer> required = new ArrayList<Scorer>();
List<Scorer> prohibited = new ArrayList<Scorer>();
List<Scorer> optional = new ArrayList<Scorer>();
Iterator<BooleanClause> cIter = clauses.iterator();
for (Weight w : weights) {
BooleanClause c = cIter.next();
Scorer subScorer = w.scorer(reader, true, false);
if (subScorer == null) {
if (c.isRequired()) {
return null;
}
} else if (c.isRequired()) {
required.add(subScorer);
} else if (c.isProhibited()) {
prohibited.add(subScorer);
} else {
optional.add(subScorer);
}
}
// Check if we can return a BooleanScorer
if (!scoreDocsInOrder && topScorer && required.size() == 0 && prohibited.size() < 32) {
return new BooleanScorer(this, similarity, minNrShouldMatch, optional, prohibited, maxCoord);
}
if (required.size() == 0 && optional.size() == 0) {
// no required and optional clauses.
return null;
} else if (optional.size() < minNrShouldMatch) {
// either >1 req scorer, or there are 0 req scorers and at least 1
// optional scorer. Therefore if there are not enough optional scorers
// no documents will be matched by the query
return null;
}
// Return a BooleanScorer2
return new BooleanScorer2(this, similarity, minNrShouldMatch, required, prohibited, optional, maxCoord);
}
@Override
public boolean scoresDocsOutOfOrder() {
int numProhibited = 0;
for (BooleanClause c : clauses) {
if (c.isRequired()) {
return false; // BS2 (in-order) will be used by scorer()
} else if (c.isProhibited()) {
++numProhibited;
}
}
if (numProhibited > 32) { // cannot use BS
return false;
}
// scorer() will return an out-of-order scorer if requested.
return true;
}
}
@Override
public Weight createWeight(Searcher searcher) throws IOException {
return new BooleanWeight(searcher);
}
@Override
public Query rewrite(IndexReader reader) throws IOException {
if (minNrShouldMatch == 0 && clauses.size() == 1) { // optimize 1-clause queries
BooleanClause c = clauses.get(0);
if (!c.isProhibited()) { // just return clause
Query query = c.getQuery().rewrite(reader); // rewrite first
if (getBoost() != 1.0f) { // incorporate boost
if (query == c.getQuery()) // if rewrite was no-op
query = (Query)query.clone(); // then clone before boost
query.setBoost(getBoost() * query.getBoost());
}
return query;
}
}
BooleanQuery clone = null; // recursively rewrite
for (int i = 0 ; i < clauses.size(); i++) {
BooleanClause c = clauses.get(i);
Query query = c.getQuery().rewrite(reader);
if (query != c.getQuery()) { // clause rewrote: must clone
if (clone == null)
clone = (BooleanQuery)this.clone();
clone.clauses.set(i, new BooleanClause(query, c.getOccur()));
}
}
if (clone != null) {
return clone; // some clauses rewrote
} else
return this; // no clauses rewrote
}
// inherit javadoc
@Override
public void extractTerms(Set<Term> terms) {
for (BooleanClause clause : clauses) {
clause.getQuery().extractTerms(terms);
}
}
@Override @SuppressWarnings("unchecked")
public Object clone() {
BooleanQuery clone = (BooleanQuery)super.clone();
clone.clauses = (ArrayList<BooleanClause>) this.clauses.clone();
return clone;
}
/** Prints a user-readable version of this query. */
@Override
public String toString(String field) {
StringBuilder buffer = new StringBuilder();
boolean needParens=(getBoost() != 1.0) || (getMinimumNumberShouldMatch()>0) ;
if (needParens) {
buffer.append("(");
}
for (int i = 0 ; i < clauses.size(); i++) {
BooleanClause c = clauses.get(i);
if (c.isProhibited())
buffer.append("-");
else if (c.isRequired())
buffer.append("+");
Query subQuery = c.getQuery();
if (subQuery != null) {
if (subQuery instanceof BooleanQuery) { // wrap sub-bools in parens
buffer.append("(");
buffer.append(subQuery.toString(field));
buffer.append(")");
} else {
buffer.append(subQuery.toString(field));
}
} else {
buffer.append("null");
}
if (i != clauses.size()-1)
buffer.append(" ");
}
if (needParens) {
buffer.append(")");
}
if (getMinimumNumberShouldMatch()>0) {
buffer.append('~');
buffer.append(getMinimumNumberShouldMatch());
}
if (getBoost() != 1.0f)
{
buffer.append(ToStringUtils.boost(getBoost()));
}
return buffer.toString();
}
/** Returns true iff <code>o</code> is equal to this. */
@Override
public boolean equals(Object o) {
if (!(o instanceof BooleanQuery))
return false;
BooleanQuery other = (BooleanQuery)o;
return (this.getBoost() == other.getBoost())
&& this.clauses.equals(other.clauses)
&& this.getMinimumNumberShouldMatch() == other.getMinimumNumberShouldMatch()
&& this.disableCoord == other.disableCoord;
}
/** Returns a hash code value for this object.*/
@Override
public int hashCode() {
return Float.floatToIntBits(getBoost()) ^ clauses.hashCode()
+ getMinimumNumberShouldMatch() + (disableCoord ? 17:0);
}
}
| true | true | public Explanation explain(IndexReader reader, int doc)
throws IOException {
final int minShouldMatch =
BooleanQuery.this.getMinimumNumberShouldMatch();
ComplexExplanation sumExpl = new ComplexExplanation();
sumExpl.setDescription("sum of:");
int coord = 0;
float sum = 0.0f;
boolean fail = false;
int shouldMatchCount = 0;
Iterator<BooleanClause> cIter = clauses.iterator();
for (Iterator<Weight> wIter = weights.iterator(); wIter.hasNext();) {
Weight w = wIter.next();
BooleanClause c = cIter.next();
if (w.scorer(reader, true, true) == null) {
continue;
}
Explanation e = w.explain(reader, doc);
if (e.isMatch()) {
if (!c.isProhibited()) {
sumExpl.addDetail(e);
sum += e.getValue();
coord++;
} else {
Explanation r =
new Explanation(0.0f, "match on prohibited clause (" + c.getQuery().toString() + ")");
r.addDetail(e);
sumExpl.addDetail(r);
fail = true;
}
if (c.getOccur() == Occur.SHOULD)
shouldMatchCount++;
} else if (c.isRequired()) {
Explanation r = new Explanation(0.0f, "no match on required clause (" + c.getQuery().toString() + ")");
r.addDetail(e);
sumExpl.addDetail(r);
fail = true;
}
}
if (fail) {
sumExpl.setMatch(Boolean.FALSE);
sumExpl.setValue(0.0f);
sumExpl.setDescription
("Failure to meet condition(s) of required/prohibited clause(s)");
return sumExpl;
} else if (shouldMatchCount < minShouldMatch) {
sumExpl.setMatch(Boolean.FALSE);
sumExpl.setValue(0.0f);
sumExpl.setDescription("Failure to match minimum number "+
"of optional clauses: " + minShouldMatch);
return sumExpl;
}
sumExpl.setMatch(0 < coord ? Boolean.TRUE : Boolean.FALSE);
sumExpl.setValue(sum);
float coordFactor = similarity.coord(coord, maxCoord);
if (coordFactor == 1.0f) // coord is no-op
return sumExpl; // eliminate wrapper
else {
ComplexExplanation result = new ComplexExplanation(sumExpl.isMatch(),
sum*coordFactor,
"product of:");
result.addDetail(sumExpl);
result.addDetail(new Explanation(coordFactor,
"coord("+coord+"/"+maxCoord+")"));
return result;
}
}
| public Explanation explain(IndexReader reader, int doc)
throws IOException {
final int minShouldMatch =
BooleanQuery.this.getMinimumNumberShouldMatch();
ComplexExplanation sumExpl = new ComplexExplanation();
sumExpl.setDescription("sum of:");
int coord = 0;
float sum = 0.0f;
boolean fail = false;
int shouldMatchCount = 0;
Iterator<BooleanClause> cIter = clauses.iterator();
for (Iterator<Weight> wIter = weights.iterator(); wIter.hasNext();) {
Weight w = wIter.next();
BooleanClause c = cIter.next();
if (w.scorer(reader, true, true) == null) {
if (c.isRequired()) {
fail = true;
Explanation r = new Explanation(0.0f, "no match on required clause (" + c.getQuery().toString() + ")");
sumExpl.addDetail(r);
}
continue;
}
Explanation e = w.explain(reader, doc);
if (e.isMatch()) {
if (!c.isProhibited()) {
sumExpl.addDetail(e);
sum += e.getValue();
coord++;
} else {
Explanation r =
new Explanation(0.0f, "match on prohibited clause (" + c.getQuery().toString() + ")");
r.addDetail(e);
sumExpl.addDetail(r);
fail = true;
}
if (c.getOccur() == Occur.SHOULD)
shouldMatchCount++;
} else if (c.isRequired()) {
Explanation r = new Explanation(0.0f, "no match on required clause (" + c.getQuery().toString() + ")");
r.addDetail(e);
sumExpl.addDetail(r);
fail = true;
}
}
if (fail) {
sumExpl.setMatch(Boolean.FALSE);
sumExpl.setValue(0.0f);
sumExpl.setDescription
("Failure to meet condition(s) of required/prohibited clause(s)");
return sumExpl;
} else if (shouldMatchCount < minShouldMatch) {
sumExpl.setMatch(Boolean.FALSE);
sumExpl.setValue(0.0f);
sumExpl.setDescription("Failure to match minimum number "+
"of optional clauses: " + minShouldMatch);
return sumExpl;
}
sumExpl.setMatch(0 < coord ? Boolean.TRUE : Boolean.FALSE);
sumExpl.setValue(sum);
float coordFactor = similarity.coord(coord, maxCoord);
if (coordFactor == 1.0f) // coord is no-op
return sumExpl; // eliminate wrapper
else {
ComplexExplanation result = new ComplexExplanation(sumExpl.isMatch(),
sum*coordFactor,
"product of:");
result.addDetail(sumExpl);
result.addDetail(new Explanation(coordFactor,
"coord("+coord+"/"+maxCoord+")"));
return result;
}
}
|
diff --git a/src/org/opensolaris/opengrok/analysis/AnalyzerGuru.java b/src/org/opensolaris/opengrok/analysis/AnalyzerGuru.java
index e97b12c..9068f82 100644
--- a/src/org/opensolaris/opengrok/analysis/AnalyzerGuru.java
+++ b/src/org/opensolaris/opengrok/analysis/AnalyzerGuru.java
@@ -1,562 +1,564 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.analysis;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.opensolaris.opengrok.analysis.FileAnalyzer.Genre;
import org.opensolaris.opengrok.analysis.archive.BZip2AnalyzerFactory;
import org.opensolaris.opengrok.analysis.archive.GZIPAnalyzerFactory;
import org.opensolaris.opengrok.analysis.archive.TarAnalyzerFactory;
import org.opensolaris.opengrok.analysis.archive.ZipAnalyzerFactory;
import org.opensolaris.opengrok.analysis.c.CAnalyzerFactory;
import org.opensolaris.opengrok.analysis.data.IgnorantAnalyzerFactory;
import org.opensolaris.opengrok.analysis.data.ImageAnalyzerFactory;
import org.opensolaris.opengrok.analysis.document.TroffAnalyzerFactory;
import org.opensolaris.opengrok.analysis.executables.ELFAnalyzerFactory;
import org.opensolaris.opengrok.analysis.executables.JarAnalyzerFactory;
import org.opensolaris.opengrok.analysis.executables.JavaClassAnalyzerFactory;
import org.opensolaris.opengrok.analysis.java.JavaAnalyzerFactory;
import org.opensolaris.opengrok.analysis.lisp.LispAnalyzerFactory;
import org.opensolaris.opengrok.analysis.plain.PlainAnalyzerFactory;
import org.opensolaris.opengrok.analysis.plain.XMLAnalyzerFactory;
import org.opensolaris.opengrok.analysis.sh.ShAnalyzerFactory;
import org.opensolaris.opengrok.analysis.sql.SQLAnalyzerFactory;
import org.opensolaris.opengrok.analysis.tcl.TclAnalyzerFactory;
import org.opensolaris.opengrok.configuration.Project;
import org.opensolaris.opengrok.history.Annotation;
import org.opensolaris.opengrok.history.HistoryGuru;
import org.opensolaris.opengrok.history.HistoryReader;
import org.opensolaris.opengrok.web.Util;
/**
* Manages and porvides Analyzers as needed. Please see
* <a href="http://www.opensolaris.org/os/project/opengrok/manual/internals/">
* this</a> page for a great description of the purpose of the AnalyzerGuru.
*
* Created on September 22, 2005
* @author Chandan
*/
public class AnalyzerGuru {
/** The default {@code FileAnalyzerFactory} instance. */
private static final FileAnalyzerFactory
DEFAULT_ANALYZER_FACTORY = new FileAnalyzerFactory();
/** Map from file extensions to analyzer factories. */
private static final Map<String, FileAnalyzerFactory>
ext = new HashMap<String, FileAnalyzerFactory>();
// TODO: have a comparator
/** Map from magic strings to analyzer factories. */
private static final SortedMap<String, FileAnalyzerFactory>
magics = new TreeMap<String, FileAnalyzerFactory>();
/**
* List of matcher objects which can be used to determine which analyzer
* factory to use.
*/
private static final List<FileAnalyzerFactory.Matcher>
matchers = new ArrayList<FileAnalyzerFactory.Matcher>();
/** List of all registered {@code FileAnalyzerFactory} instances. */
private static final List<FileAnalyzerFactory>
factories = new ArrayList<FileAnalyzerFactory>();
/*
* If you write your own analyzer please register it here
*/
static {
FileAnalyzerFactory[] analyzers = {
DEFAULT_ANALYZER_FACTORY,
new IgnorantAnalyzerFactory(),
new BZip2AnalyzerFactory(),
new XMLAnalyzerFactory(),
new TroffAnalyzerFactory(),
new ELFAnalyzerFactory(),
new JavaClassAnalyzerFactory(),
new ImageAnalyzerFactory(),
JarAnalyzerFactory.DEFAULT_INSTANCE,
ZipAnalyzerFactory.DEFAULT_INSTANCE,
new TarAnalyzerFactory(),
new CAnalyzerFactory(),
new ShAnalyzerFactory(),
PlainAnalyzerFactory.DEFAULT_INSTANCE,
new GZIPAnalyzerFactory(),
new JavaAnalyzerFactory(),
new LispAnalyzerFactory(),
new TclAnalyzerFactory(),
new SQLAnalyzerFactory(),
};
for (FileAnalyzerFactory analyzer : analyzers) {
registerAnalyzer(analyzer);
}
}
/**
* Register a {@code FileAnalyzerFactory} instance.
*/
private static void registerAnalyzer(FileAnalyzerFactory factory) {
for (String suffix : factory.getSuffixes()) {
FileAnalyzerFactory old = ext.put(suffix, factory);
assert old == null :
"suffix '" + suffix + "' used in multiple analyzers";
}
for (String magic : factory.getMagicStrings()) {
FileAnalyzerFactory old = magics.put(magic, factory);
assert old == null :
"magic '" + magic + "' used in multiple analyzers";
}
matchers.addAll(factory.getMatchers());
factories.add(factory);
}
/**
* Instruct the AnalyzerGuru to use a given analyzer for a given
* file extension.
* @param extension the file-extension to add
* @param factory a factory which creates
* the analyzer to use for the given extension
* (if you pass null as the analyzer, you will disable
* the analyzer used for that extension)
*/
public static void addExtension(String extension,
FileAnalyzerFactory factory) {
if (factory == null) {
ext.remove(extension);
} else {
ext.put(extension, factory);
}
}
/**
* Get the default Analyzer.
*/
public static FileAnalyzer getAnalyzer() {
return DEFAULT_ANALYZER_FACTORY.getAnalyzer();
}
/**
* Get an analyzer suited to analyze a file. This function will reuse
* analyzers since they are costly.
*
* @param in Input stream containing data to be analyzed
* @param file Name of the file to be analyzed
* @return An analyzer suited for that file content
* @throws java.io.IOException If an error occurs while accessing the
* data in the input stream.
*/
public static FileAnalyzer getAnalyzer(InputStream in, String file) throws IOException {
FileAnalyzerFactory factory = find(in, file);
if (factory == null) {
return getAnalyzer();
}
return factory.getAnalyzer();
}
/**
* Create a Lucene document and fill in the required fields
* @param file The file to index
* @param in The data to generate the index for
* @param path Where the file is located (from source root)
* @return The Lucene document to add to the index database
* @throws java.io.IOException If an exception occurs while collecting the
* datas
*/
public Document getDocument(File file, InputStream in, String path,
FileAnalyzer fa) throws IOException {
Document doc = new Document();
String date = DateTools.timeToString(file.lastModified(), DateTools.Resolution.MILLISECOND);
doc.add(new Field("u", Util.uid(path, date), Field.Store.YES, Field.Index.UN_TOKENIZED));
doc.add(new Field("fullpath", file.getAbsolutePath(), Field.Store.YES, Field.Index.TOKENIZED));
try {
HistoryReader hr = HistoryGuru.getInstance().getHistoryReader(file);
if (hr != null) {
doc.add(new Field("hist", hr));
// date = hr.getLastCommentDate() //RFE
}
} catch (IOException e) {
e.printStackTrace();
}
doc.add(new Field("date", date, Field.Store.YES, Field.Index.UN_TOKENIZED));
if (path != null) {
doc.add(new Field("path", path, Field.Store.YES, Field.Index.TOKENIZED));
Project project = Project.getProject(path);
if (project != null) {
doc.add(new Field("project", project.getPath(), Field.Store.YES, Field.Index.TOKENIZED));
}
}
if (fa != null) {
try {
Genre g = fa.getGenre();
if (g == Genre.PLAIN) {
doc.add(new Field("t", "p", Field.Store.YES, Field.Index.UN_TOKENIZED));
} else if (g == Genre.XREFABLE) {
doc.add(new Field("t", "x", Field.Store.YES, Field.Index.UN_TOKENIZED));
} else if (g == Genre.HTML) {
doc.add(new Field("t", "h", Field.Store.YES, Field.Index.UN_TOKENIZED));
}
fa.analyze(doc, in);
} catch (Exception e) {
// Ignoring any errors while analysing
}
}
doc.removeField("fullpath");
return doc;
}
/**
* Get the content type for a named file.
*
* @param in The input stream we want to get the content type for (if
* we cannot determine the content type by the filename)
* @param file The name of the file
* @return The contentType suitable for printing to response.setContentType() or null
* if the factory was not found
* @throws java.io.IOException If an error occurs while accessing the input
* stream.
*/
public static String getContentType(InputStream in, String file) throws IOException {
FileAnalyzerFactory factory = find(in, file);
String type = null;
if (factory != null) {
type = factory.getContentType();
}
return type;
}
/**
* Write a browsable version of the file
*
* @param factory The analyzer factory for this filetype
* @param in The input stream containing the data
* @param out Where to write the result
* @param annotation Annotation information for the file
* @param project Project the file belongs to
* @throws java.io.IOException If an error occurs while creating the
* output
*/
public static void writeXref(FileAnalyzerFactory factory, InputStream in,
Writer out, Annotation annotation, Project project)
throws IOException
{
factory.writeXref(in, out, annotation, project);
}
/**
* Get the genre of a file
*
* @param file The file to inpect
* @return The genre suitable to decide how to display the file
*/
public static Genre getGenre(String file) {
return getGenre(find(file));
}
/**
* Get the genre of a bulk of data
*
* @param in A stream containing the data
* @return The genre suitable to decide how to display the file
* @throws java.io.IOException If an error occurs while getting the content
*/
public static Genre getGenre(InputStream in) throws IOException {
return getGenre(find(in));
}
/**
* Get the genre for a named class (this is most likely an analyzer)
* @param factory the analyzer factory to get the genre for
* @return The genre of this class (null if not found)
*/
public static Genre getGenre(FileAnalyzerFactory factory) {
if (factory != null) {
return factory.getGenre();
}
return null;
}
/**
* Find a {@code FileAnalyzerFactory} with the specified class name. If one
* doesn't exist, create one and register it.
*
* @param factoryClassName name of the factory class
* @return a file analyzer factory
*
* @throws ClassNotFoundException if there is no class with that name
* @throws ClassCastException if the class is not a subclass of {@code
* FileAnalyzerFactory}
* @throws IllegalAccessException if the constructor cannot be accessed
* @throws InstantiationException if the class cannot be instantiated
*/
public static FileAnalyzerFactory findFactory(String factoryClassName)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException
{
return findFactory(Class.forName(factoryClassName));
}
/**
* Find a {@code FileAnalyzerFactory} which is an instance of the specified
* class. If one doesn't exist, create one and register it.
*
* @param factoryClass the factory class
* @return a file analyzer factory
*
* @throws ClassCastException if the class is not a subclass of {@code
* FileAnalyzerFactory}
* @throws IllegalAccessException if the constructor cannot be accessed
* @throws InstantiationException if the class cannot be instantiated
*/
private static FileAnalyzerFactory findFactory(Class factoryClass)
throws InstantiationException, IllegalAccessException
{
for (FileAnalyzerFactory f : factories) {
if (f.getClass() == factoryClass) {
return f;
}
}
FileAnalyzerFactory f =
(FileAnalyzerFactory) factoryClass.newInstance();
registerAnalyzer(f);
return f;
}
/**
* Finds a suitable analyser class for file name. If the analyzer cannot
* be determined by the file extension, try to look at the data in the
* InputStream to find a suitable analyzer.
*
* Use if you just want to find file type.
*
*
* @param in The input stream containing the data
* @param file The file name to get the analyzer for
* @return the analyzer factory to use
* @throws java.io.IOException If a problem occurs while reading the data
*/
public static FileAnalyzerFactory find(InputStream in, String file)
throws IOException
{
FileAnalyzerFactory factory = find(file);
if (factory != null) {
return factory;
}
return find(in);
}
/**
* Finds a suitable analyser class for file name.
*
* @param file The file name to get the analyzer for
* @return the analyzer factory to use
*/
public static FileAnalyzerFactory find(String file) {
int i = 0;
if ((i = file.lastIndexOf('/')) > 0 || (i = file.lastIndexOf('\\')) > 0) {
if (i + 1 < file.length()) {
file = file.substring(i + 1);
}
}
file = file.toUpperCase();
int dotpos = file.lastIndexOf('.');
if (dotpos >= 0) {
FileAnalyzerFactory factory =
ext.get(file.substring(dotpos + 1).toUpperCase());
if (factory != null) {
return factory;
}
}
// file doesn't have any of the extensions we know
return null;
}
/**
* Finds a suitable analyser class for the data in this stream
*
* @param in The stream containing the data to analyze
* @return the analyzer factory to use
* @throws java.io.IOException if an error occurs while reading data from
* the stream
*/
public static FileAnalyzerFactory find(InputStream in) throws IOException {
in.mark(8);
byte[] content = new byte[8];
int len = in.read(content);
in.reset();
if (len < 4) {
return null;
}
FileAnalyzerFactory factory = find(content);
if (factory != null) {
return factory;
}
for (FileAnalyzerFactory.Matcher matcher : matchers) {
FileAnalyzerFactory fac = matcher.isMagic(content, in);
if (fac != null) {
return fac;
}
}
return null;
}
/**
* Finds a suitable analyser class for a magic signature
*
* @param signature the magic signature look up
* @return the analyzer factory to use
*/
public static FileAnalyzerFactory find(byte[] signature) {
char[] chars = new char[signature.length > 8 ? 8 : signature.length];
for (int i = 0; i < chars.length; i++) {
chars[i] = (char) (0xFF & signature[i]);
}
return findMagic(new String(chars));
}
/**
* Get an analyzer by looking up the "magic signature"
* @param signature the signature to look up
* @return the analyzer factory to handle data with this signature
*/
public static FileAnalyzerFactory findMagic(String signature) {
FileAnalyzerFactory a = magics.get(signature);
if (a == null) {
String sigWithoutBOM = stripBOM(signature);
for (Map.Entry<String, FileAnalyzerFactory> entry :
magics.entrySet()) {
if (signature.startsWith(entry.getKey())) {
return entry.getValue();
}
// See if text files have the magic sequence if we remove the
// byte-order marker
if (sigWithoutBOM != null &&
entry.getValue().getGenre() == Genre.PLAIN &&
sigWithoutBOM.startsWith(entry.getKey())) {
return entry.getValue();
}
}
}
return a;
}
/** Byte-order markers. */
private static final String[] BOMS = {
new String(new char[] { 0xEF, 0xBB, 0xBF }), // UTF-8 BOM
new String(new char[] { 0xFE, 0xFF }), // UTF-16BE BOM
new String(new char[] { 0xFF, 0xFE }), // UTF-16LE BOM
};
/**
* Strip away the byte-order marker from the string, if it has one.
*
* @param str the string to remove the BOM from
* @return a string without the byte-order marker, or <code>null</code> if
* the string doesn't start with a BOM
*/
private static String stripBOM(String str) {
for (String bom : BOMS) {
if (str.startsWith(bom)) {
return str.substring(bom.length());
}
}
return null;
}
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) {
AnalyzerGuru af = new AnalyzerGuru();
System.out.println("<pre wrap=true>");
for (String arg : args) {
try {
- FileAnalyzerFactory an = AnalyzerGuru.find(arg);
File f = new File(arg);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
FileAnalyzer fa = AnalyzerGuru.getAnalyzer(in, arg);
System.out.println("\nANALYZER = " + fa);
Document doc = af.getDocument(f, in, arg, fa);
System.out.println("\nDOCUMENT = " + doc);
Iterator iterator = doc.getFields().iterator();
while (iterator.hasNext()) {
org.apache.lucene.document.Field field = (org.apache.lucene.document.Field) iterator.next();
if (field.isTokenized()) {
Reader r = field.readerValue();
if (r == null) {
r = new StringReader(field.stringValue());
}
TokenStream ts = fa.tokenStream(field.name(), r);
System.out.println("\nFIELD = " + field.name() + " TOKEN STREAM = " + ts.getClass().getName());
Token t;
while ((t = ts.next()) != null) {
System.out.print(t.termText());
System.out.print(' ');
}
System.out.println();
}
if (field.isStored()) {
System.out.println("\nFIELD = " + field.name());
if (field.readerValue() == null) {
System.out.println(field.stringValue());
} else {
System.out.println("STORING THE READER");
}
}
}
System.out.println("Writing XREF--------------");
Writer out = new OutputStreamWriter(System.out);
fa.writeXref(out);
out.flush();
- } catch (Exception e) {
+ } catch (IOException e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
+ } catch (RuntimeException e) {
+ System.err.println("RUNTIME ERROR: " + e.getMessage());
+ e.printStackTrace();
}
}
}
}
| false | true | public static void main(String[] args) throws Exception {
AnalyzerGuru af = new AnalyzerGuru();
System.out.println("<pre wrap=true>");
for (String arg : args) {
try {
FileAnalyzerFactory an = AnalyzerGuru.find(arg);
File f = new File(arg);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
FileAnalyzer fa = AnalyzerGuru.getAnalyzer(in, arg);
System.out.println("\nANALYZER = " + fa);
Document doc = af.getDocument(f, in, arg, fa);
System.out.println("\nDOCUMENT = " + doc);
Iterator iterator = doc.getFields().iterator();
while (iterator.hasNext()) {
org.apache.lucene.document.Field field = (org.apache.lucene.document.Field) iterator.next();
if (field.isTokenized()) {
Reader r = field.readerValue();
if (r == null) {
r = new StringReader(field.stringValue());
}
TokenStream ts = fa.tokenStream(field.name(), r);
System.out.println("\nFIELD = " + field.name() + " TOKEN STREAM = " + ts.getClass().getName());
Token t;
while ((t = ts.next()) != null) {
System.out.print(t.termText());
System.out.print(' ');
}
System.out.println();
}
if (field.isStored()) {
System.out.println("\nFIELD = " + field.name());
if (field.readerValue() == null) {
System.out.println(field.stringValue());
} else {
System.out.println("STORING THE READER");
}
}
}
System.out.println("Writing XREF--------------");
Writer out = new OutputStreamWriter(System.out);
fa.writeXref(out);
out.flush();
} catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
}
}
}
| public static void main(String[] args) {
AnalyzerGuru af = new AnalyzerGuru();
System.out.println("<pre wrap=true>");
for (String arg : args) {
try {
File f = new File(arg);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
FileAnalyzer fa = AnalyzerGuru.getAnalyzer(in, arg);
System.out.println("\nANALYZER = " + fa);
Document doc = af.getDocument(f, in, arg, fa);
System.out.println("\nDOCUMENT = " + doc);
Iterator iterator = doc.getFields().iterator();
while (iterator.hasNext()) {
org.apache.lucene.document.Field field = (org.apache.lucene.document.Field) iterator.next();
if (field.isTokenized()) {
Reader r = field.readerValue();
if (r == null) {
r = new StringReader(field.stringValue());
}
TokenStream ts = fa.tokenStream(field.name(), r);
System.out.println("\nFIELD = " + field.name() + " TOKEN STREAM = " + ts.getClass().getName());
Token t;
while ((t = ts.next()) != null) {
System.out.print(t.termText());
System.out.print(' ');
}
System.out.println();
}
if (field.isStored()) {
System.out.println("\nFIELD = " + field.name());
if (field.readerValue() == null) {
System.out.println(field.stringValue());
} else {
System.out.println("STORING THE READER");
}
}
}
System.out.println("Writing XREF--------------");
Writer out = new OutputStreamWriter(System.out);
fa.writeXref(out);
out.flush();
} catch (IOException e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
} catch (RuntimeException e) {
System.err.println("RUNTIME ERROR: " + e.getMessage());
e.printStackTrace();
}
}
}
|
diff --git a/src/com/android/email/mail/transport/SmtpSender.java b/src/com/android/email/mail/transport/SmtpSender.java
index 71a86306..a9b13a66 100644
--- a/src/com/android/email/mail/transport/SmtpSender.java
+++ b/src/com/android/email/mail/transport/SmtpSender.java
@@ -1,334 +1,334 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email.mail.transport;
import android.content.Context;
import android.util.Base64;
import android.util.Log;
import com.android.email.Email;
import com.android.email.mail.Sender;
import com.android.email.mail.Transport;
import com.android.emailcommon.Logging;
import com.android.emailcommon.internet.Rfc822Output;
import com.android.emailcommon.mail.Address;
import com.android.emailcommon.mail.AuthenticationFailedException;
import com.android.emailcommon.mail.CertificateValidationException;
import com.android.emailcommon.mail.MessagingException;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.EmailContent.Message;
import com.android.emailcommon.provider.HostAuth;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import javax.net.ssl.SSLException;
/**
* This class handles all of the protocol-level aspects of sending messages via SMTP.
* TODO Remove dependence upon URI; there's no reason why we need it here
*/
public class SmtpSender extends Sender {
private final Context mContext;
private Transport mTransport;
private String mUsername;
private String mPassword;
/**
* Static named constructor.
*/
public static Sender newInstance(Account account, Context context) throws MessagingException {
return new SmtpSender(context, account);
}
/**
* Creates a new sender for the given account.
*/
private SmtpSender(Context context, Account account) throws MessagingException {
mContext = context;
HostAuth sendAuth = account.getOrCreateHostAuthSend(context);
if (sendAuth == null || !"smtp".equalsIgnoreCase(sendAuth.mProtocol)) {
throw new MessagingException("Unsupported protocol");
}
// defaults, which can be changed by security modifiers
int connectionSecurity = Transport.CONNECTION_SECURITY_NONE;
int defaultPort = 587;
// check for security flags and apply changes
if ((sendAuth.mFlags & HostAuth.FLAG_SSL) != 0) {
connectionSecurity = Transport.CONNECTION_SECURITY_SSL;
defaultPort = 465;
} else if ((sendAuth.mFlags & HostAuth.FLAG_TLS) != 0) {
connectionSecurity = Transport.CONNECTION_SECURITY_TLS;
}
boolean trustCertificates = ((sendAuth.mFlags & HostAuth.FLAG_TRUST_ALL) != 0);
int port = defaultPort;
if (sendAuth.mPort != HostAuth.PORT_UNKNOWN) {
port = sendAuth.mPort;
}
mTransport = new MailTransport("IMAP");
mTransport.setHost(sendAuth.mAddress);
mTransport.setPort(port);
mTransport.setSecurity(connectionSecurity, trustCertificates);
String[] userInfoParts = sendAuth.getLogin();
if (userInfoParts != null) {
mUsername = userInfoParts[0];
mPassword = userInfoParts[1];
}
}
/**
* For testing only. Injects a different transport. The transport should already be set
* up and ready to use. Do not use for real code.
* @param testTransport The Transport to inject and use for all future communication.
*/
/* package */ void setTransport(Transport testTransport) {
mTransport = testTransport;
}
@Override
public void open() throws MessagingException {
try {
mTransport.open();
// Eat the banner
executeSimpleCommand(null);
String localHost = "localhost";
// Try to get local address in the proper format.
InetAddress localAddress = mTransport.getLocalAddress();
if (localAddress != null) {
// Address Literal formatted in accordance to RFC2821 Sec. 4.1.3
StringBuilder sb = new StringBuilder();
sb.append('[');
if (localAddress instanceof Inet6Address) {
sb.append("IPv6:");
}
sb.append(localAddress.getHostAddress());
sb.append(']');
localHost = sb.toString();
}
String result = executeSimpleCommand("EHLO " + localHost);
/*
* TODO may need to add code to fall back to HELO I switched it from
* using HELO on non STARTTLS connections because of AOL's mail
* server. It won't let you use AUTH without EHLO.
* We should really be paying more attention to the capabilities
* and only attempting auth if it's available, and warning the user
* if not.
*/
if (mTransport.canTryTlsSecurity()) {
- if (result.contains("-STARTTLS")) {
+ if (result.contains("STARTTLS")) {
executeSimpleCommand("STARTTLS");
mTransport.reopenTls();
/*
* Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically,
* Exim.
*/
result = executeSimpleCommand("EHLO " + localHost);
} else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "TLS not supported but required");
}
throw new MessagingException(MessagingException.TLS_REQUIRED);
}
}
/*
* result contains the results of the EHLO in concatenated form
*/
boolean authLoginSupported = result.matches(".*AUTH.*LOGIN.*$");
boolean authPlainSupported = result.matches(".*AUTH.*PLAIN.*$");
if (mUsername != null && mUsername.length() > 0 && mPassword != null
&& mPassword.length() > 0) {
if (authPlainSupported) {
saslAuthPlain(mUsername, mPassword);
}
else if (authLoginSupported) {
saslAuthLogin(mUsername, mPassword);
}
else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "No valid authentication mechanism found.");
}
throw new MessagingException(MessagingException.AUTH_REQUIRED);
}
}
} catch (SSLException e) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, e.toString());
}
throw new CertificateValidationException(e.getMessage(), e);
} catch (IOException ioe) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, ioe.toString());
}
throw new MessagingException(MessagingException.IOERROR, ioe.toString());
}
}
@Override
public void sendMessage(long messageId) throws MessagingException {
close();
open();
Message message = Message.restoreMessageWithId(mContext, messageId);
if (message == null) {
throw new MessagingException("Trying to send non-existent message id="
+ Long.toString(messageId));
}
Address from = Address.unpackFirst(message.mFrom);
Address[] to = Address.unpack(message.mTo);
Address[] cc = Address.unpack(message.mCc);
Address[] bcc = Address.unpack(message.mBcc);
try {
executeSimpleCommand("MAIL FROM: " + "<" + from.getAddress() + ">");
for (Address address : to) {
executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">");
}
for (Address address : cc) {
executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">");
}
for (Address address : bcc) {
executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">");
}
executeSimpleCommand("DATA");
// TODO byte stuffing
Rfc822Output.writeTo(mContext, messageId,
new EOLConvertingOutputStream(mTransport.getOutputStream()),
false /* do not use smart reply */,
false /* do not send BCC */);
executeSimpleCommand("\r\n.");
} catch (IOException ioe) {
throw new MessagingException("Unable to send message", ioe);
}
}
/**
* Close the protocol (and the transport below it).
*
* MUST NOT return any exceptions.
*/
@Override
public void close() {
mTransport.close();
}
/**
* Send a single command and wait for a single response. Handles responses that continue
* onto multiple lines. Throws MessagingException if response code is 4xx or 5xx. All traffic
* is logged (if debug logging is enabled) so do not use this function for user ID or password.
*
* @param command The command string to send to the server.
* @return Returns the response string from the server.
*/
private String executeSimpleCommand(String command) throws IOException, MessagingException {
return executeSensitiveCommand(command, null);
}
/**
* Send a single command and wait for a single response. Handles responses that continue
* onto multiple lines. Throws MessagingException if response code is 4xx or 5xx.
*
* @param command The command string to send to the server.
* @param sensitiveReplacement If the command includes sensitive data (e.g. authentication)
* please pass a replacement string here (for logging).
* @return Returns the response string from the server.
*/
private String executeSensitiveCommand(String command, String sensitiveReplacement)
throws IOException, MessagingException {
if (command != null) {
mTransport.writeLine(command, sensitiveReplacement);
}
String line = mTransport.readLine();
String result = line;
while (line.length() >= 4 && line.charAt(3) == '-') {
line = mTransport.readLine();
result += line.substring(3);
}
if (result.length() > 0) {
char c = result.charAt(0);
if ((c == '4') || (c == '5')) {
throw new MessagingException(result);
}
}
return result;
}
// C: AUTH LOGIN
// S: 334 VXNlcm5hbWU6
// C: d2VsZG9u
// S: 334 UGFzc3dvcmQ6
// C: dzNsZDBu
// S: 235 2.0.0 OK Authenticated
//
// Lines 2-5 of the conversation contain base64-encoded information. The same conversation, with base64 strings decoded, reads:
//
//
// C: AUTH LOGIN
// S: 334 Username:
// C: weldon
// S: 334 Password:
// C: w3ld0n
// S: 235 2.0.0 OK Authenticated
private void saslAuthLogin(String username, String password) throws MessagingException,
AuthenticationFailedException, IOException {
try {
executeSimpleCommand("AUTH LOGIN");
executeSensitiveCommand(
Base64.encodeToString(username.getBytes(), Base64.NO_WRAP),
"/username redacted/");
executeSensitiveCommand(
Base64.encodeToString(password.getBytes(), Base64.NO_WRAP),
"/password redacted/");
}
catch (MessagingException me) {
if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') {
throw new AuthenticationFailedException(me.getMessage());
}
throw me;
}
}
private void saslAuthPlain(String username, String password) throws MessagingException,
AuthenticationFailedException, IOException {
byte[] data = ("\000" + username + "\000" + password).getBytes();
data = Base64.encode(data, Base64.NO_WRAP);
try {
executeSensitiveCommand("AUTH PLAIN " + new String(data), "AUTH PLAIN /redacted/");
}
catch (MessagingException me) {
if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') {
throw new AuthenticationFailedException(me.getMessage());
}
throw me;
}
}
}
| true | true | public void open() throws MessagingException {
try {
mTransport.open();
// Eat the banner
executeSimpleCommand(null);
String localHost = "localhost";
// Try to get local address in the proper format.
InetAddress localAddress = mTransport.getLocalAddress();
if (localAddress != null) {
// Address Literal formatted in accordance to RFC2821 Sec. 4.1.3
StringBuilder sb = new StringBuilder();
sb.append('[');
if (localAddress instanceof Inet6Address) {
sb.append("IPv6:");
}
sb.append(localAddress.getHostAddress());
sb.append(']');
localHost = sb.toString();
}
String result = executeSimpleCommand("EHLO " + localHost);
/*
* TODO may need to add code to fall back to HELO I switched it from
* using HELO on non STARTTLS connections because of AOL's mail
* server. It won't let you use AUTH without EHLO.
* We should really be paying more attention to the capabilities
* and only attempting auth if it's available, and warning the user
* if not.
*/
if (mTransport.canTryTlsSecurity()) {
if (result.contains("-STARTTLS")) {
executeSimpleCommand("STARTTLS");
mTransport.reopenTls();
/*
* Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically,
* Exim.
*/
result = executeSimpleCommand("EHLO " + localHost);
} else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "TLS not supported but required");
}
throw new MessagingException(MessagingException.TLS_REQUIRED);
}
}
/*
* result contains the results of the EHLO in concatenated form
*/
boolean authLoginSupported = result.matches(".*AUTH.*LOGIN.*$");
boolean authPlainSupported = result.matches(".*AUTH.*PLAIN.*$");
if (mUsername != null && mUsername.length() > 0 && mPassword != null
&& mPassword.length() > 0) {
if (authPlainSupported) {
saslAuthPlain(mUsername, mPassword);
}
else if (authLoginSupported) {
saslAuthLogin(mUsername, mPassword);
}
else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "No valid authentication mechanism found.");
}
throw new MessagingException(MessagingException.AUTH_REQUIRED);
}
}
} catch (SSLException e) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, e.toString());
}
throw new CertificateValidationException(e.getMessage(), e);
} catch (IOException ioe) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, ioe.toString());
}
throw new MessagingException(MessagingException.IOERROR, ioe.toString());
}
}
| public void open() throws MessagingException {
try {
mTransport.open();
// Eat the banner
executeSimpleCommand(null);
String localHost = "localhost";
// Try to get local address in the proper format.
InetAddress localAddress = mTransport.getLocalAddress();
if (localAddress != null) {
// Address Literal formatted in accordance to RFC2821 Sec. 4.1.3
StringBuilder sb = new StringBuilder();
sb.append('[');
if (localAddress instanceof Inet6Address) {
sb.append("IPv6:");
}
sb.append(localAddress.getHostAddress());
sb.append(']');
localHost = sb.toString();
}
String result = executeSimpleCommand("EHLO " + localHost);
/*
* TODO may need to add code to fall back to HELO I switched it from
* using HELO on non STARTTLS connections because of AOL's mail
* server. It won't let you use AUTH without EHLO.
* We should really be paying more attention to the capabilities
* and only attempting auth if it's available, and warning the user
* if not.
*/
if (mTransport.canTryTlsSecurity()) {
if (result.contains("STARTTLS")) {
executeSimpleCommand("STARTTLS");
mTransport.reopenTls();
/*
* Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically,
* Exim.
*/
result = executeSimpleCommand("EHLO " + localHost);
} else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "TLS not supported but required");
}
throw new MessagingException(MessagingException.TLS_REQUIRED);
}
}
/*
* result contains the results of the EHLO in concatenated form
*/
boolean authLoginSupported = result.matches(".*AUTH.*LOGIN.*$");
boolean authPlainSupported = result.matches(".*AUTH.*PLAIN.*$");
if (mUsername != null && mUsername.length() > 0 && mPassword != null
&& mPassword.length() > 0) {
if (authPlainSupported) {
saslAuthPlain(mUsername, mPassword);
}
else if (authLoginSupported) {
saslAuthLogin(mUsername, mPassword);
}
else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "No valid authentication mechanism found.");
}
throw new MessagingException(MessagingException.AUTH_REQUIRED);
}
}
} catch (SSLException e) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, e.toString());
}
throw new CertificateValidationException(e.getMessage(), e);
} catch (IOException ioe) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, ioe.toString());
}
throw new MessagingException(MessagingException.IOERROR, ioe.toString());
}
}
|
diff --git a/java/com/vexsoftware/votifier/Votifier.java b/java/com/vexsoftware/votifier/Votifier.java
index 3381d1c..b447555 100644
--- a/java/com/vexsoftware/votifier/Votifier.java
+++ b/java/com/vexsoftware/votifier/Votifier.java
@@ -1,230 +1,231 @@
/*
* Copyright (C) 2012 Vex Software LLC
* This file is part of Votifier.
*
* Votifier 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.
*
* Votifier 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 Votifier. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vexsoftware.votifier;
import java.io.*;
import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.*;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import com.vexsoftware.votifier.crypto.RSAIO;
import com.vexsoftware.votifier.crypto.RSAKeygen;
import com.vexsoftware.votifier.model.ListenerLoader;
import com.vexsoftware.votifier.model.VoteListener;
import com.vexsoftware.votifier.net.VoteReceiver;
/**
* The main Votifier plugin class.
*
* @author Blake Beaupain
* @author Kramer Campbell
*/
public class Votifier extends JavaPlugin {
/** The current Votifier version. */
public static final String VERSION = "1.8";
/** The logger instance. */
private static final Logger LOG = Logger.getLogger("Votifier");
/** Log entry prefix */
private static final String logPrefix = "[Votifier] ";
/** The Votifier instance. */
private static Votifier instance;
/** The vote listeners. */
private final List<VoteListener> listeners = new ArrayList<VoteListener>();
/** The vote receiver. */
private VoteReceiver voteReceiver;
/** The RSA key pair. */
private KeyPair keyPair;
/** Debug mode flag */
private boolean debug;
/**
* Attach custom log filter to logger.
*/
static {
LOG.setFilter(new LogFilter(logPrefix));
}
@Override
public void onEnable() {
Votifier.instance = this;
// Handle configuration.
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
File config = new File(getDataFolder() + "/config.yml");
YamlConfiguration cfg = YamlConfiguration.loadConfiguration(config);
File rsaDirectory = new File(getDataFolder() + "/rsa");
- String listenerDirectory = getDataFolder() + "/listeners";
+ // Replace to remove a bug with Windows paths - SmilingDevil
+ String listenerDirectory = getDataFolder().toString().replace("\\", "/") + "/listeners";
/*
* Use IP address from server.properties as a default for
* configurations. Do not use InetAddress.getLocalHost() as it most
* likely will return the main server address instead of the address
* assigned to the server.
*/
String hostAddr = Bukkit.getServer().getIp();
if (hostAddr == null || hostAddr.length() == 0)
hostAddr = "0.0.0.0";
/*
* Create configuration file if it does not exists; otherwise, load it
*/
if (!config.exists()) {
try {
// First time run - do some initialization.
LOG.info("Configuring Votifier for the first time...");
// Initialize the configuration file.
config.createNewFile();
cfg.set("host", hostAddr);
cfg.set("port", 8192);
cfg.set("debug", false);
/*
* Remind hosted server admins to be sure they have the right
* port number.
*/
LOG.info("------------------------------------------------------------------------------");
LOG.info("Assigning Votifier to listen on port 8192. If you are hosting Craftbukkit on a");
LOG.info("shared server please check with your hosting provider to verify that this port");
LOG.info("is available for your use. Chances are that your hosting provider will assign");
LOG.info("a different port, which you need to specify in config.yml");
LOG.info("------------------------------------------------------------------------------");
cfg.set("listener_folder", listenerDirectory);
cfg.save(config);
} catch (Exception ex) {
LOG.log(Level.SEVERE, "Error creating configuration file", ex);
gracefulExit();
return;
}
} else {
// Load configuration.
cfg = YamlConfiguration.loadConfiguration(config);
}
/*
* Create RSA directory and keys if it does not exist; otherwise, read
* keys.
*/
try {
if (!rsaDirectory.exists()) {
rsaDirectory.mkdir();
new File(listenerDirectory).mkdir();
keyPair = RSAKeygen.generate(2048);
RSAIO.save(rsaDirectory, keyPair);
} else {
keyPair = RSAIO.load(rsaDirectory);
}
} catch (Exception ex) {
LOG.log(Level.SEVERE,
"Error reading configuration file or RSA keys", ex);
gracefulExit();
return;
}
// Load the vote listeners.
listenerDirectory = cfg.getString("listener_folder");
listeners.addAll(ListenerLoader.load(listenerDirectory));
// Initialize the receiver.
String host = cfg.getString("host", hostAddr);
int port = cfg.getInt("port", 8192);
debug = cfg.getBoolean("debug", false);
if (debug)
LOG.info("DEBUG mode enabled!");
try {
voteReceiver = new VoteReceiver(this, host, port);
voteReceiver.start();
LOG.info("Votifier enabled.");
} catch (Exception ex) {
gracefulExit();
return;
}
}
@Override
public void onDisable() {
// Interrupt the vote receiver.
if (voteReceiver != null) {
voteReceiver.shutdown();
}
LOG.info("Votifier disabled.");
}
private void gracefulExit() {
LOG.log(Level.SEVERE, "Votifier did not initialize properly!");
}
/**
* Gets the instance.
*
* @return The instance
*/
public static Votifier getInstance() {
return instance;
}
/**
* Gets the listeners.
*
* @return The listeners
*/
public List<VoteListener> getListeners() {
return listeners;
}
/**
* Gets the vote receiver.
*
* @return The vote receiver
*/
public VoteReceiver getVoteReceiver() {
return voteReceiver;
}
/**
* Gets the keyPair.
*
* @return The keyPair
*/
public KeyPair getKeyPair() {
return keyPair;
}
public boolean isDebug() {
return debug;
}
}
| true | true | public void onEnable() {
Votifier.instance = this;
// Handle configuration.
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
File config = new File(getDataFolder() + "/config.yml");
YamlConfiguration cfg = YamlConfiguration.loadConfiguration(config);
File rsaDirectory = new File(getDataFolder() + "/rsa");
String listenerDirectory = getDataFolder() + "/listeners";
/*
* Use IP address from server.properties as a default for
* configurations. Do not use InetAddress.getLocalHost() as it most
* likely will return the main server address instead of the address
* assigned to the server.
*/
String hostAddr = Bukkit.getServer().getIp();
if (hostAddr == null || hostAddr.length() == 0)
hostAddr = "0.0.0.0";
/*
* Create configuration file if it does not exists; otherwise, load it
*/
if (!config.exists()) {
try {
// First time run - do some initialization.
LOG.info("Configuring Votifier for the first time...");
// Initialize the configuration file.
config.createNewFile();
cfg.set("host", hostAddr);
cfg.set("port", 8192);
cfg.set("debug", false);
/*
* Remind hosted server admins to be sure they have the right
* port number.
*/
LOG.info("------------------------------------------------------------------------------");
LOG.info("Assigning Votifier to listen on port 8192. If you are hosting Craftbukkit on a");
LOG.info("shared server please check with your hosting provider to verify that this port");
LOG.info("is available for your use. Chances are that your hosting provider will assign");
LOG.info("a different port, which you need to specify in config.yml");
LOG.info("------------------------------------------------------------------------------");
cfg.set("listener_folder", listenerDirectory);
cfg.save(config);
} catch (Exception ex) {
LOG.log(Level.SEVERE, "Error creating configuration file", ex);
gracefulExit();
return;
}
} else {
// Load configuration.
cfg = YamlConfiguration.loadConfiguration(config);
}
/*
* Create RSA directory and keys if it does not exist; otherwise, read
* keys.
*/
try {
if (!rsaDirectory.exists()) {
rsaDirectory.mkdir();
new File(listenerDirectory).mkdir();
keyPair = RSAKeygen.generate(2048);
RSAIO.save(rsaDirectory, keyPair);
} else {
keyPair = RSAIO.load(rsaDirectory);
}
} catch (Exception ex) {
LOG.log(Level.SEVERE,
"Error reading configuration file or RSA keys", ex);
gracefulExit();
return;
}
// Load the vote listeners.
listenerDirectory = cfg.getString("listener_folder");
listeners.addAll(ListenerLoader.load(listenerDirectory));
// Initialize the receiver.
String host = cfg.getString("host", hostAddr);
int port = cfg.getInt("port", 8192);
debug = cfg.getBoolean("debug", false);
if (debug)
LOG.info("DEBUG mode enabled!");
try {
voteReceiver = new VoteReceiver(this, host, port);
voteReceiver.start();
LOG.info("Votifier enabled.");
} catch (Exception ex) {
gracefulExit();
return;
}
}
| public void onEnable() {
Votifier.instance = this;
// Handle configuration.
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
File config = new File(getDataFolder() + "/config.yml");
YamlConfiguration cfg = YamlConfiguration.loadConfiguration(config);
File rsaDirectory = new File(getDataFolder() + "/rsa");
// Replace to remove a bug with Windows paths - SmilingDevil
String listenerDirectory = getDataFolder().toString().replace("\\", "/") + "/listeners";
/*
* Use IP address from server.properties as a default for
* configurations. Do not use InetAddress.getLocalHost() as it most
* likely will return the main server address instead of the address
* assigned to the server.
*/
String hostAddr = Bukkit.getServer().getIp();
if (hostAddr == null || hostAddr.length() == 0)
hostAddr = "0.0.0.0";
/*
* Create configuration file if it does not exists; otherwise, load it
*/
if (!config.exists()) {
try {
// First time run - do some initialization.
LOG.info("Configuring Votifier for the first time...");
// Initialize the configuration file.
config.createNewFile();
cfg.set("host", hostAddr);
cfg.set("port", 8192);
cfg.set("debug", false);
/*
* Remind hosted server admins to be sure they have the right
* port number.
*/
LOG.info("------------------------------------------------------------------------------");
LOG.info("Assigning Votifier to listen on port 8192. If you are hosting Craftbukkit on a");
LOG.info("shared server please check with your hosting provider to verify that this port");
LOG.info("is available for your use. Chances are that your hosting provider will assign");
LOG.info("a different port, which you need to specify in config.yml");
LOG.info("------------------------------------------------------------------------------");
cfg.set("listener_folder", listenerDirectory);
cfg.save(config);
} catch (Exception ex) {
LOG.log(Level.SEVERE, "Error creating configuration file", ex);
gracefulExit();
return;
}
} else {
// Load configuration.
cfg = YamlConfiguration.loadConfiguration(config);
}
/*
* Create RSA directory and keys if it does not exist; otherwise, read
* keys.
*/
try {
if (!rsaDirectory.exists()) {
rsaDirectory.mkdir();
new File(listenerDirectory).mkdir();
keyPair = RSAKeygen.generate(2048);
RSAIO.save(rsaDirectory, keyPair);
} else {
keyPair = RSAIO.load(rsaDirectory);
}
} catch (Exception ex) {
LOG.log(Level.SEVERE,
"Error reading configuration file or RSA keys", ex);
gracefulExit();
return;
}
// Load the vote listeners.
listenerDirectory = cfg.getString("listener_folder");
listeners.addAll(ListenerLoader.load(listenerDirectory));
// Initialize the receiver.
String host = cfg.getString("host", hostAddr);
int port = cfg.getInt("port", 8192);
debug = cfg.getBoolean("debug", false);
if (debug)
LOG.info("DEBUG mode enabled!");
try {
voteReceiver = new VoteReceiver(this, host, port);
voteReceiver.start();
LOG.info("Votifier enabled.");
} catch (Exception ex) {
gracefulExit();
return;
}
}
|
diff --git a/src/org/apache/pig/tools/pigstats/PigStats.java b/src/org/apache/pig/tools/pigstats/PigStats.java
index 4807d85d..f0b87c70 100644
--- a/src/org/apache/pig/tools/pigstats/PigStats.java
+++ b/src/org/apache/pig/tools/pigstats/PigStats.java
@@ -1,262 +1,262 @@
/*
* 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.pig.tools.pigstats;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.hadoop.mapred.Counters;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.Counters.Counter;
import org.apache.hadoop.mapred.Counters.Group;
import org.apache.hadoop.mapred.jobcontrol.Job;
import org.apache.hadoop.mapred.jobcontrol.JobControl;
import org.apache.pig.ExecType;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans.MROperPlan;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.PhysicalOperator;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhysicalPlan;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POStore;
import org.apache.pig.backend.local.executionengine.physicalLayer.counters.POCounter;
import org.apache.pig.impl.io.FileSpec;
import org.apache.pig.impl.util.ObjectSerializer;
public class PigStats {
MROperPlan mrp;
PhysicalPlan php;
JobControl jc;
JobClient jobClient;
Map<String, Map<String, String>> stats = new HashMap<String, Map<String,String>>();
String lastJobID;
ExecType mode;
public void setMROperatorPlan(MROperPlan mrp) {
this.mrp = mrp;
}
public void setJobControl(JobControl jc) {
this.jc = jc;
}
public void setJobClient(JobClient jobClient) {
this.jobClient = jobClient;
}
public String getMRPlan() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mrp.dump(new PrintStream(baos));
return baos.toString();
}
public void setExecType(ExecType mode) {
this.mode = mode;
}
public void setPhysicalPlan(PhysicalPlan php) {
this.php = php;
}
public String getPhysicalPlan() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
php.explain(baos);
return baos.toString();
}
public Map<String, Map<String, String>> accumulateStats() throws ExecException {
if(mode == ExecType.MAPREDUCE)
return accumulateMRStats();
else if(mode == ExecType.LOCAL)
return accumulateLocalStats();
else
throw new RuntimeException("Unrecognized mode. Either MapReduce or Local mode expected.");
}
private Map<String, Map<String, String>> accumulateLocalStats() {
//The counter placed before a store in the local plan should be able to get the number of records
for(PhysicalOperator op : php.getLeaves()) {
Map<String, String> jobStats = new HashMap<String, String>();
stats.put(op.toString(), jobStats);
POCounter counter = (POCounter) php.getPredecessors(op).get(0);
jobStats.put("PIG_STATS_LOCAL_OUTPUT_RECORDS", (Long.valueOf(counter.getCount())).toString());
jobStats.put("PIG_STATS_LOCAL_BYTES_WRITTEN", (Long.valueOf((new File(((POStore)op).getSFile().getFileName())).length())).toString());
}
return stats;
}
private Map<String, Map<String, String>> accumulateMRStats() throws ExecException {
Job lastJob = getLastJob(jc.getSuccessfulJobs());
for(Job job : jc.getSuccessfulJobs()) {
JobConf jobConf = job.getJobConf();
RunningJob rj = null;
try {
rj = jobClient.getJob(job.getAssignedJobID());
} catch (IOException e1) {
String error = "Unable to get the job statistics from JobClient.";
throw new ExecException(error, e1);
}
if(rj == null)
continue;
Map<String, String> jobStats = new HashMap<String, String>();
stats.put(job.getAssignedJobID().toString(), jobStats);
try {
PhysicalPlan plan = (PhysicalPlan) ObjectSerializer.deserialize(jobConf.get("pig.mapPlan"));
jobStats.put("PIG_STATS_MAP_PLAN", plan.toString());
plan = (PhysicalPlan) ObjectSerializer.deserialize(jobConf.get("pig.combinePlan"));
if(plan != null) {
jobStats.put("PIG_STATS_COMBINE_PLAN", plan.toString());
}
plan = (PhysicalPlan) ObjectSerializer.deserialize(jobConf.get("pig.reducePlan"));
if(plan != null) {
jobStats.put("PIG_STATS_REDUCE_PLAN", plan.toString());
}
} catch (IOException e2) {
String error = "Error deserializing plans from the JobConf.";
throw new RuntimeException(error, e2);
}
Counters counters = null;
try {
counters = rj.getCounters();
Counters.Group taskgroup = counters.getGroup("org.apache.hadoop.mapred.Task$Counter");
Counters.Group hdfsgroup = counters.getGroup("org.apache.hadoop.mapred.Task$FileSystemCounter");
System.out.println("BYTES WRITTEN : " + hdfsgroup.getCounterForName("HDFS_WRITE").getCounter());
jobStats.put("PIG_STATS_MAP_INPUT_RECORDS", (Long.valueOf(taskgroup.getCounterForName("MAP_INPUT_RECORDS").getCounter())).toString());
jobStats.put("PIG_STATS_MAP_OUTPUT_RECORDS", (Long.valueOf(taskgroup.getCounterForName("MAP_OUTPUT_RECORDS").getCounter())).toString());
jobStats.put("PIG_STATS_REDUCE_INPUT_RECORDS", (Long.valueOf(taskgroup.getCounterForName("REDUCE_INPUT_RECORDS").getCounter())).toString());
jobStats.put("PIG_STATS_REDUCE_OUTPUT_RECORDS", (Long.valueOf(taskgroup.getCounterForName("REDUCE_OUTPUT_RECORDS").getCounter())).toString());
jobStats.put("PIG_STATS_BYTES_WRITTEN", (Long.valueOf(hdfsgroup.getCounterForName("HDFS_WRITE").getCounter())).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
String error = "Unable to get the counters.";
throw new ExecException(error, e);
}
}
- lastJobID = lastJob.getAssignedJobID().toString();
+ if (lastJob != null) lastJobID = lastJob.getAssignedJobID().toString();
return stats;
}
private Job getLastJob(List<Job> jobs) {
Set<Job> temp = new HashSet<Job>();
for(Job job : jobs) {
if(job.getDependingJobs() != null && job.getDependingJobs().size() > 0)
temp.addAll(job.getDependingJobs());
}
//difference between temp and jobs would be the set of leaves
//we can safely assume there would be only one leaf
for(Job job : jobs) {
if(temp.contains(job))
continue;
else
//this means a leaf
return job;
}
return null;
}
public String getLastJobID() {
return lastJobID;
}
public Map<String, Map<String, String>> getPigStats() {
return stats;
}
public long getRecordsWritten() {
if(mode == ExecType.LOCAL)
return getRecordsCountLocal();
else if(mode == ExecType.MAPREDUCE)
return getRecordsCountMR();
else
throw new RuntimeException("Unrecognized mode. Either MapReduce or Local mode expected.");
}
private long getRecordsCountLocal() {
//System.out.println(getPhysicalPlan());
//because of the nature of the parser, there will always be only one store
for(PhysicalOperator op : php.getLeaves()) {
return Long.parseLong(stats.get(op.toString()).get("PIG_STATS_LOCAL_OUTPUT_RECORDS"));
}
return 0;
}
/**
* Returns the no. of records written by the pig script in MR mode
* @return
*/
private long getRecordsCountMR() {
String reducePlan = stats.get(lastJobID).get("PIG_STATS_REDUCE_PLAN");
String records = null;
if(reducePlan == null) {
records = stats.get(lastJobID).get("PIG_STATS_MAP_OUTPUT_RECORDS");
} else {
records = stats.get(lastJobID).get("PIG_STATS_REDUCE_OUTPUT_RECORDS");
}
return Long.parseLong(records);
}
public long getBytesWritten() {
if(mode == ExecType.LOCAL) {
return getLocalBytesWritten();
} else if(mode == ExecType.MAPREDUCE) {
return getMapReduceBytesWritten();
} else {
throw new RuntimeException("Unrecognized mode. Either MapReduce or Local mode expected.");
}
}
private long getLocalBytesWritten() {
for(PhysicalOperator op : php.getLeaves())
return Long.parseLong(stats.get(op.toString()).get("PIG_STATS_LOCAL_BYTES_WRITTEN"));
return 0;
}
private long getMapReduceBytesWritten() {
return Long.parseLong(stats.get(lastJobID).get("PIG_STATS_BYTES_WRITTEN"));
}
}
| true | true | private Map<String, Map<String, String>> accumulateMRStats() throws ExecException {
Job lastJob = getLastJob(jc.getSuccessfulJobs());
for(Job job : jc.getSuccessfulJobs()) {
JobConf jobConf = job.getJobConf();
RunningJob rj = null;
try {
rj = jobClient.getJob(job.getAssignedJobID());
} catch (IOException e1) {
String error = "Unable to get the job statistics from JobClient.";
throw new ExecException(error, e1);
}
if(rj == null)
continue;
Map<String, String> jobStats = new HashMap<String, String>();
stats.put(job.getAssignedJobID().toString(), jobStats);
try {
PhysicalPlan plan = (PhysicalPlan) ObjectSerializer.deserialize(jobConf.get("pig.mapPlan"));
jobStats.put("PIG_STATS_MAP_PLAN", plan.toString());
plan = (PhysicalPlan) ObjectSerializer.deserialize(jobConf.get("pig.combinePlan"));
if(plan != null) {
jobStats.put("PIG_STATS_COMBINE_PLAN", plan.toString());
}
plan = (PhysicalPlan) ObjectSerializer.deserialize(jobConf.get("pig.reducePlan"));
if(plan != null) {
jobStats.put("PIG_STATS_REDUCE_PLAN", plan.toString());
}
} catch (IOException e2) {
String error = "Error deserializing plans from the JobConf.";
throw new RuntimeException(error, e2);
}
Counters counters = null;
try {
counters = rj.getCounters();
Counters.Group taskgroup = counters.getGroup("org.apache.hadoop.mapred.Task$Counter");
Counters.Group hdfsgroup = counters.getGroup("org.apache.hadoop.mapred.Task$FileSystemCounter");
System.out.println("BYTES WRITTEN : " + hdfsgroup.getCounterForName("HDFS_WRITE").getCounter());
jobStats.put("PIG_STATS_MAP_INPUT_RECORDS", (Long.valueOf(taskgroup.getCounterForName("MAP_INPUT_RECORDS").getCounter())).toString());
jobStats.put("PIG_STATS_MAP_OUTPUT_RECORDS", (Long.valueOf(taskgroup.getCounterForName("MAP_OUTPUT_RECORDS").getCounter())).toString());
jobStats.put("PIG_STATS_REDUCE_INPUT_RECORDS", (Long.valueOf(taskgroup.getCounterForName("REDUCE_INPUT_RECORDS").getCounter())).toString());
jobStats.put("PIG_STATS_REDUCE_OUTPUT_RECORDS", (Long.valueOf(taskgroup.getCounterForName("REDUCE_OUTPUT_RECORDS").getCounter())).toString());
jobStats.put("PIG_STATS_BYTES_WRITTEN", (Long.valueOf(hdfsgroup.getCounterForName("HDFS_WRITE").getCounter())).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
String error = "Unable to get the counters.";
throw new ExecException(error, e);
}
}
lastJobID = lastJob.getAssignedJobID().toString();
return stats;
}
| private Map<String, Map<String, String>> accumulateMRStats() throws ExecException {
Job lastJob = getLastJob(jc.getSuccessfulJobs());
for(Job job : jc.getSuccessfulJobs()) {
JobConf jobConf = job.getJobConf();
RunningJob rj = null;
try {
rj = jobClient.getJob(job.getAssignedJobID());
} catch (IOException e1) {
String error = "Unable to get the job statistics from JobClient.";
throw new ExecException(error, e1);
}
if(rj == null)
continue;
Map<String, String> jobStats = new HashMap<String, String>();
stats.put(job.getAssignedJobID().toString(), jobStats);
try {
PhysicalPlan plan = (PhysicalPlan) ObjectSerializer.deserialize(jobConf.get("pig.mapPlan"));
jobStats.put("PIG_STATS_MAP_PLAN", plan.toString());
plan = (PhysicalPlan) ObjectSerializer.deserialize(jobConf.get("pig.combinePlan"));
if(plan != null) {
jobStats.put("PIG_STATS_COMBINE_PLAN", plan.toString());
}
plan = (PhysicalPlan) ObjectSerializer.deserialize(jobConf.get("pig.reducePlan"));
if(plan != null) {
jobStats.put("PIG_STATS_REDUCE_PLAN", plan.toString());
}
} catch (IOException e2) {
String error = "Error deserializing plans from the JobConf.";
throw new RuntimeException(error, e2);
}
Counters counters = null;
try {
counters = rj.getCounters();
Counters.Group taskgroup = counters.getGroup("org.apache.hadoop.mapred.Task$Counter");
Counters.Group hdfsgroup = counters.getGroup("org.apache.hadoop.mapred.Task$FileSystemCounter");
System.out.println("BYTES WRITTEN : " + hdfsgroup.getCounterForName("HDFS_WRITE").getCounter());
jobStats.put("PIG_STATS_MAP_INPUT_RECORDS", (Long.valueOf(taskgroup.getCounterForName("MAP_INPUT_RECORDS").getCounter())).toString());
jobStats.put("PIG_STATS_MAP_OUTPUT_RECORDS", (Long.valueOf(taskgroup.getCounterForName("MAP_OUTPUT_RECORDS").getCounter())).toString());
jobStats.put("PIG_STATS_REDUCE_INPUT_RECORDS", (Long.valueOf(taskgroup.getCounterForName("REDUCE_INPUT_RECORDS").getCounter())).toString());
jobStats.put("PIG_STATS_REDUCE_OUTPUT_RECORDS", (Long.valueOf(taskgroup.getCounterForName("REDUCE_OUTPUT_RECORDS").getCounter())).toString());
jobStats.put("PIG_STATS_BYTES_WRITTEN", (Long.valueOf(hdfsgroup.getCounterForName("HDFS_WRITE").getCounter())).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
String error = "Unable to get the counters.";
throw new ExecException(error, e);
}
}
if (lastJob != null) lastJobID = lastJob.getAssignedJobID().toString();
return stats;
}
|
diff --git a/addon-maven/src/main/java/org/springframework/roo/addon/maven/MavenCommands.java b/addon-maven/src/main/java/org/springframework/roo/addon/maven/MavenCommands.java
index 037da4c7b..54872acb3 100644
--- a/addon-maven/src/main/java/org/springframework/roo/addon/maven/MavenCommands.java
+++ b/addon-maven/src/main/java/org/springframework/roo/addon/maven/MavenCommands.java
@@ -1,167 +1,170 @@
package org.springframework.roo.addon.maven;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Logger;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.springframework.roo.model.JavaPackage;
import org.springframework.roo.process.manager.ActiveProcessManager;
import org.springframework.roo.process.manager.ProcessManager;
import org.springframework.roo.shell.CliAvailabilityIndicator;
import org.springframework.roo.shell.CliCommand;
import org.springframework.roo.shell.CliOption;
import org.springframework.roo.shell.CommandMarker;
import org.springframework.roo.support.logging.HandlerUtils;
import org.springframework.roo.support.util.Assert;
/**
* Shell commands for {@link MavenOperations} and also to launch native mvn commands.
*
* @author Ben Alex
* @since 1.0
*/
@Component
@Service
public class MavenCommands implements CommandMarker {
private static final Logger logger = HandlerUtils.getLogger(MavenCommands.class);
@Reference private MavenOperations mavenOperations;
@Reference private ProcessManager processManager;
@CliAvailabilityIndicator("project")
public boolean isCreateProjectAvailable() {
return mavenOperations.isCreateProjectAvailable();
}
@CliCommand(value = "project", help = "Creates a new project")
public void createProject(
@CliOption(key = { "", "topLevelPackage" }, mandatory = true, optionContext = "update", help = "The uppermost package name (this becomes the <groupId> in Maven and also the '~' value when using Roo's shell)") JavaPackage topLevelPackage,
@CliOption(key = "projectName", mandatory = false, help = "The name of the project (last segment of package name used as default)") String projectName,
@CliOption(key = "java", mandatory = false, help = "Forces a particular major version of Java to be used (will be auto-detected if unspecified; specify 5 or 6 or 7 only)") Integer majorJavaVersion) {
mavenOperations.createProject(topLevelPackage, projectName, majorJavaVersion);
}
@CliAvailabilityIndicator({ "dependency add", "dependency remove" })
public boolean isDependencyModificationAllowed() {
return mavenOperations.isDependencyModificationAllowed();
}
@CliCommand(value = "dependency add", help = "Adds a new dependency to the Maven project object model (POM)")
public void addDependency(
@CliOption(key = "groupId", mandatory = true, help = "The group ID of the dependency") String groupId,
@CliOption(key = "artifactId", mandatory = true, help = "The artifact ID of the dependency") String artifactId,
@CliOption(key = "version", mandatory = true, help = "The version of the dependency") String version) {
mavenOperations.addDependency(groupId, artifactId, version);
}
@CliCommand(value = "dependency remove", help = "Removes an existing dependency from the Maven project object model (POM)")
public void removeDependency(
@CliOption(key = "groupId", mandatory = true, help = "The group ID of the dependency") String groupId,
@CliOption(key = "artifactId", mandatory = true, help = "The artifact ID of the dependency") String artifactId,
@CliOption(key = "version", mandatory = true, help = "The version of the dependency") String version) {
mavenOperations.removeDependency(groupId, artifactId, version);
}
@CliAvailabilityIndicator({ "perform package", "perform eclipse", "perform tests", "perform clean", "perform assembly", "perform command" })
public boolean isPerformCommandAllowed() {
return mavenOperations.isPerformCommandAllowed();
}
@CliCommand(value = { "perform package" }, help = "Packages the application using Maven, but does not execute any tests")
public void runPackage() throws IOException {
mvn("-DskipTests=true package");
}
@CliCommand(value = { "perform eclipse" }, help = "Sets up Eclipse configuration via Maven (only necessary if you have not installed the m2eclipse plugin in Eclipse)")
public void runEclipse() throws IOException {
mvn("eclipse:clean eclipse:eclipse");
}
@CliCommand(value = { "perform tests" }, help = "Executes the tests via Maven")
public void runTest() throws IOException {
mvn("test");
}
@CliCommand(value = { "perform assembly" }, help = "Executes the assembly goal via Maven")
public void runAssembly() throws IOException {
mvn("assembly:assembly");
}
@CliCommand(value = { "perform clean" }, help = "Executes a full clean (including Eclipse files) via Maven")
public void runClean() throws IOException {
mvn("clean");
}
@CliCommand(value = { "perform command" }, help = "Executes a user-specified Maven command")
public void mvn(
@CliOption(key = "mavenCommand", mandatory = true, help = "User-specified Maven command (eg test:test)") String extra) throws IOException {
File root = new File(mavenOperations.getProjectRoot());
Assert.isTrue(root.isDirectory() && root.exists(), "Project root does not currently exist as a directory ('" + root.getCanonicalPath() + "')");
String cmd = (File.separatorChar == '\\' ? "mvn.bat " : "mvn ") + extra;
Process p = Runtime.getRuntime().exec(cmd, null, root);
// Ensure separate threads are used for logging, as per ROO-652
LoggingInputStream input = new LoggingInputStream(p.getInputStream(), processManager);
LoggingInputStream errors = new LoggingInputStream(p.getErrorStream(), processManager);
p.getOutputStream().close(); // Close OutputStream to avoid blocking by Maven commands that expect input, as per ROO-2034
input.start();
errors.start();
try {
p.waitFor();
+ if (p.exitValue() != 0) {
+ logger.warning("The command '" + cmd + "' failed to complete");
+ }
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
private class LoggingInputStream extends Thread {
private BufferedReader reader;
private ProcessManager processManager;
public LoggingInputStream(InputStream inputStream, ProcessManager processManager) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
this.processManager = processManager;
}
@Override
public void run() {
ActiveProcessManager.setActiveProcessManager(processManager);
String line;
try {
while ((line = reader.readLine()) != null) {
if (line.startsWith("[ERROR]")) {
logger.severe(line);
} else if (line.startsWith("[WARNING]")) {
logger.warning(line);
} else {
logger.info(line);
}
}
} catch (IOException e) {
if (e.getMessage().contains("No such file or directory") || // For *nix/Mac
e.getMessage().contains("CreateProcess error=2")) { // For Windows
logger.severe("Could not locate Maven executable; please ensure mvn command is in your path");
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
ActiveProcessManager.clearActiveProcessManager();
}
}
}
}
| true | true | public void createProject(
@CliOption(key = { "", "topLevelPackage" }, mandatory = true, optionContext = "update", help = "The uppermost package name (this becomes the <groupId> in Maven and also the '~' value when using Roo's shell)") JavaPackage topLevelPackage,
@CliOption(key = "projectName", mandatory = false, help = "The name of the project (last segment of package name used as default)") String projectName,
@CliOption(key = "java", mandatory = false, help = "Forces a particular major version of Java to be used (will be auto-detected if unspecified; specify 5 or 6 or 7 only)") Integer majorJavaVersion) {
mavenOperations.createProject(topLevelPackage, projectName, majorJavaVersion);
}
@CliAvailabilityIndicator({ "dependency add", "dependency remove" })
public boolean isDependencyModificationAllowed() {
return mavenOperations.isDependencyModificationAllowed();
}
@CliCommand(value = "dependency add", help = "Adds a new dependency to the Maven project object model (POM)")
public void addDependency(
@CliOption(key = "groupId", mandatory = true, help = "The group ID of the dependency") String groupId,
@CliOption(key = "artifactId", mandatory = true, help = "The artifact ID of the dependency") String artifactId,
@CliOption(key = "version", mandatory = true, help = "The version of the dependency") String version) {
mavenOperations.addDependency(groupId, artifactId, version);
}
@CliCommand(value = "dependency remove", help = "Removes an existing dependency from the Maven project object model (POM)")
public void removeDependency(
@CliOption(key = "groupId", mandatory = true, help = "The group ID of the dependency") String groupId,
@CliOption(key = "artifactId", mandatory = true, help = "The artifact ID of the dependency") String artifactId,
@CliOption(key = "version", mandatory = true, help = "The version of the dependency") String version) {
mavenOperations.removeDependency(groupId, artifactId, version);
}
@CliAvailabilityIndicator({ "perform package", "perform eclipse", "perform tests", "perform clean", "perform assembly", "perform command" })
public boolean isPerformCommandAllowed() {
return mavenOperations.isPerformCommandAllowed();
}
@CliCommand(value = { "perform package" }, help = "Packages the application using Maven, but does not execute any tests")
public void runPackage() throws IOException {
mvn("-DskipTests=true package");
}
@CliCommand(value = { "perform eclipse" }, help = "Sets up Eclipse configuration via Maven (only necessary if you have not installed the m2eclipse plugin in Eclipse)")
public void runEclipse() throws IOException {
mvn("eclipse:clean eclipse:eclipse");
}
@CliCommand(value = { "perform tests" }, help = "Executes the tests via Maven")
public void runTest() throws IOException {
mvn("test");
}
@CliCommand(value = { "perform assembly" }, help = "Executes the assembly goal via Maven")
public void runAssembly() throws IOException {
mvn("assembly:assembly");
}
@CliCommand(value = { "perform clean" }, help = "Executes a full clean (including Eclipse files) via Maven")
public void runClean() throws IOException {
mvn("clean");
}
@CliCommand(value = { "perform command" }, help = "Executes a user-specified Maven command")
public void mvn(
@CliOption(key = "mavenCommand", mandatory = true, help = "User-specified Maven command (eg test:test)") String extra) throws IOException {
File root = new File(mavenOperations.getProjectRoot());
Assert.isTrue(root.isDirectory() && root.exists(), "Project root does not currently exist as a directory ('" + root.getCanonicalPath() + "')");
String cmd = (File.separatorChar == '\\' ? "mvn.bat " : "mvn ") + extra;
Process p = Runtime.getRuntime().exec(cmd, null, root);
// Ensure separate threads are used for logging, as per ROO-652
LoggingInputStream input = new LoggingInputStream(p.getInputStream(), processManager);
LoggingInputStream errors = new LoggingInputStream(p.getErrorStream(), processManager);
p.getOutputStream().close(); // Close OutputStream to avoid blocking by Maven commands that expect input, as per ROO-2034
input.start();
errors.start();
try {
p.waitFor();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
private class LoggingInputStream extends Thread {
private BufferedReader reader;
private ProcessManager processManager;
public LoggingInputStream(InputStream inputStream, ProcessManager processManager) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
this.processManager = processManager;
}
@Override
public void run() {
ActiveProcessManager.setActiveProcessManager(processManager);
String line;
try {
while ((line = reader.readLine()) != null) {
if (line.startsWith("[ERROR]")) {
logger.severe(line);
} else if (line.startsWith("[WARNING]")) {
logger.warning(line);
} else {
logger.info(line);
}
}
} catch (IOException e) {
if (e.getMessage().contains("No such file or directory") || // For *nix/Mac
e.getMessage().contains("CreateProcess error=2")) { // For Windows
logger.severe("Could not locate Maven executable; please ensure mvn command is in your path");
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
ActiveProcessManager.clearActiveProcessManager();
}
}
}
}
| public void createProject(
@CliOption(key = { "", "topLevelPackage" }, mandatory = true, optionContext = "update", help = "The uppermost package name (this becomes the <groupId> in Maven and also the '~' value when using Roo's shell)") JavaPackage topLevelPackage,
@CliOption(key = "projectName", mandatory = false, help = "The name of the project (last segment of package name used as default)") String projectName,
@CliOption(key = "java", mandatory = false, help = "Forces a particular major version of Java to be used (will be auto-detected if unspecified; specify 5 or 6 or 7 only)") Integer majorJavaVersion) {
mavenOperations.createProject(topLevelPackage, projectName, majorJavaVersion);
}
@CliAvailabilityIndicator({ "dependency add", "dependency remove" })
public boolean isDependencyModificationAllowed() {
return mavenOperations.isDependencyModificationAllowed();
}
@CliCommand(value = "dependency add", help = "Adds a new dependency to the Maven project object model (POM)")
public void addDependency(
@CliOption(key = "groupId", mandatory = true, help = "The group ID of the dependency") String groupId,
@CliOption(key = "artifactId", mandatory = true, help = "The artifact ID of the dependency") String artifactId,
@CliOption(key = "version", mandatory = true, help = "The version of the dependency") String version) {
mavenOperations.addDependency(groupId, artifactId, version);
}
@CliCommand(value = "dependency remove", help = "Removes an existing dependency from the Maven project object model (POM)")
public void removeDependency(
@CliOption(key = "groupId", mandatory = true, help = "The group ID of the dependency") String groupId,
@CliOption(key = "artifactId", mandatory = true, help = "The artifact ID of the dependency") String artifactId,
@CliOption(key = "version", mandatory = true, help = "The version of the dependency") String version) {
mavenOperations.removeDependency(groupId, artifactId, version);
}
@CliAvailabilityIndicator({ "perform package", "perform eclipse", "perform tests", "perform clean", "perform assembly", "perform command" })
public boolean isPerformCommandAllowed() {
return mavenOperations.isPerformCommandAllowed();
}
@CliCommand(value = { "perform package" }, help = "Packages the application using Maven, but does not execute any tests")
public void runPackage() throws IOException {
mvn("-DskipTests=true package");
}
@CliCommand(value = { "perform eclipse" }, help = "Sets up Eclipse configuration via Maven (only necessary if you have not installed the m2eclipse plugin in Eclipse)")
public void runEclipse() throws IOException {
mvn("eclipse:clean eclipse:eclipse");
}
@CliCommand(value = { "perform tests" }, help = "Executes the tests via Maven")
public void runTest() throws IOException {
mvn("test");
}
@CliCommand(value = { "perform assembly" }, help = "Executes the assembly goal via Maven")
public void runAssembly() throws IOException {
mvn("assembly:assembly");
}
@CliCommand(value = { "perform clean" }, help = "Executes a full clean (including Eclipse files) via Maven")
public void runClean() throws IOException {
mvn("clean");
}
@CliCommand(value = { "perform command" }, help = "Executes a user-specified Maven command")
public void mvn(
@CliOption(key = "mavenCommand", mandatory = true, help = "User-specified Maven command (eg test:test)") String extra) throws IOException {
File root = new File(mavenOperations.getProjectRoot());
Assert.isTrue(root.isDirectory() && root.exists(), "Project root does not currently exist as a directory ('" + root.getCanonicalPath() + "')");
String cmd = (File.separatorChar == '\\' ? "mvn.bat " : "mvn ") + extra;
Process p = Runtime.getRuntime().exec(cmd, null, root);
// Ensure separate threads are used for logging, as per ROO-652
LoggingInputStream input = new LoggingInputStream(p.getInputStream(), processManager);
LoggingInputStream errors = new LoggingInputStream(p.getErrorStream(), processManager);
p.getOutputStream().close(); // Close OutputStream to avoid blocking by Maven commands that expect input, as per ROO-2034
input.start();
errors.start();
try {
p.waitFor();
if (p.exitValue() != 0) {
logger.warning("The command '" + cmd + "' failed to complete");
}
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
private class LoggingInputStream extends Thread {
private BufferedReader reader;
private ProcessManager processManager;
public LoggingInputStream(InputStream inputStream, ProcessManager processManager) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
this.processManager = processManager;
}
@Override
public void run() {
ActiveProcessManager.setActiveProcessManager(processManager);
String line;
try {
while ((line = reader.readLine()) != null) {
if (line.startsWith("[ERROR]")) {
logger.severe(line);
} else if (line.startsWith("[WARNING]")) {
logger.warning(line);
} else {
logger.info(line);
}
}
} catch (IOException e) {
if (e.getMessage().contains("No such file or directory") || // For *nix/Mac
e.getMessage().contains("CreateProcess error=2")) { // For Windows
logger.severe("Could not locate Maven executable; please ensure mvn command is in your path");
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
ActiveProcessManager.clearActiveProcessManager();
}
}
}
}
|
diff --git a/esupecm-orioai/src/main/java/org/orioai/esupecm/workflow/service/OriOaiWorkflowServiceImpl.java b/esupecm-orioai/src/main/java/org/orioai/esupecm/workflow/service/OriOaiWorkflowServiceImpl.java
index 15164f8..6198350 100644
--- a/esupecm-orioai/src/main/java/org/orioai/esupecm/workflow/service/OriOaiWorkflowServiceImpl.java
+++ b/esupecm-orioai/src/main/java/org/orioai/esupecm/workflow/service/OriOaiWorkflowServiceImpl.java
@@ -1,381 +1,381 @@
package org.orioai.esupecm.workflow.service;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.runtime.model.ComponentInstance;
import org.nuxeo.runtime.model.DefaultComponent;
import org.orioai.esupecm.OriOaiMetadataType;
import org.orioai.esupecm.workflow.WsDescriptor;
import org.orioai.ws.workflow.IOriWorkflowService;
import org.orioai.ws.workflow.InstanceInfos;
public class OriOaiWorkflowServiceImpl extends DefaultComponent implements OriOaiWorkflowService {
private static final Log log = LogFactory.getLog(OriOaiWorkflowServiceImpl.class);
protected WsDescriptor config;
protected HashMap<String, IOriWorkflowService> _oriWorkflowServices;
public void registerContribution(Object contribution,
String extensionPoint, ComponentInstance contributor) {
config = (WsDescriptor) contribution;
}
public void unregisterContribution(Object contribution,
String extensionPoint, ComponentInstance contributor) {
if (config==contribution)
config = null;
}
/**
* Get the ori-oai-workflow service
* @return
*/
private IOriWorkflowService getRemoteOriWorkflowService(String username) {
if (_oriWorkflowServices == null) {
_oriWorkflowServices = new HashMap<String, IOriWorkflowService>();
}
IOriWorkflowService oriWorkflowService = _oriWorkflowServices.get(username);
if( oriWorkflowService == null ) {
String wsUrl = config.getWsUrl();
log.info("getRemoteOriWorkflowService :: contacting Web Service from URL : " + wsUrl);
try {
- QName service_name = new QName("http://remote.services.workflow.orioai.org", "OriWorkflowServiceService");
+ QName service_name = new QName("http://remote.services.workflow.orioai.org/", "OriWorkflowServiceService");
Service service = Service.create(new URL(wsUrl + "?wsdl"), service_name);
oriWorkflowService = service.getPort(IOriWorkflowService.class);
_oriWorkflowServices.put(username, oriWorkflowService);
}
catch (MalformedURLException e) {
throw new RuntimeException("pb retireving ori-oai-workflow Web Service", e);
}
}
return oriWorkflowService;
}
public List<OriOaiMetadataType> getMetadataTypes(String username) {
if (log.isDebugEnabled())
log.debug("getMetadataTypes :: going to get metadataTypes for "+username);
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
Map<String,String> metadataTypes = oriWorkflowService.getMetadataTypes(username);
if (log.isDebugEnabled())
log.debug("getMetadataTypes :: get metadataTypes for "+username+" from Web Service ok : " + metadataTypes.toString());
List<OriOaiMetadataType> oriOaiMetadataTypes = new ArrayList<OriOaiMetadataType>();
Iterator<String> metadataTypeIds = metadataTypes.keySet().iterator();
while (metadataTypeIds.hasNext()) {
String metadataTypeId = metadataTypeIds.next();
String metadataTypeLabel = metadataTypes.get(metadataTypeId);
OriOaiMetadataType metadataType = new OriOaiMetadataType(metadataTypeId, metadataTypeLabel);
oriOaiMetadataTypes.add(metadataType);
}
return oriOaiMetadataTypes;
}
public Long newWorkflowInstance(String username, String metadataTypeId) {
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
log.debug("newWorkflowInstance :: call newWorkflowInstance from Web Service ...");
Long id = oriWorkflowService.newWorkflowInstance(null, metadataTypeId, username);
return id;
}
/**
* @deprecated
* use Vector<String> getCurrentStates(Map<String, String> statesMap) instead
*/
public Map<String, String> getCurrentStates(String username, String idp, String language) {
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
Map<String, String> currentStates = oriWorkflowService.getCurrentStates(idp, language);
if (log.isDebugEnabled())
log.debug("getCurrentStates :: currentStates=" + currentStates);
return currentStates;
}
public Vector<String> getCurrentStates(Map<String, String> statesMap) {
Vector<String> currentStates = new Vector<String>();
for (String key : statesMap.keySet())
currentStates.add(statesMap.get(key));
return currentStates;
}
/**
* @deprecated
* use List<String> getCurrentInformations(Map<String, String> currentInformations) instead
*/
public List<String> getCurrentInformations(String username, String idp, String language) {
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
if (log.isDebugEnabled()) {
log.debug("getCurrentInformations :: idp=" + idp);
log.debug("getCurrentInformations :: language=" + language);
}
Map<String, String> currentInformations = oriWorkflowService.getErrors(idp, language);
if (log.isDebugEnabled())
log.debug("getCurrentInformations :: currentInformations=" + currentInformations);
List<String> informations = new ArrayList<String>();
for (Map.Entry<String, String> entry : currentInformations.entrySet()) {
if (entry.getKey() != null) {
informations.add(entry.getValue());
}
}
return informations;
}
public List<String> getCurrentInformations(Map<String, String> currentInformations) {
if (log.isDebugEnabled())
log.debug("getCurrentInformations :: currentInformations=" + currentInformations);
List<String> informations = new ArrayList<String>();
for (Map.Entry<String, String> entry : currentInformations.entrySet()) {
if (entry.getKey() != null) {
informations.add(entry.getValue());
}
}
return informations;
}
/**
* Return metadata type for a given idp (remote access to workflow)
* @param idp
* @return metadata type or null if failed
*/
public OriOaiMetadataType getMetadataType(String username, String idp) {
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
try {
String metadataTypeId = oriWorkflowService.getMetadataType(idp);
return new OriOaiMetadataType(metadataTypeId, oriWorkflowService.getMetadataTypes().get(metadataTypeId));
}
catch (Exception e) {
log.error("getMetadataType :: can't retrieve metadata type from idp "+ idp, e);
return null;
}
}
public String getMetadataSchemaNamespace(String username, String metadataTypeId) {
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
try {
String metadataSchemaNamespace = oriWorkflowService.getMetadataSchemaNamespace(metadataTypeId);
//String metadataSchemaNamespace = "http://www.abes.fr/abes/documents/tef";
return metadataSchemaNamespace;
}
catch (Exception e) {
log.error("getMetadataSchemaNamespace :: can't retrieve metadata namespace from metadataTypeId "+ metadataTypeId, e);
return null;
}
}
public String getIdp(String username, Long id) {
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
return oriWorkflowService.getIdp(id, username);
}
private String getReplacedMdEditorUrl(String mdEditorUrl) {
if (log.isDebugEnabled()) {
log.debug("getReplacedMdEditorUrl :: mdEditorUrl=" + mdEditorUrl);
log.debug("getReplacedMdEditorUrl :: config.getMdEditorFromUrl()=" + config.getMdEditorFromUrl());
log.debug("getReplacedMdEditorUrl :: config.getMdEditorToUrl()=" + config.getMdEditorToUrl());
log.debug("getReplacedMdEditorUrl :: config.isMdEditorTranslationSet()=" + config.isMdEditorTranslationSet());
}
String result = mdEditorUrl;
if (config.isMdEditorTranslationSet()) {
result = mdEditorUrl.replaceFirst(config.getMdEditorFromUrl(), config.getMdEditorToUrl());
}
return result;
}
/**
* Returns md editor url for the first form available for user
* @param idp
* @param userId
* @return
*/
public String getMdeditorUrl(String username, String idp) {
return getMdeditorUrlWS(username, idp);
}
/**
*
* @param idp
* @param userId
* @return
*/
public String getMdeditorUrlWS(String username, String idp) {
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
Map<String,String> formsMap = oriWorkflowService.getMdEditorUrl(idp);
if (log.isDebugEnabled())
log.debug("getMdeditorUrlWS :: formsMap.get(0)=" + formsMap.get(0));
String result = getReplacedMdEditorUrl(formsMap.get(0));
if (log.isDebugEnabled())
log.debug("getMdeditorUrlWS :: result=" + result);
return result;
}
/**
* Return a map for availables md editors
* @param idp
* @param userId
* @return map formTitle:formUrl
*/
public Map<String,String> getMdeditorUrls(String username, String idp) {
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
Map<String,String> formsMap = oriWorkflowService.getMdEditorUrl(idp);
if (log.isDebugEnabled())
log.debug("getMdeditorUrlWS :: before formsMap=" + formsMap);
for (String key : formsMap.keySet()) {
String value = getReplacedMdEditorUrl(formsMap.get(key));
if (log.isDebugEnabled())
log.debug("getMdeditorUrlWS :: put(" + key + ", "+value+")");
formsMap.put(key, value);
}
if (log.isDebugEnabled())
log.debug("getMdeditorUrlWS :: after formsMap=" + formsMap);
return formsMap;
}
/**
* Returns availables actions for given user and idp
* @param idp
* @param userId
* @return
*/
public Map<String,String> getAvailableActions(String username, String idp, String language) {
if (log.isDebugEnabled()) {
log.debug("getAvailableActions :: idp=" + idp);
log.debug("getAvailableActions :: language=" + language);
}
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
Map<String,String> actionsMap = oriWorkflowService.getAvailableActions(idp, language);
if (log.isDebugEnabled())
log.debug("getAvailableActions :: actionsMap=" + actionsMap);
return actionsMap;
}
/**
* Perform an available action
* @param idp
* @param actionId
* @param observation
* @return true if action was performed
*/
public boolean performAction(String username, String idp, int actionId, String observation) {
log.info("performAction :: idp=" + idp+", actionId="+actionId+", observation="+observation);
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
return oriWorkflowService.performAction(idp, actionId, observation);
}
public String getXMLForms(String username, String idp) {
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
String xml = oriWorkflowService.getXMLForms(idp);
if (log.isDebugEnabled())
log.debug("getXMLForms :: xml=" + xml);
return xml;
}
public void saveXML(String username, String idp, String xmlContent) {
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(username);
oriWorkflowService.saveXML(idp, xmlContent);
}
public InstanceInfos getInstanceInfos(Long id, String userId, String language) {
IOriWorkflowService oriWorkflowService = getRemoteOriWorkflowService(userId);
return oriWorkflowService.getInstanceInfos(id, userId, language);
}
}
| true | true | private IOriWorkflowService getRemoteOriWorkflowService(String username) {
if (_oriWorkflowServices == null) {
_oriWorkflowServices = new HashMap<String, IOriWorkflowService>();
}
IOriWorkflowService oriWorkflowService = _oriWorkflowServices.get(username);
if( oriWorkflowService == null ) {
String wsUrl = config.getWsUrl();
log.info("getRemoteOriWorkflowService :: contacting Web Service from URL : " + wsUrl);
try {
QName service_name = new QName("http://remote.services.workflow.orioai.org", "OriWorkflowServiceService");
Service service = Service.create(new URL(wsUrl + "?wsdl"), service_name);
oriWorkflowService = service.getPort(IOriWorkflowService.class);
_oriWorkflowServices.put(username, oriWorkflowService);
}
catch (MalformedURLException e) {
throw new RuntimeException("pb retireving ori-oai-workflow Web Service", e);
}
}
return oriWorkflowService;
}
| private IOriWorkflowService getRemoteOriWorkflowService(String username) {
if (_oriWorkflowServices == null) {
_oriWorkflowServices = new HashMap<String, IOriWorkflowService>();
}
IOriWorkflowService oriWorkflowService = _oriWorkflowServices.get(username);
if( oriWorkflowService == null ) {
String wsUrl = config.getWsUrl();
log.info("getRemoteOriWorkflowService :: contacting Web Service from URL : " + wsUrl);
try {
QName service_name = new QName("http://remote.services.workflow.orioai.org/", "OriWorkflowServiceService");
Service service = Service.create(new URL(wsUrl + "?wsdl"), service_name);
oriWorkflowService = service.getPort(IOriWorkflowService.class);
_oriWorkflowServices.put(username, oriWorkflowService);
}
catch (MalformedURLException e) {
throw new RuntimeException("pb retireving ori-oai-workflow Web Service", e);
}
}
return oriWorkflowService;
}
|
diff --git a/com.ibm.wala.core/src/com/ibm/wala/analysis/pointers/BasicHeapGraph.java b/com.ibm.wala.core/src/com/ibm/wala/analysis/pointers/BasicHeapGraph.java
index bcb915c9d..e528fd13c 100644
--- a/com.ibm.wala.core/src/com/ibm/wala/analysis/pointers/BasicHeapGraph.java
+++ b/com.ibm.wala.core/src/com/ibm/wala/analysis/pointers/BasicHeapGraph.java
@@ -1,518 +1,518 @@
/*******************************************************************************
* Copyright (c) 2002 - 2006 IBM Corporation.
* 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 com.ibm.wala.analysis.pointers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import com.ibm.wala.analysis.reflection.Malleable;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CompoundIterator;
import com.ibm.wala.util.IntFunction;
import com.ibm.wala.util.IntMapIterator;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.graph.AbstractNumberedGraph;
import com.ibm.wala.util.graph.EdgeManager;
import com.ibm.wala.util.graph.NodeManager;
import com.ibm.wala.util.graph.NumberedGraph;
import com.ibm.wala.util.graph.NumberedNodeManager;
import com.ibm.wala.util.graph.impl.NumberedNodeIterator;
import com.ibm.wala.util.intset.BasicNaturalRelation;
import com.ibm.wala.util.intset.IBinaryNaturalRelation;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableMapping;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import com.ibm.wala.util.intset.OrdinalSet;
import com.ibm.wala.util.intset.OrdinalSetMapping;
import com.ibm.wala.util.intset.SparseIntSet;
/**
* @author sfink
*/
public class BasicHeapGraph extends HeapGraph {
private final static boolean VERBOSE = false;
private final static int VERBOSE_INTERVAL = 10000;
/**
* Pointer analysis solution
*/
private final PointerAnalysis pointerAnalysis;
/**
* The backing graph
*/
private final NumberedGraph<Object> G;
/**
* governing call graph
*/
private final CallGraph callGraph;
/**
* @param P
* governing pointer analysis
* @throws NullPointerException
* if P is null
*/
public BasicHeapGraph(final PointerAnalysis P, final CallGraph callGraph) throws NullPointerException {
super(P.getHeapModel());
this.pointerAnalysis = P;
this.callGraph = callGraph;
final OrdinalSetMapping<PointerKey> pointerKeys = getPointerKeys();
final NumberedNodeManager<Object> nodeMgr = new NumberedNodeManager<Object>() {
public Iterator<Object> iterator() {
return new CompoundIterator<Object>(pointerKeys.iterator(), P.getInstanceKeyMapping().iterator());
}
public int getNumberOfNodes() {
return pointerKeys.getSize() + P.getInstanceKeyMapping().getSize();
}
public void addNode(Object n) {
Assertions.UNREACHABLE();
}
public void removeNode(Object n) {
Assertions.UNREACHABLE();
}
public int getNumber(Object N) {
if (N instanceof PointerKey) {
return pointerKeys.getMappedIndex((PointerKey) N);
} else {
if (Assertions.verifyAssertions) {
if (!(N instanceof InstanceKey)) {
Assertions.UNREACHABLE(N.getClass().toString());
}
}
int inumber = P.getInstanceKeyMapping().getMappedIndex((InstanceKey) N);
return (inumber == -1) ? -1 : inumber + pointerKeys.getMaximumIndex();
}
}
public Object getNode(int number) {
- if (number >= pointerKeys.getMaximumIndex()) {
- return P.getInstanceKeyMapping().getMappedObject(number - pointerKeys.getMaximumIndex());
+ if (number > pointerKeys.getMaximumIndex()) {
+ return P.getInstanceKeyMapping().getMappedObject(number - pointerKeys.getSize());
} else {
return pointerKeys.getMappedObject(number);
}
}
public int getMaxNumber() {
return getNumberOfNodes() - 1;
}
public boolean containsNode(Object n) {
return getNumber(n) != -1;
}
public Iterator<Object> iterateNodes(IntSet s) {
return new NumberedNodeIterator<Object>(s, this);
}
};
final IBinaryNaturalRelation pred = computePredecessors(nodeMgr);
final IntFunction<Object> toNode = new IntFunction<Object>() {
public Object apply(int i) {
return nodeMgr.getNode(i);
}
};
this.G = new AbstractNumberedGraph<Object>() {
private final EdgeManager<Object> edgeMgr = new EdgeManager<Object>() {
public Iterator<Object> getPredNodes(Object N) {
int n = nodeMgr.getNumber(N);
IntSet p = pred.getRelated(n);
if (p == null) {
return EmptyIterator.instance();
} else {
return new IntMapIterator<Object>(p.intIterator(), toNode);
}
}
public int getPredNodeCount(Object N) {
int n = nodeMgr.getNumber(N);
return pred.getRelatedCount(n);
}
public Iterator<? extends Object> getSuccNodes(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
if (succ == null) {
return EmptyIterator.instance();
}
SparseIntSet s = new MutableSparseIntSet(succ);
return new IntMapIterator<Object>(s.intIterator(), toNode);
}
public int getSuccNodeCount(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
return succ == null ? 0 : succ.length;
}
public void addEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
public void removeEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
public void removeAllIncidentEdges(Object node) {
Assertions.UNREACHABLE();
}
public void removeIncomingEdges(Object node) {
Assertions.UNREACHABLE();
}
public void removeOutgoingEdges(Object node) {
Assertions.UNREACHABLE();
}
public boolean hasEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
return false;
}
};
@Override
protected NodeManager<Object> getNodeManager() {
return nodeMgr;
}
@Override
protected EdgeManager<Object> getEdgeManager() {
return edgeMgr;
}
};
}
private OrdinalSetMapping<PointerKey> getPointerKeys() {
MutableMapping<PointerKey> result = new MutableMapping<PointerKey>();
for (Iterator<PointerKey> it = pointerAnalysis.getPointerKeys().iterator(); it.hasNext();) {
PointerKey p = it.next();
result.add(p);
}
return result;
}
private int[] computeSuccNodeNumbers(Object N, NumberedNodeManager<Object> nodeManager) {
if (N instanceof PointerKey) {
PointerKey P = (PointerKey) N;
OrdinalSet<InstanceKey> S = pointerAnalysis.getPointsToSet(P);
int[] result = new int[S.size()];
int i = 0;
for (Iterator<InstanceKey> it = S.iterator(); it.hasNext();) {
result[i] = nodeManager.getNumber(it.next());
i++;
}
return result;
} else if (N instanceof InstanceKey) {
InstanceKey I = (InstanceKey) N;
TypeReference T = I.getConcreteType().getReference();
if (Assertions.verifyAssertions) {
if (T == null) {
Assertions._assert(T != null, "null concrete type from " + I.getClass());
}
}
if (T.isArrayType()) {
PointerKey p = getHeapModel().getPointerKeyForArrayContents(I);
if (p == null || !nodeManager.containsNode(p)) {
return null;
} else {
return new int[] { nodeManager.getNumber(p) };
}
} else if (!Malleable.isMalleable(T)) {
IClass klass = getHeapModel().getClassHierarchy().lookupClass(T);
if (Assertions.verifyAssertions) {
if (klass == null) {
Assertions._assert(klass != null, "null klass for type " + T);
}
}
MutableSparseIntSet result = new MutableSparseIntSet();
try {
for (Iterator<IField> it = klass.getAllInstanceFields().iterator(); it.hasNext();) {
IField f = it.next();
if (!f.getReference().getFieldType().isPrimitiveType()) {
PointerKey p = getHeapModel().getPointerKeyForInstanceField(I, f);
if (p != null && nodeManager.containsNode(p)) {
result.add(nodeManager.getNumber(p));
}
}
}
} catch (ClassHierarchyException e) {
// uh oh. skip it for now.
}
return result.toIntArray();
} else {
Assertions._assert(Malleable.isMalleable(T));
return null;
}
} else {
Assertions.UNREACHABLE("Unexpected type: " + N.getClass());
return null;
}
}
/**
* @return R, y \in R(x,y) if the node y is a predecessor of node x
*/
private IBinaryNaturalRelation computePredecessors(NumberedNodeManager<Object> nodeManager) {
BasicNaturalRelation R = new BasicNaturalRelation(new byte[] { BasicNaturalRelation.SIMPLE }, BasicNaturalRelation.SIMPLE);
// we split the following loops to improve temporal locality,
// particularly for locals
computePredecessorsForNonLocals(nodeManager, R);
computePredecessorsForLocals(nodeManager, R);
return R;
}
private void computePredecessorsForNonLocals(NumberedNodeManager<Object> nodeManager, BasicNaturalRelation R) {
// Note: we run this loop backwards on purpose, to avoid lots of resizing of
// bitvectors
// in the backing relation. i.e., we will add the biggest bits first.
// pretty damn tricky.
for (int i = nodeManager.getMaxNumber(); i >= 0; i--) {
if (VERBOSE) {
if (i % VERBOSE_INTERVAL == 0) {
System.err.println("Building HeapGraph: " + i);
}
}
Object n = nodeManager.getNode(i);
if (!(n instanceof LocalPointerKey)) {
int[] succ = computeSuccNodeNumbers(n, nodeManager);
if (succ != null) {
for (int z = 0; z < succ.length; z++) {
int j = succ[z];
R.add(j, i);
}
}
}
}
}
/**
* traverse locals in order, first by node, then by value number: attempt to
* improve locality
*/
private void computePredecessorsForLocals(NumberedNodeManager<Object> nodeManager, BasicNaturalRelation R) {
ArrayList<LocalPointerKey> list = new ArrayList<LocalPointerKey>();
for (Iterator<Object> it = nodeManager.iterator(); it.hasNext();) {
Object n = it.next();
if (n instanceof LocalPointerKey) {
list.add((LocalPointerKey) n);
}
}
Object[] arr = list.toArray();
Arrays.sort(arr, new LocalPointerComparator());
for (int i = 0; i < arr.length; i++) {
if (VERBOSE) {
if (i % VERBOSE_INTERVAL == 0) {
System.err.println("Building HeapGraph: " + i + " of " + arr.length);
}
}
LocalPointerKey n = (LocalPointerKey) arr[i];
int num = nodeManager.getNumber(n);
int[] succ = computeSuccNodeNumbers(n, nodeManager);
if (succ != null) {
for (int z = 0; z < succ.length; z++) {
int j = succ[z];
R.add(j, num);
}
}
}
}
/**
* sorts local pointers by node, then value number
*/
private final class LocalPointerComparator implements Comparator<Object> {
public int compare(Object arg1, Object arg2) {
LocalPointerKey o1 = (LocalPointerKey) arg1;
LocalPointerKey o2 = (LocalPointerKey) arg2;
if (o1.getNode().equals(o2.getNode())) {
return o1.getValueNumber() - o2.getValueNumber();
} else {
return callGraph.getNumber(o1.getNode()) - callGraph.getNumber(o2.getNode());
}
}
}
/*
* @see com.ibm.wala.util.graph.NumberedNodeManager#getNumber(com.ibm.wala.util.graph.Node)
*/
public int getNumber(Object N) {
return G.getNumber(N);
}
/*
* @see com.ibm.wala.util.graph.NumberedNodeManager#getNode(int)
*/
public Object getNode(int number) {
return G.getNode(number);
}
/*
* @see com.ibm.wala.util.graph.NumberedNodeManager#getMaxNumber()
*/
public int getMaxNumber() {
return G.getMaxNumber();
}
/*
* @see com.ibm.wala.util.graph.NodeManager#iterateNodes()
*/
public Iterator<Object> iterator() {
return G.iterator();
}
/*
* @see com.ibm.wala.util.graph.NodeManager#getNumberOfNodes()
*/
public int getNumberOfNodes() {
return G.getNumberOfNodes();
}
/*
* @see com.ibm.wala.util.graph.EdgeManager#getPredNodes(com.ibm.wala.util.graph.Node)
*/
public Iterator<? extends Object> getPredNodes(Object N) {
return G.getPredNodes(N);
}
/*
* @see com.ibm.wala.util.graph.EdgeManager#getPredNodeCount(com.ibm.wala.util.graph.Node)
*/
public int getPredNodeCount(Object N) {
return G.getPredNodeCount(N);
}
/*
* @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(com.ibm.wala.util.graph.Node)
*/
public Iterator<? extends Object> getSuccNodes(Object N) {
return G.getSuccNodes(N);
}
/*
* @see com.ibm.wala.util.graph.EdgeManager#getSuccNodeCount(com.ibm.wala.util.graph.Node)
*/
public int getSuccNodeCount(Object N) {
return G.getSuccNodeCount(N);
}
/*
* @see com.ibm.wala.util.graph.NodeManager#addNode(com.ibm.wala.util.graph.Node)
*/
public void addNode(Object n) {
Assertions.UNREACHABLE();
}
/*
* @see com.ibm.wala.util.graph.NodeManager#remove(com.ibm.wala.util.graph.Node)
*/
public void removeNode(Object n) {
Assertions.UNREACHABLE();
}
public void addEdge(Object from, Object to) {
Assertions.UNREACHABLE();
}
public void removeEdge(Object from, Object to) {
Assertions.UNREACHABLE();
}
public boolean hasEdge(Object from, Object to) {
Assertions.UNREACHABLE();
return false;
}
public void removeAllIncidentEdges(Object node) {
Assertions.UNREACHABLE();
}
/*
* @see com.ibm.wala.util.graph.NodeManager#containsNode(com.ibm.wala.util.graph.Node)
*/
public boolean containsNode(Object N) {
return G.containsNode(N);
}
@Override
public String toString() {
StringBuffer result = new StringBuffer();
result.append("Nodes:\n");
for (int i = 0; i <= getMaxNumber(); i++) {
Object node = getNode(i);
if (node != null) {
result.append(i).append(" ").append(node).append("\n");
}
}
result.append("Edges:\n");
for (int i = 0; i <= getMaxNumber(); i++) {
Object node = getNode(i);
if (node != null) {
result.append(i).append(" -> ");
for (Iterator it = getSuccNodes(node); it.hasNext();) {
Object s = it.next();
result.append(getNumber(s)).append(" ");
}
result.append("\n");
}
}
return result.toString();
}
public void removeIncomingEdges(Object node) {
// TODO Auto-generated method stub
Assertions.UNREACHABLE();
}
public void removeOutgoingEdges(Object node) {
// TODO Auto-generated method stub
Assertions.UNREACHABLE();
}
public IntSet getSuccNodeNumbers(Object node) {
// TODO Auto-generated method stub
Assertions.UNREACHABLE();
return null;
}
public IntSet getPredNodeNumbers(Object node) {
// TODO Auto-generated method stub
Assertions.UNREACHABLE();
return null;
}
}
| true | true | public BasicHeapGraph(final PointerAnalysis P, final CallGraph callGraph) throws NullPointerException {
super(P.getHeapModel());
this.pointerAnalysis = P;
this.callGraph = callGraph;
final OrdinalSetMapping<PointerKey> pointerKeys = getPointerKeys();
final NumberedNodeManager<Object> nodeMgr = new NumberedNodeManager<Object>() {
public Iterator<Object> iterator() {
return new CompoundIterator<Object>(pointerKeys.iterator(), P.getInstanceKeyMapping().iterator());
}
public int getNumberOfNodes() {
return pointerKeys.getSize() + P.getInstanceKeyMapping().getSize();
}
public void addNode(Object n) {
Assertions.UNREACHABLE();
}
public void removeNode(Object n) {
Assertions.UNREACHABLE();
}
public int getNumber(Object N) {
if (N instanceof PointerKey) {
return pointerKeys.getMappedIndex((PointerKey) N);
} else {
if (Assertions.verifyAssertions) {
if (!(N instanceof InstanceKey)) {
Assertions.UNREACHABLE(N.getClass().toString());
}
}
int inumber = P.getInstanceKeyMapping().getMappedIndex((InstanceKey) N);
return (inumber == -1) ? -1 : inumber + pointerKeys.getMaximumIndex();
}
}
public Object getNode(int number) {
if (number >= pointerKeys.getMaximumIndex()) {
return P.getInstanceKeyMapping().getMappedObject(number - pointerKeys.getMaximumIndex());
} else {
return pointerKeys.getMappedObject(number);
}
}
public int getMaxNumber() {
return getNumberOfNodes() - 1;
}
public boolean containsNode(Object n) {
return getNumber(n) != -1;
}
public Iterator<Object> iterateNodes(IntSet s) {
return new NumberedNodeIterator<Object>(s, this);
}
};
final IBinaryNaturalRelation pred = computePredecessors(nodeMgr);
final IntFunction<Object> toNode = new IntFunction<Object>() {
public Object apply(int i) {
return nodeMgr.getNode(i);
}
};
this.G = new AbstractNumberedGraph<Object>() {
private final EdgeManager<Object> edgeMgr = new EdgeManager<Object>() {
public Iterator<Object> getPredNodes(Object N) {
int n = nodeMgr.getNumber(N);
IntSet p = pred.getRelated(n);
if (p == null) {
return EmptyIterator.instance();
} else {
return new IntMapIterator<Object>(p.intIterator(), toNode);
}
}
public int getPredNodeCount(Object N) {
int n = nodeMgr.getNumber(N);
return pred.getRelatedCount(n);
}
public Iterator<? extends Object> getSuccNodes(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
if (succ == null) {
return EmptyIterator.instance();
}
SparseIntSet s = new MutableSparseIntSet(succ);
return new IntMapIterator<Object>(s.intIterator(), toNode);
}
public int getSuccNodeCount(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
return succ == null ? 0 : succ.length;
}
public void addEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
public void removeEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
public void removeAllIncidentEdges(Object node) {
Assertions.UNREACHABLE();
}
public void removeIncomingEdges(Object node) {
Assertions.UNREACHABLE();
}
public void removeOutgoingEdges(Object node) {
Assertions.UNREACHABLE();
}
public boolean hasEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
return false;
}
};
@Override
protected NodeManager<Object> getNodeManager() {
return nodeMgr;
}
@Override
protected EdgeManager<Object> getEdgeManager() {
return edgeMgr;
}
};
}
| public BasicHeapGraph(final PointerAnalysis P, final CallGraph callGraph) throws NullPointerException {
super(P.getHeapModel());
this.pointerAnalysis = P;
this.callGraph = callGraph;
final OrdinalSetMapping<PointerKey> pointerKeys = getPointerKeys();
final NumberedNodeManager<Object> nodeMgr = new NumberedNodeManager<Object>() {
public Iterator<Object> iterator() {
return new CompoundIterator<Object>(pointerKeys.iterator(), P.getInstanceKeyMapping().iterator());
}
public int getNumberOfNodes() {
return pointerKeys.getSize() + P.getInstanceKeyMapping().getSize();
}
public void addNode(Object n) {
Assertions.UNREACHABLE();
}
public void removeNode(Object n) {
Assertions.UNREACHABLE();
}
public int getNumber(Object N) {
if (N instanceof PointerKey) {
return pointerKeys.getMappedIndex((PointerKey) N);
} else {
if (Assertions.verifyAssertions) {
if (!(N instanceof InstanceKey)) {
Assertions.UNREACHABLE(N.getClass().toString());
}
}
int inumber = P.getInstanceKeyMapping().getMappedIndex((InstanceKey) N);
return (inumber == -1) ? -1 : inumber + pointerKeys.getMaximumIndex();
}
}
public Object getNode(int number) {
if (number > pointerKeys.getMaximumIndex()) {
return P.getInstanceKeyMapping().getMappedObject(number - pointerKeys.getSize());
} else {
return pointerKeys.getMappedObject(number);
}
}
public int getMaxNumber() {
return getNumberOfNodes() - 1;
}
public boolean containsNode(Object n) {
return getNumber(n) != -1;
}
public Iterator<Object> iterateNodes(IntSet s) {
return new NumberedNodeIterator<Object>(s, this);
}
};
final IBinaryNaturalRelation pred = computePredecessors(nodeMgr);
final IntFunction<Object> toNode = new IntFunction<Object>() {
public Object apply(int i) {
return nodeMgr.getNode(i);
}
};
this.G = new AbstractNumberedGraph<Object>() {
private final EdgeManager<Object> edgeMgr = new EdgeManager<Object>() {
public Iterator<Object> getPredNodes(Object N) {
int n = nodeMgr.getNumber(N);
IntSet p = pred.getRelated(n);
if (p == null) {
return EmptyIterator.instance();
} else {
return new IntMapIterator<Object>(p.intIterator(), toNode);
}
}
public int getPredNodeCount(Object N) {
int n = nodeMgr.getNumber(N);
return pred.getRelatedCount(n);
}
public Iterator<? extends Object> getSuccNodes(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
if (succ == null) {
return EmptyIterator.instance();
}
SparseIntSet s = new MutableSparseIntSet(succ);
return new IntMapIterator<Object>(s.intIterator(), toNode);
}
public int getSuccNodeCount(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
return succ == null ? 0 : succ.length;
}
public void addEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
public void removeEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
public void removeAllIncidentEdges(Object node) {
Assertions.UNREACHABLE();
}
public void removeIncomingEdges(Object node) {
Assertions.UNREACHABLE();
}
public void removeOutgoingEdges(Object node) {
Assertions.UNREACHABLE();
}
public boolean hasEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
return false;
}
};
@Override
protected NodeManager<Object> getNodeManager() {
return nodeMgr;
}
@Override
protected EdgeManager<Object> getEdgeManager() {
return edgeMgr;
}
};
}
|
diff --git a/extrabiomes/src/bukkit/extrabiomes/terrain/WorldGenRedwood.java b/extrabiomes/src/bukkit/extrabiomes/terrain/WorldGenRedwood.java
index 6181f25f..476d8d4d 100644
--- a/extrabiomes/src/bukkit/extrabiomes/terrain/WorldGenRedwood.java
+++ b/extrabiomes/src/bukkit/extrabiomes/terrain/WorldGenRedwood.java
@@ -1,134 +1,134 @@
package extrabiomes.terrain;
import java.util.Random;
import org.bukkit.BlockChangeDelegate;
import net.minecraft.server.World;
import net.minecraft.server.WorldGenerator;
import net.minecraft.server.Block;
import extrabiomes.api.TerrainGenManager;
public class WorldGenRedwood extends WorldGenerator {
final int blockLeaf;
final int metaLeaf;
final int blockWood;
final int metaWood;
public WorldGenRedwood(boolean flag) {
super(flag);
blockLeaf = TerrainGenManager.blockRedwoodLeaves.id;
metaLeaf = TerrainGenManager.metaRedwoodLeaves;
blockWood = TerrainGenManager.blockRedwoodWood.id;
metaWood = TerrainGenManager.metaRedwoodWood;
}
@Override
public boolean a(World arg0, Random arg1, int arg2, int arg3,
int arg4)
{
return generate((BlockChangeDelegate) arg0, arg1, arg2, arg3,
arg4);
}
public boolean generate(BlockChangeDelegate arg0, Random random, int i, int j, int k) {
- final int l = random.nextInt(8) + 24;
+ final int l = random.nextInt(30) + 32;
final int i1 = 1 + random.nextInt(12);
final int j1 = l - i1;
final int k1 = 2 + random.nextInt(6);
if (j < 1 || j + l + 1 > 256) return false;
final int l1 = arg0.getTypeId(i, j - 1, k);
if (!TerrainGenManager.treesCanGrowOnIDs.contains(Integer
.valueOf(l1)) || j >= 256 - l - 1) return false;
for (int i2 = j; i2 <= j + 1 + l; i2++) {
int k2 = 1;
if (i2 - j < i1)
k2 = 0;
else
k2 = k1;
for (int i3 = i - k2; i3 <= i + k2; i3++)
for (int j3 = k - k2; j3 <= k + k2; j3++)
if (i2 >= 0 && i2 < 256) {
final int i4 = arg0.getTypeId(i3, i2, j3);
if (Block.byId[i4] != null
&& Block.byId[i4].isLeaves(arg0, i3,
i2, j3)) return false;
} else
return false;
}
arg0.setRawTypeId(i, j - 1, k, Block.DIRT.id);
arg0.setRawTypeId(i - 1, j - 1, k, Block.DIRT.id);
arg0.setRawTypeId(i, j - 1, k - 1, Block.DIRT.id);
arg0.setRawTypeId(i - 1, j - 1, k - 1, Block.DIRT.id);
int j2 = random.nextInt(2);
int l2 = 1;
boolean flag = false;
for (int k3 = 0; k3 <= j1; k3++) {
final int j4 = j + l - k3;
for (int l4 = i - j2; l4 <= i + j2; l4++) {
final int j5 = l4 - i;
for (int k5 = k - j2; k5 <= k + j2; k5++) {
final int l5 = k5 - k;
final Block block = Block.byId[arg0.getTypeId(l4,
j4, k5)];
if ((Math.abs(j5) != j2 || Math.abs(l5) != j2 || j2 <= 0)
&& (block == null || block
.canBeReplacedByLeaves(arg0, l4,
j4, k5)))
{
setTypeAndData(arg0, l4, j4, k5, blockLeaf,
metaLeaf);
setTypeAndData(arg0, l4 - 1, j4, k5,
blockLeaf, metaLeaf);
setTypeAndData(arg0, l4, j4, k5 - 1,
blockLeaf, metaLeaf);
setTypeAndData(arg0, l4 - 1, j4, k5 - 1,
blockLeaf, metaLeaf);
}
}
}
if (j2 >= l2) {
j2 = flag ? 1 : 0;
flag = true;
if (++l2 > k1) l2 = k1;
} else
j2++;
}
final int l3 = random.nextInt(3);
for (int k4 = 0; k4 < l - l3; k4++) {
final int i5 = arg0.getTypeId(i, j + k4, k);
if (Block.byId[i5] == null
|| Block.byId[i5].isLeaves(arg0, i, j + k4, k))
{
setTypeAndData(arg0, i, j + k4, k, blockWood, metaWood);
setTypeAndData(arg0, i, j + k4, k, blockWood, metaWood);
setTypeAndData(arg0, i - 1, j + k4, k, blockWood,
metaWood);
setTypeAndData(arg0, i, j + k4, k - 1, blockWood,
metaWood);
setTypeAndData(arg0, i - 1, j + k4, k - 1, blockWood,
metaWood);
}
}
return true;
}
}
| true | true | public boolean generate(BlockChangeDelegate arg0, Random random, int i, int j, int k) {
final int l = random.nextInt(8) + 24;
final int i1 = 1 + random.nextInt(12);
final int j1 = l - i1;
final int k1 = 2 + random.nextInt(6);
if (j < 1 || j + l + 1 > 256) return false;
final int l1 = arg0.getTypeId(i, j - 1, k);
if (!TerrainGenManager.treesCanGrowOnIDs.contains(Integer
.valueOf(l1)) || j >= 256 - l - 1) return false;
for (int i2 = j; i2 <= j + 1 + l; i2++) {
int k2 = 1;
if (i2 - j < i1)
k2 = 0;
else
k2 = k1;
for (int i3 = i - k2; i3 <= i + k2; i3++)
for (int j3 = k - k2; j3 <= k + k2; j3++)
if (i2 >= 0 && i2 < 256) {
final int i4 = arg0.getTypeId(i3, i2, j3);
if (Block.byId[i4] != null
&& Block.byId[i4].isLeaves(arg0, i3,
i2, j3)) return false;
} else
return false;
}
arg0.setRawTypeId(i, j - 1, k, Block.DIRT.id);
arg0.setRawTypeId(i - 1, j - 1, k, Block.DIRT.id);
arg0.setRawTypeId(i, j - 1, k - 1, Block.DIRT.id);
arg0.setRawTypeId(i - 1, j - 1, k - 1, Block.DIRT.id);
int j2 = random.nextInt(2);
int l2 = 1;
boolean flag = false;
for (int k3 = 0; k3 <= j1; k3++) {
final int j4 = j + l - k3;
for (int l4 = i - j2; l4 <= i + j2; l4++) {
final int j5 = l4 - i;
for (int k5 = k - j2; k5 <= k + j2; k5++) {
final int l5 = k5 - k;
final Block block = Block.byId[arg0.getTypeId(l4,
j4, k5)];
if ((Math.abs(j5) != j2 || Math.abs(l5) != j2 || j2 <= 0)
&& (block == null || block
.canBeReplacedByLeaves(arg0, l4,
j4, k5)))
{
setTypeAndData(arg0, l4, j4, k5, blockLeaf,
metaLeaf);
setTypeAndData(arg0, l4 - 1, j4, k5,
blockLeaf, metaLeaf);
setTypeAndData(arg0, l4, j4, k5 - 1,
blockLeaf, metaLeaf);
setTypeAndData(arg0, l4 - 1, j4, k5 - 1,
blockLeaf, metaLeaf);
}
}
}
if (j2 >= l2) {
j2 = flag ? 1 : 0;
flag = true;
if (++l2 > k1) l2 = k1;
} else
j2++;
}
final int l3 = random.nextInt(3);
for (int k4 = 0; k4 < l - l3; k4++) {
final int i5 = arg0.getTypeId(i, j + k4, k);
if (Block.byId[i5] == null
|| Block.byId[i5].isLeaves(arg0, i, j + k4, k))
{
setTypeAndData(arg0, i, j + k4, k, blockWood, metaWood);
setTypeAndData(arg0, i, j + k4, k, blockWood, metaWood);
setTypeAndData(arg0, i - 1, j + k4, k, blockWood,
metaWood);
setTypeAndData(arg0, i, j + k4, k - 1, blockWood,
metaWood);
setTypeAndData(arg0, i - 1, j + k4, k - 1, blockWood,
metaWood);
}
}
return true;
}
| public boolean generate(BlockChangeDelegate arg0, Random random, int i, int j, int k) {
final int l = random.nextInt(30) + 32;
final int i1 = 1 + random.nextInt(12);
final int j1 = l - i1;
final int k1 = 2 + random.nextInt(6);
if (j < 1 || j + l + 1 > 256) return false;
final int l1 = arg0.getTypeId(i, j - 1, k);
if (!TerrainGenManager.treesCanGrowOnIDs.contains(Integer
.valueOf(l1)) || j >= 256 - l - 1) return false;
for (int i2 = j; i2 <= j + 1 + l; i2++) {
int k2 = 1;
if (i2 - j < i1)
k2 = 0;
else
k2 = k1;
for (int i3 = i - k2; i3 <= i + k2; i3++)
for (int j3 = k - k2; j3 <= k + k2; j3++)
if (i2 >= 0 && i2 < 256) {
final int i4 = arg0.getTypeId(i3, i2, j3);
if (Block.byId[i4] != null
&& Block.byId[i4].isLeaves(arg0, i3,
i2, j3)) return false;
} else
return false;
}
arg0.setRawTypeId(i, j - 1, k, Block.DIRT.id);
arg0.setRawTypeId(i - 1, j - 1, k, Block.DIRT.id);
arg0.setRawTypeId(i, j - 1, k - 1, Block.DIRT.id);
arg0.setRawTypeId(i - 1, j - 1, k - 1, Block.DIRT.id);
int j2 = random.nextInt(2);
int l2 = 1;
boolean flag = false;
for (int k3 = 0; k3 <= j1; k3++) {
final int j4 = j + l - k3;
for (int l4 = i - j2; l4 <= i + j2; l4++) {
final int j5 = l4 - i;
for (int k5 = k - j2; k5 <= k + j2; k5++) {
final int l5 = k5 - k;
final Block block = Block.byId[arg0.getTypeId(l4,
j4, k5)];
if ((Math.abs(j5) != j2 || Math.abs(l5) != j2 || j2 <= 0)
&& (block == null || block
.canBeReplacedByLeaves(arg0, l4,
j4, k5)))
{
setTypeAndData(arg0, l4, j4, k5, blockLeaf,
metaLeaf);
setTypeAndData(arg0, l4 - 1, j4, k5,
blockLeaf, metaLeaf);
setTypeAndData(arg0, l4, j4, k5 - 1,
blockLeaf, metaLeaf);
setTypeAndData(arg0, l4 - 1, j4, k5 - 1,
blockLeaf, metaLeaf);
}
}
}
if (j2 >= l2) {
j2 = flag ? 1 : 0;
flag = true;
if (++l2 > k1) l2 = k1;
} else
j2++;
}
final int l3 = random.nextInt(3);
for (int k4 = 0; k4 < l - l3; k4++) {
final int i5 = arg0.getTypeId(i, j + k4, k);
if (Block.byId[i5] == null
|| Block.byId[i5].isLeaves(arg0, i, j + k4, k))
{
setTypeAndData(arg0, i, j + k4, k, blockWood, metaWood);
setTypeAndData(arg0, i, j + k4, k, blockWood, metaWood);
setTypeAndData(arg0, i - 1, j + k4, k, blockWood,
metaWood);
setTypeAndData(arg0, i, j + k4, k - 1, blockWood,
metaWood);
setTypeAndData(arg0, i - 1, j + k4, k - 1, blockWood,
metaWood);
}
}
return true;
}
|
diff --git a/SpagoBIQbeEngine/src/it/eng/spagobi/engines/qbe/services/core/ValidateExpressionAction.java b/SpagoBIQbeEngine/src/it/eng/spagobi/engines/qbe/services/core/ValidateExpressionAction.java
index 566228d47..a2fc3076e 100644
--- a/SpagoBIQbeEngine/src/it/eng/spagobi/engines/qbe/services/core/ValidateExpressionAction.java
+++ b/SpagoBIQbeEngine/src/it/eng/spagobi/engines/qbe/services/core/ValidateExpressionAction.java
@@ -1,236 +1,236 @@
/* SpagoBI, the Open Source Business Intelligence suite
* Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice.
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package it.eng.spagobi.engines.qbe.services.core;
import it.eng.spago.base.SourceBean;
import it.eng.spagobi.commons.bo.UserProfile;
import it.eng.spagobi.utilities.assertion.Assert;
import it.eng.spagobi.utilities.engines.EngineConstants;
import it.eng.spagobi.utilities.engines.SpagoBIEngineServiceException;
import it.eng.spagobi.utilities.engines.SpagoBIEngineServiceExceptionHandler;
import it.eng.spagobi.utilities.service.JSONAcknowledge;
import it.eng.spagobi.utilities.service.JSONFailure;
import it.eng.spagobi.utilities.service.JSONResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
/**
*
* @author Andrea Gioia (andrea.gioia@eng.it)
*/
public class ValidateExpressionAction extends AbstractQbeEngineAction {
public static final String EXPRESSION = "expression";
public static final String FIELDS = "fields";
public static final String SERVICE_NAME = "VALIDATE_EXPRESSION_ACTION";
public String getActionName(){return SERVICE_NAME;}
/** Logger component. */
public static transient Logger logger = Logger.getLogger(ValidateExpressionAction.class);
public void service(SourceBean request, SourceBean response) {
String expression;
JSONArray fieldsJSON;
// filed in context (mapped by unique name and by alias)
Set availableDMFields;
Set availableQFields;
// unresolved field reference errors stack
List uresolvedReferenceErrors;
List items;
Pattern seedPattern;
Matcher seedMatcher;
// bindings
Map attributes;
Map parameters;
Map qFields;
Map dmFields;
ScriptEngineManager scriptManager;
ScriptEngine groovyScriptEngine;
logger.debug("IN");
try {
super.service(request, response);
expression = getAttributeAsString( EXPRESSION );
logger.debug("Parameter [" + EXPRESSION + "] is equals to [" + expression + "]");
Assert.assertNotNull(expression, "Parameter [" + EXPRESSION + "] cannot be null in oder to execute " + this.getActionName() + " service");
fieldsJSON = getAttributeAsJSONArray( FIELDS );
logger.debug("Parameter [" + FIELDS + "] is equals to [" + fieldsJSON + "]");
Assert.assertNotNull(fieldsJSON, "Parameter [" + FIELDS + "] cannot be null in oder to execute " + this.getActionName() + " service");
availableQFields = new HashSet();
availableDMFields = new HashSet();
for(int i = 0; i < fieldsJSON.length(); i++) {
JSONObject field = fieldsJSON.getJSONObject(i);
availableDMFields.add(field.getString("uniqueName"));
availableQFields.add(field.getString("alias"));
}
attributes = new HashMap();
UserProfile profile = (UserProfile)this.getEnv().get(EngineConstants.ENV_USER_PROFILE);
Iterator it = profile.getUserAttributeNames().iterator();
while(it.hasNext()) {
String attributeName = (String)it.next();
Object attributeValue = profile.getUserAttribute(attributeName);
attributes.put(attributeName, attributeValue);
}
parameters = this.getEnv();
// check for unresolved reference first
uresolvedReferenceErrors = new ArrayList();
seedPattern = Pattern.compile("'[^']*'");
// ... in fields
items = new ArrayList();
items.addAll(extractItems("fields", expression));
items.addAll(extractItems("qFields", expression));
items.addAll(extractItems("dmFields", expression));
qFields = new HashMap();
dmFields = new HashMap();
for(int i = 0; i < items.size(); i++) {
String item = (String)items.get(i);
seedMatcher = seedPattern.matcher(item);
seedMatcher.find();
String seed = seedMatcher.group().substring(1, seedMatcher.group().length()-1);
if(!availableQFields.contains(seed) && !availableDMFields.contains(seed)) {
uresolvedReferenceErrors.add("Impossible to resolve reference to filed: " + item);
}
if(item.trim().startsWith("dmFields")) {
- dmFields.put(seed, "1000");
+ dmFields.put(seed, 1000);
} else {
- qFields.put(seed, "1000");
+ qFields.put(seed, 1000);
}
}
// ... in attributes
items = new ArrayList();
items.addAll(extractItems("attributes", expression));
for(int i = 0; i < items.size(); i++) {
String item = (String)items.get(i);
seedMatcher = seedPattern.matcher(item);
seedMatcher.find();
String seed = seedMatcher.group().substring(1, seedMatcher.group().length()-1);
if( !attributes.containsKey(seed) ) {
uresolvedReferenceErrors.add("Impossible to resolve reference to attribute: " + item);
}
}
// ... in parameters
items = new ArrayList();
items.addAll(extractItems("parameters", expression));
for(int i = 0; i < items.size(); i++) {
String item = (String)items.get(i);
seedMatcher = seedPattern.matcher(item);
seedMatcher.find();
String seed = seedMatcher.group().substring(1, seedMatcher.group().length()-1);
if( !parameters.containsKey(seed) ) {
uresolvedReferenceErrors.add("Impossible to resolve reference to parameter: " + item);
}
}
JSONResponse jsonResponse = null;
if(uresolvedReferenceErrors.size() > 0) {
SpagoBIEngineServiceException validationException;
String msg = "Unresolved reference error: ";
for(int i = 0; i < uresolvedReferenceErrors.size(); i++) {
String error = (String)uresolvedReferenceErrors.get(i);
msg += "\n" + error + "; ";
}
validationException = new SpagoBIEngineServiceException(getActionName(), msg);
jsonResponse = new JSONFailure(validationException);
} else {
scriptManager = new ScriptEngineManager();
groovyScriptEngine = scriptManager.getEngineByName("groovy");
// bindings ...
groovyScriptEngine.put("attributes", attributes);
groovyScriptEngine.put("parameters", parameters);
groovyScriptEngine.put("qFields", qFields);
groovyScriptEngine.put("dmFields", dmFields);
groovyScriptEngine.put("fields", qFields);
Object calculatedValue = null;
try {
calculatedValue = groovyScriptEngine.eval(expression);
jsonResponse = new JSONAcknowledge();
} catch (ScriptException e) {
SpagoBIEngineServiceException validationException;
Throwable t = e;
String msg = t.getMessage();
while( (msg = t.getMessage()) == null && t.getCause()!= null) t = t.getCause();
if(msg == null) msg = e.toString();
//msg = "Syntatic error at line:" + e.getLineNumber() + ", column:" + e.getColumnNumber() + ". Error details: " + msg;
validationException = new SpagoBIEngineServiceException(getActionName(), msg, e);
jsonResponse = new JSONFailure(validationException);
//logger.error("validation error", e);
}
}
try {
writeBackToClient( jsonResponse );
} catch (IOException e) {
String message = "Impossible to write back the responce to the client";
throw new SpagoBIEngineServiceException(getActionName(), message, e);
}
} catch(Throwable t) {
throw SpagoBIEngineServiceExceptionHandler.getInstance().getWrappedException(getActionName(), getEngineInstance(), t);
} finally {
logger.debug("OUT");
}
}
private List extractItems(String itemGroupName, String expression) {
List items;
Pattern itemPattern;
Matcher itemMatcher;
items = new ArrayList();
itemPattern = Pattern.compile(itemGroupName + "\\['[^']+'\\]");
itemMatcher = itemPattern.matcher(expression);
while(itemMatcher.find()) {
items.add(itemMatcher.group());
}
return items;
}
}
| false | true | public void service(SourceBean request, SourceBean response) {
String expression;
JSONArray fieldsJSON;
// filed in context (mapped by unique name and by alias)
Set availableDMFields;
Set availableQFields;
// unresolved field reference errors stack
List uresolvedReferenceErrors;
List items;
Pattern seedPattern;
Matcher seedMatcher;
// bindings
Map attributes;
Map parameters;
Map qFields;
Map dmFields;
ScriptEngineManager scriptManager;
ScriptEngine groovyScriptEngine;
logger.debug("IN");
try {
super.service(request, response);
expression = getAttributeAsString( EXPRESSION );
logger.debug("Parameter [" + EXPRESSION + "] is equals to [" + expression + "]");
Assert.assertNotNull(expression, "Parameter [" + EXPRESSION + "] cannot be null in oder to execute " + this.getActionName() + " service");
fieldsJSON = getAttributeAsJSONArray( FIELDS );
logger.debug("Parameter [" + FIELDS + "] is equals to [" + fieldsJSON + "]");
Assert.assertNotNull(fieldsJSON, "Parameter [" + FIELDS + "] cannot be null in oder to execute " + this.getActionName() + " service");
availableQFields = new HashSet();
availableDMFields = new HashSet();
for(int i = 0; i < fieldsJSON.length(); i++) {
JSONObject field = fieldsJSON.getJSONObject(i);
availableDMFields.add(field.getString("uniqueName"));
availableQFields.add(field.getString("alias"));
}
attributes = new HashMap();
UserProfile profile = (UserProfile)this.getEnv().get(EngineConstants.ENV_USER_PROFILE);
Iterator it = profile.getUserAttributeNames().iterator();
while(it.hasNext()) {
String attributeName = (String)it.next();
Object attributeValue = profile.getUserAttribute(attributeName);
attributes.put(attributeName, attributeValue);
}
parameters = this.getEnv();
// check for unresolved reference first
uresolvedReferenceErrors = new ArrayList();
seedPattern = Pattern.compile("'[^']*'");
// ... in fields
items = new ArrayList();
items.addAll(extractItems("fields", expression));
items.addAll(extractItems("qFields", expression));
items.addAll(extractItems("dmFields", expression));
qFields = new HashMap();
dmFields = new HashMap();
for(int i = 0; i < items.size(); i++) {
String item = (String)items.get(i);
seedMatcher = seedPattern.matcher(item);
seedMatcher.find();
String seed = seedMatcher.group().substring(1, seedMatcher.group().length()-1);
if(!availableQFields.contains(seed) && !availableDMFields.contains(seed)) {
uresolvedReferenceErrors.add("Impossible to resolve reference to filed: " + item);
}
if(item.trim().startsWith("dmFields")) {
dmFields.put(seed, "1000");
} else {
qFields.put(seed, "1000");
}
}
// ... in attributes
items = new ArrayList();
items.addAll(extractItems("attributes", expression));
for(int i = 0; i < items.size(); i++) {
String item = (String)items.get(i);
seedMatcher = seedPattern.matcher(item);
seedMatcher.find();
String seed = seedMatcher.group().substring(1, seedMatcher.group().length()-1);
if( !attributes.containsKey(seed) ) {
uresolvedReferenceErrors.add("Impossible to resolve reference to attribute: " + item);
}
}
// ... in parameters
items = new ArrayList();
items.addAll(extractItems("parameters", expression));
for(int i = 0; i < items.size(); i++) {
String item = (String)items.get(i);
seedMatcher = seedPattern.matcher(item);
seedMatcher.find();
String seed = seedMatcher.group().substring(1, seedMatcher.group().length()-1);
if( !parameters.containsKey(seed) ) {
uresolvedReferenceErrors.add("Impossible to resolve reference to parameter: " + item);
}
}
JSONResponse jsonResponse = null;
if(uresolvedReferenceErrors.size() > 0) {
SpagoBIEngineServiceException validationException;
String msg = "Unresolved reference error: ";
for(int i = 0; i < uresolvedReferenceErrors.size(); i++) {
String error = (String)uresolvedReferenceErrors.get(i);
msg += "\n" + error + "; ";
}
validationException = new SpagoBIEngineServiceException(getActionName(), msg);
jsonResponse = new JSONFailure(validationException);
} else {
scriptManager = new ScriptEngineManager();
groovyScriptEngine = scriptManager.getEngineByName("groovy");
// bindings ...
groovyScriptEngine.put("attributes", attributes);
groovyScriptEngine.put("parameters", parameters);
groovyScriptEngine.put("qFields", qFields);
groovyScriptEngine.put("dmFields", dmFields);
groovyScriptEngine.put("fields", qFields);
Object calculatedValue = null;
try {
calculatedValue = groovyScriptEngine.eval(expression);
jsonResponse = new JSONAcknowledge();
} catch (ScriptException e) {
SpagoBIEngineServiceException validationException;
Throwable t = e;
String msg = t.getMessage();
while( (msg = t.getMessage()) == null && t.getCause()!= null) t = t.getCause();
if(msg == null) msg = e.toString();
//msg = "Syntatic error at line:" + e.getLineNumber() + ", column:" + e.getColumnNumber() + ". Error details: " + msg;
validationException = new SpagoBIEngineServiceException(getActionName(), msg, e);
jsonResponse = new JSONFailure(validationException);
//logger.error("validation error", e);
}
}
try {
writeBackToClient( jsonResponse );
} catch (IOException e) {
String message = "Impossible to write back the responce to the client";
throw new SpagoBIEngineServiceException(getActionName(), message, e);
}
} catch(Throwable t) {
throw SpagoBIEngineServiceExceptionHandler.getInstance().getWrappedException(getActionName(), getEngineInstance(), t);
} finally {
logger.debug("OUT");
}
}
| public void service(SourceBean request, SourceBean response) {
String expression;
JSONArray fieldsJSON;
// filed in context (mapped by unique name and by alias)
Set availableDMFields;
Set availableQFields;
// unresolved field reference errors stack
List uresolvedReferenceErrors;
List items;
Pattern seedPattern;
Matcher seedMatcher;
// bindings
Map attributes;
Map parameters;
Map qFields;
Map dmFields;
ScriptEngineManager scriptManager;
ScriptEngine groovyScriptEngine;
logger.debug("IN");
try {
super.service(request, response);
expression = getAttributeAsString( EXPRESSION );
logger.debug("Parameter [" + EXPRESSION + "] is equals to [" + expression + "]");
Assert.assertNotNull(expression, "Parameter [" + EXPRESSION + "] cannot be null in oder to execute " + this.getActionName() + " service");
fieldsJSON = getAttributeAsJSONArray( FIELDS );
logger.debug("Parameter [" + FIELDS + "] is equals to [" + fieldsJSON + "]");
Assert.assertNotNull(fieldsJSON, "Parameter [" + FIELDS + "] cannot be null in oder to execute " + this.getActionName() + " service");
availableQFields = new HashSet();
availableDMFields = new HashSet();
for(int i = 0; i < fieldsJSON.length(); i++) {
JSONObject field = fieldsJSON.getJSONObject(i);
availableDMFields.add(field.getString("uniqueName"));
availableQFields.add(field.getString("alias"));
}
attributes = new HashMap();
UserProfile profile = (UserProfile)this.getEnv().get(EngineConstants.ENV_USER_PROFILE);
Iterator it = profile.getUserAttributeNames().iterator();
while(it.hasNext()) {
String attributeName = (String)it.next();
Object attributeValue = profile.getUserAttribute(attributeName);
attributes.put(attributeName, attributeValue);
}
parameters = this.getEnv();
// check for unresolved reference first
uresolvedReferenceErrors = new ArrayList();
seedPattern = Pattern.compile("'[^']*'");
// ... in fields
items = new ArrayList();
items.addAll(extractItems("fields", expression));
items.addAll(extractItems("qFields", expression));
items.addAll(extractItems("dmFields", expression));
qFields = new HashMap();
dmFields = new HashMap();
for(int i = 0; i < items.size(); i++) {
String item = (String)items.get(i);
seedMatcher = seedPattern.matcher(item);
seedMatcher.find();
String seed = seedMatcher.group().substring(1, seedMatcher.group().length()-1);
if(!availableQFields.contains(seed) && !availableDMFields.contains(seed)) {
uresolvedReferenceErrors.add("Impossible to resolve reference to filed: " + item);
}
if(item.trim().startsWith("dmFields")) {
dmFields.put(seed, 1000);
} else {
qFields.put(seed, 1000);
}
}
// ... in attributes
items = new ArrayList();
items.addAll(extractItems("attributes", expression));
for(int i = 0; i < items.size(); i++) {
String item = (String)items.get(i);
seedMatcher = seedPattern.matcher(item);
seedMatcher.find();
String seed = seedMatcher.group().substring(1, seedMatcher.group().length()-1);
if( !attributes.containsKey(seed) ) {
uresolvedReferenceErrors.add("Impossible to resolve reference to attribute: " + item);
}
}
// ... in parameters
items = new ArrayList();
items.addAll(extractItems("parameters", expression));
for(int i = 0; i < items.size(); i++) {
String item = (String)items.get(i);
seedMatcher = seedPattern.matcher(item);
seedMatcher.find();
String seed = seedMatcher.group().substring(1, seedMatcher.group().length()-1);
if( !parameters.containsKey(seed) ) {
uresolvedReferenceErrors.add("Impossible to resolve reference to parameter: " + item);
}
}
JSONResponse jsonResponse = null;
if(uresolvedReferenceErrors.size() > 0) {
SpagoBIEngineServiceException validationException;
String msg = "Unresolved reference error: ";
for(int i = 0; i < uresolvedReferenceErrors.size(); i++) {
String error = (String)uresolvedReferenceErrors.get(i);
msg += "\n" + error + "; ";
}
validationException = new SpagoBIEngineServiceException(getActionName(), msg);
jsonResponse = new JSONFailure(validationException);
} else {
scriptManager = new ScriptEngineManager();
groovyScriptEngine = scriptManager.getEngineByName("groovy");
// bindings ...
groovyScriptEngine.put("attributes", attributes);
groovyScriptEngine.put("parameters", parameters);
groovyScriptEngine.put("qFields", qFields);
groovyScriptEngine.put("dmFields", dmFields);
groovyScriptEngine.put("fields", qFields);
Object calculatedValue = null;
try {
calculatedValue = groovyScriptEngine.eval(expression);
jsonResponse = new JSONAcknowledge();
} catch (ScriptException e) {
SpagoBIEngineServiceException validationException;
Throwable t = e;
String msg = t.getMessage();
while( (msg = t.getMessage()) == null && t.getCause()!= null) t = t.getCause();
if(msg == null) msg = e.toString();
//msg = "Syntatic error at line:" + e.getLineNumber() + ", column:" + e.getColumnNumber() + ". Error details: " + msg;
validationException = new SpagoBIEngineServiceException(getActionName(), msg, e);
jsonResponse = new JSONFailure(validationException);
//logger.error("validation error", e);
}
}
try {
writeBackToClient( jsonResponse );
} catch (IOException e) {
String message = "Impossible to write back the responce to the client";
throw new SpagoBIEngineServiceException(getActionName(), message, e);
}
} catch(Throwable t) {
throw SpagoBIEngineServiceExceptionHandler.getInstance().getWrappedException(getActionName(), getEngineInstance(), t);
} finally {
logger.debug("OUT");
}
}
|
diff --git a/src/animata/LayerView.java b/src/animata/LayerView.java
index b527912..0bd3508 100644
--- a/src/animata/LayerView.java
+++ b/src/animata/LayerView.java
@@ -1,90 +1,90 @@
package animata;
import java.util.ArrayList;
import processing.core.PApplet;
import animata.model.Layer;
public class LayerView {
protected final PApplet applet;
private final Layer layer;
private MeshView mesh;
private ArrayList<LayerView> layers;
public LayerView(Layer layer, PApplet applet) {
this.applet = applet;
this.layer = layer;
if (layer.mesh != null) {
mesh = new MeshView(applet, layer);
}
addChildLayers(layer.layers);
}
public Layer getLayer(String layerName) {
//System.err.println("LayerView#getLayer: " + layerName ); // DEBUG
Layer l = null;
for (Layer ll : layer.layers) {
// System.err.println("LayerView#getLayer: compare " + layerName + " to " + ll.name); // DEBUG
if (ll.name.equals(layerName)) {
return ll;
}
}
return l;
}
// This seems to work OK under simple conditions but the
// lack of any way to target a layer is a Bad Idea.
public void setNewMeshImage(String imageName, String layerName ) {
// System.err.println("LayerView#setNewMeshImage: " + imageName + " for " + layerName ); // DEBUG
for (Layer llayer : layer.layers) {
llayer.setNewTextureImage(applet, imageName, layerName);
}
//}
}
private void addChildLayers(ArrayList<Layer> layers) {
this.layers = new ArrayList<LayerView>();
for (Layer llayer : layers) {
this.layers.add(new LayerView(llayer, applet));
}
}
public void draw(float x, float y) {
// System.err.println("LayerView#draw using: " + x + ", " + y + ". "); // DEBUG
// System.err.println("LayerView#draw This layer has x, y " + layer.x() + ", " + layer.y() ); // DEBUG
// This will propagate layer locatins down to child layers. Is this correct?
// Is the location of child layers relative to the parent layer?
x = x+layer.x();
y = y+layer.y();
- // How can we apply the changein x, y set in the Layer?
- // The current x,y seems to xome direct from the sketch, in `draw` (e.g. Foo.draw(10, 20);)
- // We could grab the x,y stored in the layer and appyt it
+ // How can we apply the change in x, y set in the Layer?
+ // The current x,y seems to come direct from the sketch, in `draw` (e.g. Foo.draw(10, 20);)
+ // We could grab the x,y stored in the layer and apply it
applet.pushMatrix();
doTransformation(x, y);
if (mesh != null) {
mesh.draw();
}
applet.popMatrix();
drawChildLayers(x, y);
}
private void drawChildLayers(float x, float y) {
for (LayerView layerView : layers) {
if (layerView.layer.visible() ) {
layerView.draw(x, y);
}
}
}
private void doTransformation(float _x, float _y) {
applet.translate(layer.x + _x, layer.y + _y, layer.z);
applet.scale(layer.scale, layer.scale, 1);
}
}
| true | true | public void draw(float x, float y) {
// System.err.println("LayerView#draw using: " + x + ", " + y + ". "); // DEBUG
// System.err.println("LayerView#draw This layer has x, y " + layer.x() + ", " + layer.y() ); // DEBUG
// This will propagate layer locatins down to child layers. Is this correct?
// Is the location of child layers relative to the parent layer?
x = x+layer.x();
y = y+layer.y();
// How can we apply the changein x, y set in the Layer?
// The current x,y seems to xome direct from the sketch, in `draw` (e.g. Foo.draw(10, 20);)
// We could grab the x,y stored in the layer and appyt it
applet.pushMatrix();
doTransformation(x, y);
if (mesh != null) {
mesh.draw();
}
applet.popMatrix();
drawChildLayers(x, y);
}
| public void draw(float x, float y) {
// System.err.println("LayerView#draw using: " + x + ", " + y + ". "); // DEBUG
// System.err.println("LayerView#draw This layer has x, y " + layer.x() + ", " + layer.y() ); // DEBUG
// This will propagate layer locatins down to child layers. Is this correct?
// Is the location of child layers relative to the parent layer?
x = x+layer.x();
y = y+layer.y();
// How can we apply the change in x, y set in the Layer?
// The current x,y seems to come direct from the sketch, in `draw` (e.g. Foo.draw(10, 20);)
// We could grab the x,y stored in the layer and apply it
applet.pushMatrix();
doTransformation(x, y);
if (mesh != null) {
mesh.draw();
}
applet.popMatrix();
drawChildLayers(x, y);
}
|
diff --git a/grisu-client/src/main/java/grisu/frontend/control/JaxWsServiceInterfaceCreator.java b/grisu-client/src/main/java/grisu/frontend/control/JaxWsServiceInterfaceCreator.java
index b7ee402c..57c228b5 100644
--- a/grisu-client/src/main/java/grisu/frontend/control/JaxWsServiceInterfaceCreator.java
+++ b/grisu-client/src/main/java/grisu/frontend/control/JaxWsServiceInterfaceCreator.java
@@ -1,229 +1,230 @@
package grisu.frontend.control;
import grisu.control.ServiceInterface;
import grisu.control.ServiceInterfaceCreator;
import grisu.control.exceptions.ServiceInterfaceException;
import grisu.settings.Environment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.soap.MTOMFeature;
import javax.xml.ws.soap.SOAPBinding;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.sun.xml.ws.developer.JAXWSProperties;
public class JaxWsServiceInterfaceCreator implements ServiceInterfaceCreator {
static final Logger myLogger = Logger
.getLogger(JaxWsServiceInterfaceCreator.class.getName());
public static String TRUST_FILE_NAME = Environment
.getGrisuClientDirectory().getPath()
+ File.separator
+ "truststore.jks";
/**
* configures secure connection parameters.
**/
public JaxWsServiceInterfaceCreator() throws ServiceInterfaceException {
try {
if (!(new File(Environment.getGrisuClientDirectory(),
"truststore.jks").exists())) {
final InputStream ts = JaxWsServiceInterfaceCreator.class
.getResourceAsStream("/truststore.jks");
IOUtils.copy(ts, new FileOutputStream(TRUST_FILE_NAME));
}
} catch (final IOException ex) {
throw new ServiceInterfaceException(
"cannot copy SSL certificate store into grisu home directory. Does "
+ Environment.getGrisuClientDirectory().getPath()
+ " exist?", ex);
}
System.setProperty("javax.net.ssl.trustStore", TRUST_FILE_NAME);
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
}
public boolean canHandleUrl(String url) {
if (StringUtils.isNotBlank(url) && url.startsWith("http")) {
return true;
} else {
return false;
}
}
public ServiceInterface create(String interfaceUrl, String username,
char[] password, String myProxyServer, String myProxyPort,
Object[] otherOptions) throws ServiceInterfaceException {
try {
final QName serviceName = new QName(
"http://api.grisu.arcs.org.au/", "GrisuService");
final QName portName = new QName("http://api.grisu.arcs.org.au/",
// "ServiceInterfaceSOAPPort");
"ServiceInterfacePort");
Service s;
try {
s = Service.create(
new URL(interfaceUrl.replace("soap/GrisuService",
"api.wsdl")), serviceName);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
final MTOMFeature mtom = new MTOMFeature();
try {
s.getPort(portName, ServiceInterface.class, mtom);
} catch (Error e) {
// throw new ServiceInterfaceException(
// "Could not connect to backend, probably because of frontend/backend incompatibility (Underlying cause: \""
// + e.getLocalizedMessage()
// +
// "\"). Before reporting a bug, please try latest client from: http://code.ceres.auckland.ac.nz/stable-downloads.");
throw new ServiceInterfaceException(
"Sorry, could not login. Most likely your client version is incompatible with the server.\n"
+ "Please download the latest version from:\nhttp://code.ceres.auckland.ac.nz/stable-downloads\n"
+ "If you have the latest version and are still experiencing this problem please contact\n"
+ "eresearch-admin@list.auckland.ac.nz\n"
- + "with a description of the issue.", e);
+ + "with a description of the issue.\n\nUnderlying cause: "
+ + e.getLocalizedMessage());
}
final ServiceInterface service = s.getPort(portName,
ServiceInterface.class);
final BindingProvider bp = (javax.xml.ws.BindingProvider) service;
bp.getRequestContext().put(
javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
interfaceUrl);
bp.getRequestContext().put(
JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 4096);
// just to be sure, I'll keep that in there as well...
bp.getRequestContext()
.put("com.sun.xml.internal.ws.transport.http.client.streaming.chunk.size",
new Integer(4096));
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,
username);
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,
new String(password));
bp.getRequestContext().put(
BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
final SOAPBinding binding = (SOAPBinding) bp.getBinding();
binding.setMTOMEnabled(true);
return service;
} catch (final Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new ServiceInterfaceException(
"Could not create JaxwsServiceInterface: "
+ e.getLocalizedMessage(), e);
}
}
// private SSLSocketFactory createSocketFactory(String interfaceUrl)
// throws ServiceInterfaceException {
// // Technique similar to
// // http://juliusdavies.ca/commons-ssl/TrustExample.java.html
// HttpSecureProtocol protocolSocketFactory;
// try {
// protocolSocketFactory = new HttpSecureProtocol();
//
// TrustMaterial trustMaterial = null;
//
// // "/thecertificate.cer" can be PEM or DER (raw ASN.1). Can even
// // be several PEM certificates in one file.
//
// String cacertFilename = System.getProperty("grisu.cacert");
// URL cacertURL = null;
//
// try {
// if (cacertFilename != null && !"".equals(cacertFilename)) {
// cacertURL = JaxWsServiceInterfaceCreator.class
// .getResource("/" + cacertFilename);
// if (cacertURL != null) {
// myLogger.debug("Using cacert " + cacertFilename
// + " as configured in the -D option.");
// }
// }
// } catch (Exception e) {
// // doesn't matter
// myLogger
// .debug("Couldn't find specified cacert. Using default one.");
// }
//
// if (cacertURL == null) {
//
// cacertFilename = new CaCertManager()
// .getCaCertNameForServiceInterfaceUrl(interfaceUrl);
// if (cacertFilename != null && cacertFilename.length() > 0) {
// myLogger
// .debug("Found url in map. Trying to use this cacert file: "
// + cacertFilename);
// cacertURL = JaxWsServiceInterfaceCreator.class
// .getResource("/" + cacertFilename);
// if (cacertURL == null) {
// myLogger
// .debug("Didn't find cacert. Using the default one.");
// // use the default one
// cacertURL = JaxWsServiceInterfaceCreator.class
// .getResource("/cacert.pem");
// } else {
// myLogger.debug("Found cacert. Using it. Good.");
// }
// } else {
// myLogger
// .debug("Didn't find any configuration for a special cacert. Using the default one.");
// // use the default one
// cacertURL = JaxWsServiceInterfaceCreator.class
// .getResource("/cacert.pem");
// }
//
// }
//
// trustMaterial = new TrustMaterial(cacertURL);
//
// // We can use setTrustMaterial() instead of addTrustMaterial()
// // if we want to remove
// // HttpSecureProtocol's default trust of TrustMaterial.CACERTS.
// protocolSocketFactory.addTrustMaterial(trustMaterial);
//
// // Maybe we want to turn off CN validation (not recommended!):
// protocolSocketFactory.setCheckHostname(false);
//
// Protocol protocol = new Protocol("https",
// (ProtocolSocketFactory) protocolSocketFactory, 443);
// Protocol.registerProtocol("https", protocol);
//
// return protocolSocketFactory;
// } catch (Exception e1) {
// // TODO Auto-generated catch block
// // e1.printStackTrace();
// throw new ServiceInterfaceException(
// "Unspecified error while trying to establish secure connection.",
// e1);
// }
// }
}
| true | true | public ServiceInterface create(String interfaceUrl, String username,
char[] password, String myProxyServer, String myProxyPort,
Object[] otherOptions) throws ServiceInterfaceException {
try {
final QName serviceName = new QName(
"http://api.grisu.arcs.org.au/", "GrisuService");
final QName portName = new QName("http://api.grisu.arcs.org.au/",
// "ServiceInterfaceSOAPPort");
"ServiceInterfacePort");
Service s;
try {
s = Service.create(
new URL(interfaceUrl.replace("soap/GrisuService",
"api.wsdl")), serviceName);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
final MTOMFeature mtom = new MTOMFeature();
try {
s.getPort(portName, ServiceInterface.class, mtom);
} catch (Error e) {
// throw new ServiceInterfaceException(
// "Could not connect to backend, probably because of frontend/backend incompatibility (Underlying cause: \""
// + e.getLocalizedMessage()
// +
// "\"). Before reporting a bug, please try latest client from: http://code.ceres.auckland.ac.nz/stable-downloads.");
throw new ServiceInterfaceException(
"Sorry, could not login. Most likely your client version is incompatible with the server.\n"
+ "Please download the latest version from:\nhttp://code.ceres.auckland.ac.nz/stable-downloads\n"
+ "If you have the latest version and are still experiencing this problem please contact\n"
+ "eresearch-admin@list.auckland.ac.nz\n"
+ "with a description of the issue.", e);
}
final ServiceInterface service = s.getPort(portName,
ServiceInterface.class);
final BindingProvider bp = (javax.xml.ws.BindingProvider) service;
bp.getRequestContext().put(
javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
interfaceUrl);
bp.getRequestContext().put(
JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 4096);
// just to be sure, I'll keep that in there as well...
bp.getRequestContext()
.put("com.sun.xml.internal.ws.transport.http.client.streaming.chunk.size",
new Integer(4096));
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,
username);
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,
new String(password));
bp.getRequestContext().put(
BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
final SOAPBinding binding = (SOAPBinding) bp.getBinding();
binding.setMTOMEnabled(true);
return service;
} catch (final Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new ServiceInterfaceException(
"Could not create JaxwsServiceInterface: "
+ e.getLocalizedMessage(), e);
}
}
| public ServiceInterface create(String interfaceUrl, String username,
char[] password, String myProxyServer, String myProxyPort,
Object[] otherOptions) throws ServiceInterfaceException {
try {
final QName serviceName = new QName(
"http://api.grisu.arcs.org.au/", "GrisuService");
final QName portName = new QName("http://api.grisu.arcs.org.au/",
// "ServiceInterfaceSOAPPort");
"ServiceInterfacePort");
Service s;
try {
s = Service.create(
new URL(interfaceUrl.replace("soap/GrisuService",
"api.wsdl")), serviceName);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
final MTOMFeature mtom = new MTOMFeature();
try {
s.getPort(portName, ServiceInterface.class, mtom);
} catch (Error e) {
// throw new ServiceInterfaceException(
// "Could not connect to backend, probably because of frontend/backend incompatibility (Underlying cause: \""
// + e.getLocalizedMessage()
// +
// "\"). Before reporting a bug, please try latest client from: http://code.ceres.auckland.ac.nz/stable-downloads.");
throw new ServiceInterfaceException(
"Sorry, could not login. Most likely your client version is incompatible with the server.\n"
+ "Please download the latest version from:\nhttp://code.ceres.auckland.ac.nz/stable-downloads\n"
+ "If you have the latest version and are still experiencing this problem please contact\n"
+ "eresearch-admin@list.auckland.ac.nz\n"
+ "with a description of the issue.\n\nUnderlying cause: "
+ e.getLocalizedMessage());
}
final ServiceInterface service = s.getPort(portName,
ServiceInterface.class);
final BindingProvider bp = (javax.xml.ws.BindingProvider) service;
bp.getRequestContext().put(
javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
interfaceUrl);
bp.getRequestContext().put(
JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 4096);
// just to be sure, I'll keep that in there as well...
bp.getRequestContext()
.put("com.sun.xml.internal.ws.transport.http.client.streaming.chunk.size",
new Integer(4096));
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,
username);
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,
new String(password));
bp.getRequestContext().put(
BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
final SOAPBinding binding = (SOAPBinding) bp.getBinding();
binding.setMTOMEnabled(true);
return service;
} catch (final Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new ServiceInterfaceException(
"Could not create JaxwsServiceInterface: "
+ e.getLocalizedMessage(), e);
}
}
|
diff --git a/scm-core/src/main/java/sonia/scm/config/ScmConfiguration.java b/scm-core/src/main/java/sonia/scm/config/ScmConfiguration.java
index fe593e11c..7c49da3c9 100644
--- a/scm-core/src/main/java/sonia/scm/config/ScmConfiguration.java
+++ b/scm-core/src/main/java/sonia/scm/config/ScmConfiguration.java
@@ -1,760 +1,761 @@
/**
* Copyright (c) 2010, Sebastian Sdorra
* 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. Neither the name of SCM-Manager; 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 REGENTS 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.
*
* http://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.config;
//~--- non-JDK imports --------------------------------------------------------
import com.google.common.collect.Sets;
import com.google.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.ConfigChangedListener;
import sonia.scm.ListenerSupport;
import sonia.scm.xml.XmlSetStringAdapter;
//~--- JDK imports ------------------------------------------------------------
import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* The main configuration object for SCM-Manager.
* This class is a singleton and is available via injection.
*
* @author Sebastian Sdorra
*/
@Singleton
@XmlRootElement(name = "scm-config")
@XmlAccessorType(XmlAccessType.FIELD)
public class ScmConfiguration
implements ListenerSupport<ConfigChangedListener<ScmConfiguration>>
{
/** Default JavaScript date format */
public static final String DEFAULT_DATEFORMAT = "Y-m-d H:i:s";
/** Default plugin url */
public static final String DEFAULT_PLUGINURL =
"http://plugins.scm-manager.org/scm-plugin-backend/api/{version}/plugins?os={os}&arch={arch}&snapshot=false";
/** Default plugin url from version 1.0 */
public static final String OLD_PLUGINURL =
"http://plugins.scm-manager.org/plugins.xml.gz";
/** Path to the configuration file */
public static final String PATH =
"config".concat(File.separator).concat("config.xml");
/** the logger for ScmConfiguration */
private static final Logger logger =
LoggerFactory.getLogger(ScmConfiguration.class);
//~--- methods --------------------------------------------------------------
/**
* Register a {@link sonia.scm.ConfigChangedListener}
*
*
*
* @param listener
*/
@Override
public void addListener(ConfigChangedListener<ScmConfiguration> listener)
{
listeners.add(listener);
}
/**
* Register a {@link java.util.Collection} of {@link sonia.scm.ConfigChangedListener}
*
*
*
* @param listeners
*/
@Override
public void addListeners(
Collection<ConfigChangedListener<ScmConfiguration>> listeners)
{
listeners.addAll(listeners);
}
/**
* Calls the {@link sonia.scm.ConfigChangedListener#configChanged(Object)}
* method of all registered listeners.
*/
public void fireChangeEvent()
{
if (logger.isDebugEnabled())
{
logger.debug("fire config changed event");
}
for (ConfigChangedListener listener : listeners)
{
if (logger.isTraceEnabled())
{
logger.trace("call listener {}", listener.getClass().getName());
}
listener.configChanged(this);
}
}
/**
* Load all properties from another {@link ScmConfiguration} object.
*
*
*
* @param other
*/
public void load(ScmConfiguration other)
{
this.servername = other.servername;
this.dateFormat = other.dateFormat;
this.pluginUrl = other.pluginUrl;
this.anonymousAccessEnabled = other.anonymousAccessEnabled;
this.adminUsers = other.adminUsers;
this.adminGroups = other.adminGroups;
this.enableProxy = other.enableProxy;
this.proxyPort = other.proxyPort;
this.proxyServer = other.proxyServer;
this.proxyUser = other.proxyUser;
this.proxyPassword = other.proxyPassword;
+ this.proxyExcludes = other.proxyExcludes;
this.forceBaseUrl = other.forceBaseUrl;
this.baseUrl = other.baseUrl;
this.disableGroupingGrid = other.disableGroupingGrid;
this.enableRepositoryArchive = other.enableRepositoryArchive;
// deprecated fields
this.sslPort = other.sslPort;
this.enableSSL = other.enableSSL;
this.enablePortForward = other.enablePortForward;
this.forwardPort = other.forwardPort;
}
/**
* Unregister a listener object.
*
*
* @param listener
*/
@Override
public void removeListener(ConfigChangedListener listener)
{
listeners.remove(listener);
}
//~--- get methods ----------------------------------------------------------
/**
* Returns a set of admin group names.
*
*
* @return set of admin group names
*/
public Set<String> getAdminGroups()
{
return adminGroups;
}
/**
* Returns a set of admin user names.
*
*
* @return set of admin user names
*/
public Set<String> getAdminUsers()
{
return adminUsers;
}
/**
* Returns the complete base url of the scm-manager including the context path.
* For example http://localhost:8080/scm
*
* @since 1.5
* @return complete base url of the scm-manager
*/
public String getBaseUrl()
{
return baseUrl;
}
/**
* Returns the date format for the user interface. This format is a
* JavaScript date format, see
* {@link http://jacwright.com/projects/javascript/date_format}.
*
*
* @return JavaScript date format
*/
public String getDateFormat()
{
return dateFormat;
}
/**
* Returns the forwarding port.
*
*
* @return forwarding port
* @deprecated use {@link #getBaseUrl()}
*/
@Deprecated
public int getForwardPort()
{
return forwardPort;
}
/**
* Returns the url of the plugin repository. This url can contain placeholders.
* Explanation of the {placeholders}:
* <ul>
* <li><b>version</b> = SCM-Manager Version</li>
* <li><b>os</b> = Operation System</li>
* <li><b>arch</b> = Architecture</li>
* </ul>
* For example http://plugins.scm-manager.org/scm-plugin-backend/api/{version}/plugins?os={os}&arch={arch}&snapshot=false
*
* @return the complete plugin url.
*/
public String getPluginUrl()
{
return pluginUrl;
}
/**
* Returns a set of glob patterns for urls which should excluded from
* proxy settings.
*
*
* @return set of glob patterns
* @since 1.23
*/
public Set<String> getProxyExcludes()
{
if (proxyExcludes == null)
{
proxyExcludes = Sets.newHashSet();
}
return proxyExcludes;
}
/**
* Method description
*
*
* @return
* @since 1.7
*/
public String getProxyPassword()
{
return proxyPassword;
}
/**
* Returns the proxy port.
*
*
* @return proxy port
*/
public int getProxyPort()
{
return proxyPort;
}
/**
* Returns the servername or ip of the proxyserver.
*
*
* @return servername or ip of the proxyserver
*/
public String getProxyServer()
{
return proxyServer;
}
/**
* Method description
*
*
* @return
* @since 1.7
*/
public String getProxyUser()
{
return proxyUser;
}
/**
* Returns the servername of the SCM-Manager host.
*
*
* @return servername of the SCM-Manager host
* @deprecated use {@link #getBaseUrl()}
*/
public String getServername()
{
return servername;
}
/**
* Returns the ssl port.
*
*
* @return ssl port
* @deprecated use {@link #getBaseUrl()} and {@link #isForceBaseUrl()}
*/
@Deprecated
public int getSslPort()
{
return sslPort;
}
/**
* Returns true if the anonymous access to the SCM-Manager is enabled.
*
*
* @return true if the anonymous access to the SCM-Manager is enabled
*/
public boolean isAnonymousAccessEnabled()
{
return anonymousAccessEnabled;
}
/**
* Method description
*
* @since 1.9
* @return
*/
public boolean isDisableGroupingGrid()
{
return disableGroupingGrid;
}
/**
* Returns true if port forwarding is enabled.
*
*
* @return true if port forwarding is enabled
* @deprecated use {@link #getBaseUrl()}
*/
@Deprecated
public boolean isEnablePortForward()
{
return enablePortForward;
}
/**
* Returns true if proxy is enabled.
*
*
* @return true if proxy is enabled
*/
public boolean isEnableProxy()
{
return enableProxy;
}
/**
* Returns true if the repository archive is enabled.
*
*
* @return true if the repository archive is enabled
* @since 1.14
*/
public boolean isEnableRepositoryArchive()
{
return enableRepositoryArchive;
}
/**
* Returns true if ssl is enabled.
*
*
* @return true if ssl is enabled
* @deprecated use {@link #getBaseUrl()} and {@link #isForceBaseUrl()}
*/
@Deprecated
public boolean isEnableSSL()
{
return enableSSL;
}
/**
* Returns true if force base url is enabled.
*
* @since 1.5
* @return true if force base url is enabled
*/
public boolean isForceBaseUrl()
{
return forceBaseUrl;
}
//~--- set methods ----------------------------------------------------------
/**
* Method description
*
*
* @param adminGroups
*/
public void setAdminGroups(Set<String> adminGroups)
{
this.adminGroups = adminGroups;
}
/**
* Method description
*
*
* @param adminUsers
*/
public void setAdminUsers(Set<String> adminUsers)
{
this.adminUsers = adminUsers;
}
/**
* Method description
*
*
* @param anonymousAccessEnabled
*/
public void setAnonymousAccessEnabled(boolean anonymousAccessEnabled)
{
this.anonymousAccessEnabled = anonymousAccessEnabled;
}
/**
* Method description
*
*
* @param baseUrl
* @since 1.5
*/
public void setBaseUrl(String baseUrl)
{
this.baseUrl = baseUrl;
}
/**
* Method description
*
*
* @param dateFormat
*/
public void setDateFormat(String dateFormat)
{
this.dateFormat = dateFormat;
}
/**
* Method description
*
* @since 1.9
*
* @param disableGroupingGrid
*/
public void setDisableGroupingGrid(boolean disableGroupingGrid)
{
this.disableGroupingGrid = disableGroupingGrid;
}
/**
* Method description
*
*
* @param enablePortForward
* @deprecated use {@link #setBaseUrl(String)}
*/
@Deprecated
public void setEnablePortForward(boolean enablePortForward)
{
this.enablePortForward = enablePortForward;
}
/**
* Method description
*
*
* @param enableProxy
*/
public void setEnableProxy(boolean enableProxy)
{
this.enableProxy = enableProxy;
}
/**
* Enable or disable the repository archive. Default is disabled.
*
*
* @param enableRepositoryArchive true to disable the repository archive
* @since 1.14
*/
public void setEnableRepositoryArchive(boolean enableRepositoryArchive)
{
this.enableRepositoryArchive = enableRepositoryArchive;
}
/**
* Method description
*
*
* @param enableSSL
* @deprecated use {@link #setBaseUrl(String)} and {$link #setForceBaseUrl(boolean)}
*/
@Deprecated
public void setEnableSSL(boolean enableSSL)
{
this.enableSSL = enableSSL;
}
/**
* Method description
*
*
* @param forceBaseUrl
* @since 1.5
*/
public void setForceBaseUrl(boolean forceBaseUrl)
{
this.forceBaseUrl = forceBaseUrl;
}
/**
* Method description
*
*
* @param forwardPort
* @deprecated use {@link #setBaseUrl(String)}
*/
@Deprecated
public void setForwardPort(int forwardPort)
{
this.forwardPort = forwardPort;
}
/**
* Method description
*
*
* @param pluginUrl
*/
public void setPluginUrl(String pluginUrl)
{
this.pluginUrl = pluginUrl;
}
/**
* Set glob patterns for urls which are should be excluded from proxy
* settings.
*
*
* @param proxyExcludes glob patterns
* @since 1.23
*/
public void setProxyExcludes(Set<String> proxyExcludes)
{
this.proxyExcludes = proxyExcludes;
}
/**
* Method description
*
*
* @param proxyPassword
* @since 1.7
*/
public void setProxyPassword(String proxyPassword)
{
this.proxyPassword = proxyPassword;
}
/**
* Method description
*
*
* @param proxyPort
*/
public void setProxyPort(int proxyPort)
{
this.proxyPort = proxyPort;
}
/**
* Method description
*
*
* @param proxyServer
*/
public void setProxyServer(String proxyServer)
{
this.proxyServer = proxyServer;
}
/**
* Method description
*
*
* @param proxyUser
* @since 1.7
*/
public void setProxyUser(String proxyUser)
{
this.proxyUser = proxyUser;
}
/**
* Method description
*
*
* @param servername
* @deprecated use {@link #setBaseUrl(String)}
*/
public void setServername(String servername)
{
this.servername = servername;
}
/**
* Method description
*
*
* @param sslPort
* @deprecated use {@link #setBaseUrl(String)} and {@link #setForceBaseUrl(boolean)}
*/
@Deprecated
public void setSslPort(int sslPort)
{
this.sslPort = sslPort;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
@XmlElement(name = "admin-groups")
@XmlJavaTypeAdapter(XmlSetStringAdapter.class)
private Set<String> adminGroups;
/** Field description */
@XmlElement(name = "admin-users")
@XmlJavaTypeAdapter(XmlSetStringAdapter.class)
private Set<String> adminUsers;
/** Field description */
@XmlElement(name = "base-url")
private String baseUrl;
/** Field description */
private boolean enableProxy = false;
/** Field description */
@XmlElement(name = "force-base-url")
private boolean forceBaseUrl;
/** @deprecated use {@link #baseUrl} */
@Deprecated
private int forwardPort = 80;
/** Field description */
@XmlElement(name = "plugin-url")
private String pluginUrl = DEFAULT_PLUGINURL;
/** glob patterns for urls which are excluded from proxy */
@XmlElement(name = "proxy-excludes")
@XmlJavaTypeAdapter(XmlSetStringAdapter.class)
private Set<String> proxyExcludes;
/** Field description */
private String proxyPassword;
/** Field description */
private int proxyPort = 8080;
/** Field description */
private String proxyServer = "proxy.mydomain.com";
/** Field description */
private String proxyUser;
/** @deprecated use {@link #baseUrl} */
private String servername = "localhost";
/** @deprecated use {@link #baseUrl} and {@link #forceBaseUrl} */
@Deprecated
private boolean enableSSL = false;
/** @deprecated use {@link #baseUrl} */
@Deprecated
private boolean enablePortForward = false;
/** @deprecated use {@link #baseUrl} and {@link #forceBaseUrl} */
@Deprecated
private int sslPort = 8181;
/** Configuration change listeners */
@XmlTransient
private Set<ConfigChangedListener> listeners =
new HashSet<ConfigChangedListener>();
/** Field description */
private boolean enableRepositoryArchive = false;
/** Field description */
private boolean disableGroupingGrid = false;
/**
* JavaScript date format, see http://jacwright.com/projects/javascript/date_format
*/
private String dateFormat = DEFAULT_DATEFORMAT;
/** Field description */
private boolean anonymousAccessEnabled = false;
}
| true | true | public void load(ScmConfiguration other)
{
this.servername = other.servername;
this.dateFormat = other.dateFormat;
this.pluginUrl = other.pluginUrl;
this.anonymousAccessEnabled = other.anonymousAccessEnabled;
this.adminUsers = other.adminUsers;
this.adminGroups = other.adminGroups;
this.enableProxy = other.enableProxy;
this.proxyPort = other.proxyPort;
this.proxyServer = other.proxyServer;
this.proxyUser = other.proxyUser;
this.proxyPassword = other.proxyPassword;
this.forceBaseUrl = other.forceBaseUrl;
this.baseUrl = other.baseUrl;
this.disableGroupingGrid = other.disableGroupingGrid;
this.enableRepositoryArchive = other.enableRepositoryArchive;
// deprecated fields
this.sslPort = other.sslPort;
this.enableSSL = other.enableSSL;
this.enablePortForward = other.enablePortForward;
this.forwardPort = other.forwardPort;
}
| public void load(ScmConfiguration other)
{
this.servername = other.servername;
this.dateFormat = other.dateFormat;
this.pluginUrl = other.pluginUrl;
this.anonymousAccessEnabled = other.anonymousAccessEnabled;
this.adminUsers = other.adminUsers;
this.adminGroups = other.adminGroups;
this.enableProxy = other.enableProxy;
this.proxyPort = other.proxyPort;
this.proxyServer = other.proxyServer;
this.proxyUser = other.proxyUser;
this.proxyPassword = other.proxyPassword;
this.proxyExcludes = other.proxyExcludes;
this.forceBaseUrl = other.forceBaseUrl;
this.baseUrl = other.baseUrl;
this.disableGroupingGrid = other.disableGroupingGrid;
this.enableRepositoryArchive = other.enableRepositoryArchive;
// deprecated fields
this.sslPort = other.sslPort;
this.enableSSL = other.enableSSL;
this.enablePortForward = other.enablePortForward;
this.forwardPort = other.forwardPort;
}
|
diff --git a/src/com/qozix/mapview/viewmanagers/DownsampleManager.java b/src/com/qozix/mapview/viewmanagers/DownsampleManager.java
index fe54f58..d42e6a9 100644
--- a/src/com/qozix/mapview/viewmanagers/DownsampleManager.java
+++ b/src/com/qozix/mapview/viewmanagers/DownsampleManager.java
@@ -1,50 +1,50 @@
package com.qozix.mapview.viewmanagers;
import java.io.InputStream;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.View;
public class DownsampleManager {
private static final BitmapFactory.Options OPTIONS = new BitmapFactory.Options();
static {
OPTIONS.inPreferredConfig = Bitmap.Config.RGB_565;
}
private String lastFileName;
// NFI why this is required - caused by if ( fileName == null )
@SuppressWarnings("unused")
public void setDownsample( View view, String fileName ) {
- if ( fileName.equals( lastFileName )) {
+ if ( fileName != null && fileName.equals( lastFileName )) {
return;
}
lastFileName = fileName;
if ( fileName == null ) {
view.setBackgroundDrawable( null );
return;
}
Context context = view.getContext();
AssetManager assets = context.getAssets();
try {
InputStream input = assets.open( fileName );
if ( input != null ) {
try {
Bitmap bitmap = BitmapFactory.decodeStream( input, null, OPTIONS );
BitmapDrawable bitmapDrawable = new BitmapDrawable( bitmap );
view.setBackgroundDrawable( bitmapDrawable );
} catch( Exception e ) {
}
}
} catch (Exception e ) {
}
}
}
| true | true | public void setDownsample( View view, String fileName ) {
if ( fileName.equals( lastFileName )) {
return;
}
lastFileName = fileName;
if ( fileName == null ) {
view.setBackgroundDrawable( null );
return;
}
Context context = view.getContext();
AssetManager assets = context.getAssets();
try {
InputStream input = assets.open( fileName );
if ( input != null ) {
try {
Bitmap bitmap = BitmapFactory.decodeStream( input, null, OPTIONS );
BitmapDrawable bitmapDrawable = new BitmapDrawable( bitmap );
view.setBackgroundDrawable( bitmapDrawable );
} catch( Exception e ) {
}
}
} catch (Exception e ) {
}
}
| public void setDownsample( View view, String fileName ) {
if ( fileName != null && fileName.equals( lastFileName )) {
return;
}
lastFileName = fileName;
if ( fileName == null ) {
view.setBackgroundDrawable( null );
return;
}
Context context = view.getContext();
AssetManager assets = context.getAssets();
try {
InputStream input = assets.open( fileName );
if ( input != null ) {
try {
Bitmap bitmap = BitmapFactory.decodeStream( input, null, OPTIONS );
BitmapDrawable bitmapDrawable = new BitmapDrawable( bitmap );
view.setBackgroundDrawable( bitmapDrawable );
} catch( Exception e ) {
}
}
} catch (Exception e ) {
}
}
|
diff --git a/luntbuild/src/com/luntsys/luntbuild/notifiers/TemplatedNotifier.java b/luntbuild/src/com/luntsys/luntbuild/notifiers/TemplatedNotifier.java
index 47e210f..46bd4b0 100644
--- a/luntbuild/src/com/luntsys/luntbuild/notifiers/TemplatedNotifier.java
+++ b/luntbuild/src/com/luntsys/luntbuild/notifiers/TemplatedNotifier.java
@@ -1,529 +1,528 @@
package com.luntsys.luntbuild.notifiers;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import java.util.StringTokenizer;
import ognl.OgnlException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import com.luntsys.luntbuild.BuildGenerator;
import com.luntsys.luntbuild.db.Build;
import com.luntsys.luntbuild.db.Schedule;
import com.luntsys.luntbuild.facades.Constants;
import com.luntsys.luntbuild.reports.Report;
import com.luntsys.luntbuild.scrapers.MSVSScraper;
import com.luntsys.luntbuild.utility.Luntbuild;
/**
* Encapsulates the logic for processing templates within Luntbuild.
*
* @author Dustin Hunter
* @author Jason Archer
*/
public abstract class TemplatedNotifier extends Notifier implements ReferenceInsertionEventHandler {
/** Logger */
protected Log logger = null;
/** Template dir */
public String templateDir = null;
/** Template sub dir */
public String subDir = null;
/** Build template file */
public String templateBuildFile = null;
/** Schedule template file */
public String templateScheduleFile = null;
private Object ognlRoot = null;
private MSVSScraper visualStudioScraper = new MSVSScraper();
/** Base template directory */
public static final String TEMPLATE_BASE_DIR = Luntbuild.installDir + File.separator + "templates";
private static final String QUOTE_FILE = "quotes.txt";
private static final String TEMPLATE_DEF_FILE = "set-template.txt";
private static final String DEFAULT_TEMPLATE_BUILD = "simple-build.vm";
private static final String DEFAULT_TEMPLATE_SCHEDULE = "simple-schedule.vm";
/**
* Creates a templated notifier.
*
* @param logClass the log class
* @param subdir the template subdir (in installdir/templates)
*/
public TemplatedNotifier(Class logClass, String subdir) {
logger = LogFactory.getLog(logClass);
templateDir = TEMPLATE_BASE_DIR;
subDir = subdir;
setTemplateFiles();
}
/**
* Sets the template files from the default properties.
*/
private void setTemplateFiles() {
setTemplateFiles("");
}
/**
* Sets the template files from the specified property. If the property does not exist, the default
* properties will be used. If the default properties do not exist, the default file names will be used.
*
* @param templatePropertyName the property name to use
*/
private void setTemplateFiles(String templatePropertyName) {
File f = new File(templateDir + File.separator + subDir + File.separator + TEMPLATE_DEF_FILE);
if (!f.exists()) {
logger.error("Unable to find template definition file " + f.getPath());
templateBuildFile = subDir + "/" + DEFAULT_TEMPLATE_BUILD;
templateScheduleFile = subDir + "/" + DEFAULT_TEMPLATE_SCHEDULE;
return;
}
Properties props = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream(f);
props.load(in);
} catch (IOException e) {
logger.error("Unable to read template definition file " + f.getPath());
templateBuildFile = subDir + "/" + DEFAULT_TEMPLATE_BUILD;
templateScheduleFile = subDir + "/" + DEFAULT_TEMPLATE_SCHEDULE;
return;
} finally {
if (in != null) try { in.close(); } catch (Exception e) {/*Ignore*/}
}
templateBuildFile = props.getProperty(templatePropertyName + "_buildTemplate");
templateScheduleFile = props.getProperty(templatePropertyName + "_scheduleTemplate");
if (templateBuildFile == null) templateBuildFile = props.getProperty("buildTemplate");
if (templateScheduleFile == null) templateScheduleFile = props.getProperty("scheduleTemplate");
if (templateBuildFile == null) templateBuildFile = DEFAULT_TEMPLATE_BUILD;
if (templateScheduleFile == null) templateScheduleFile = DEFAULT_TEMPLATE_SCHEDULE;
templateBuildFile = subDir + "/" + templateBuildFile;
templateScheduleFile = subDir + "/" + templateScheduleFile;
}
/**
* Initializes Velocity and uses the specified property for template files.
*
* @param templatePropertyName the property name to use
* @throws Exception from {@link Velocity#init(Properties)}
*/
private void init(String templatePropertyName) throws Exception {
Properties props = new Properties();
props.put("file.resource.loader.path", templateDir);
props.put("runtime.log", "velocity.log");
Velocity.init(props);
setTemplateFiles(templatePropertyName);
}
/**
* Processes the template for a build notification.
*
* @param build the build
* @param ctx a Velocity context
* @throws Exception from {@link Velocity#getTemplate(String)}
*/
private String processTemplate(Build build, VelocityContext ctx) throws Exception {
return processTemplate(Velocity.getTemplate(templateBuildFile),
build, ctx);
}
/**
* Processes the template for a schedule notification.
*
* @param schedule the schedule
* @param ctx a Velocity context
* @throws Exception from {@link Velocity#getTemplate(String)}
*/
private String processTemplate(Schedule schedule, VelocityContext ctx) throws Exception {
return processTemplate(Velocity.getTemplate(templateScheduleFile), schedule, ctx);
}
/**
* Processes the template for a build notification.
*
* @param template the template
* @param build the build
* @param ctx a Velocity context
* @throws Exception from {@link Velocity#init()}
* @throws Exception from {@link #createContext(Build, VelocityContext)}
* @throws Exception from {@link Template#merge(org.apache.velocity.context.Context, Writer)}
*/
private String processTemplate(Template template, Build build, VelocityContext ctx) throws Exception {
Velocity.init();
VelocityContext context = createContext(build, ctx);
EventCartridge ec = new EventCartridge();
ec.addEventHandler(this);
ec.attachToContext(context);
ognlRoot = build;
// Process the template
StringWriter writer = null;
try {
writer = new StringWriter();
if (template != null)
template.merge(context, writer);
return writer.toString();
} finally {
writer.close();
}
}
/**
* Processes the template for a schedule notification.
*
* @param template the template
* @param schedule the schedule
* @param ctx a Velocity context
* @throws Exception from {@link Velocity#init()}
* @throws Exception from {@link #createContext(Schedule, VelocityContext)}
* @throws Exception from {@link Template#merge(org.apache.velocity.context.Context, Writer)}
*/
private String processTemplate(Template template, Schedule schedule, VelocityContext ctx) throws Exception {
Velocity.init();
VelocityContext context = createContext(schedule, ctx);
EventCartridge ec = new EventCartridge();
ec.addEventHandler(this);
ec.attachToContext(context);
ognlRoot = schedule;
// Process the template
StringWriter writer = null;
try {
writer = new StringWriter();
if (template != null)
template.merge(context, writer);
return writer.toString();
} finally {
writer.close();
}
}
/**
* @inheritDoc
*/
public Object referenceInsert(String reference, Object value) {
if (value != null) return value;
try {
return Luntbuild.evaluateExpression(ognlRoot, reference);
} catch (OgnlException ex) {
return value;
}
}
/**
* Populates the context with the variables which are exposed to the build template.
*
* @param build the build
* @param ctx the Velocity context
* @throws Exception from {@link #extractRootUrl(String)}
*/
private VelocityContext createContext(Build build, VelocityContext ctx) throws Exception {
VelocityContext context = new VelocityContext(ctx);
// System info
context.put("luntbuild_webroot", extractRootUrl(build.getUrl()));
context.put("luntbuild_servlet_url", Luntbuild.getServletUrl());
context.put("luntbuild_systemlog_url", Luntbuild.getSystemLogUrl());
// Project Info
context.put("build_project", build.getSchedule().getProject().getName());
context.put("build_project_desc", build.getSchedule().getProject().getDescription());
// Schedule Info
context.put("build_schedule", build.getSchedule().getName());
context.put("build_schedule_desc", build.getSchedule().getDescription());
context.put("build_schedule_url", build.getSchedule().getUrl());
context.put("build_schedule_status", Constants.getScheduleStatusText(build.getSchedule().getStatus()));
context.put("build_schedule_status_date",
Luntbuild.DATE_DISPLAY_FORMAT.format(build.getSchedule().getStatusDate()));
// Build Info
context.put("build_url", build.getUrl());
context.put("build_version", build.getVersion());
context.put("build_status", Constants.getBuildStatusText(build.getStatus()));
context.put("build_isSuccess", new Boolean(build.getStatus() == Constants.BUILD_STATUS_SUCCESS));
context.put("build_isFailure", new Boolean(build.getStatus() == Constants.BUILD_STATUS_FAILED));
context.put("build_artifactsdir", build.getArtifactsDir());
context.put("build_publishdir", build.getPublishDir());
context.put("build_type", Constants.getBuildTypeText(build.getBuildType()));
context.put("build_labelstrategy", Constants.getLabelStrategyText(build.getLabelStrategy()));
context.put("build_changelist", build.getChangelist());
// Time Info
context.put("build_start", Luntbuild.DATE_DISPLAY_FORMAT.format(build.getStartDate()));
context.put("build_end", Luntbuild.DATE_DISPLAY_FORMAT.format(build.getEndDate()));
long diffSec = (build.getEndDate().getTime()-build.getStartDate().getTime())/1000;
context.put("build_duration", "" + diffSec + " seconds");
// Log info
context.put("build_revisionlog_url", build.getRevisionLogUrl());
context.put("build_revisionlog_text", readFile(build.getPublishDir()
+ File.separator + BuildGenerator.REVISION_LOG));
context.put("build_buildlog_url", build.getBuildLogUrl());
String buildText = readFile(build.getPublishDir() + File.separator + BuildGenerator.BUILD_LOG);
context.put("build_buildlog_text", buildText);
// Reports
Enumeration reports = Luntbuild.reports.keys();
while (reports.hasMoreElements()) {
String report_name = (String) reports.nextElement();
- context.put("build_" + report_name + "_reporturl", build.getPublishDir()
- + File.separator + ((Report)Luntbuild.reports.get(report_name)).getReportUrl(build.getPublishDir()));
+ context.put("build_" + report_name + "_reporturl", ((Report)Luntbuild.reports.get(report_name)).getReportUrl(build.getPublishDir()));
}
visualStudioScraper.scrape(buildText, build, context);
// Just for fun
try {
context.put("build_randomquote", getRandomQuote(this.templateDir));
} catch (Exception ex) {
// If we fail, this should not affect the rest of the message
}
return context;
}
/**
* Populates the context with the variables which are exposed to the schedule template.
*
* @param schedule the schedule
* @param ctx the Velocity context
* @throws Exception from {@link #extractRootUrl(String)}
*/
private VelocityContext createContext(Schedule schedule, VelocityContext ctx) throws Exception {
VelocityContext context = new VelocityContext(ctx);
// System info
context.put("luntbuild_webroot", extractRootUrl(schedule.getUrl()));
context.put("luntbuild_servlet_url", Luntbuild.getServletUrl());
context.put("luntbuild_systemlog_url", Luntbuild.getSystemLogUrl());
// Project Info
context.put("schedule_project", schedule.getProject().getName());
context.put("schedule_project_desc", schedule.getProject().getDescription());
// Schedule Info
context.put("schedule_name", schedule.getName());
context.put("schedule_desc", schedule.getDescription());
context.put("schedule_url", schedule.getUrl());
context.put("schedule_status", Constants.getScheduleStatusText(schedule.getStatus()));
context.put("schedule_status_date",
Luntbuild.DATE_DISPLAY_FORMAT.format(schedule.getStatusDate()));
context.put("schedule_publishdir", schedule.getPublishDir());
context.put("schedule_type", Constants.getBuildTypeText(schedule.getBuildType()));
context.put("schedule_labelstrategy", Constants.getLabelStrategyText(schedule.getLabelStrategy()));
return context;
}
/**
* Creates a message title for a schedule notification.
*
* @param schedule the schedule
* @return the message title
*/
protected String constructNotificationTitle(Schedule schedule) {
String scheduleDesc = schedule.getProject().getName() + "/" + schedule.getName();
return "[luntbuild] schedule \"" + scheduleDesc + "\" " +
com.luntsys.luntbuild.facades.Constants.getScheduleStatusText(schedule.getStatus());
}
/**
* Creates a message body for a schedule notification.
*
* @param schedule the schedule
* @return the message body
*/
protected String constructNotificationBody(Schedule schedule) {
return constructNotificationBody(schedule, null);
}
/**
* Creates a message title for a build notification.
*
* @param build the build
* @return the message title
*/
protected String constructNotificationTitle(Build build) {
String buildDesc = build.getSchedule().getProject().getName() +
"/" + build.getSchedule().getName() + "/" + build.getVersion();
return "[luntbuild] build of \"" + buildDesc +
"\" " + com.luntsys.luntbuild.facades.Constants.getBuildStatusText(build.getStatus());
}
/**
* Creates a message body for a build notification for recent checkin users.
*
* @param build the build
* @return the message body
*/
protected String constructNotificationBody4CheckinUsers(Build build) {
VelocityContext context = new VelocityContext();
context.put("build_user_msg",
"You have received this note because you've made checkins in the source repository recently.");
return constructNotificationBody(build, context);
}
/**
* Creates a message body for a build notification for subscribed users.
*
* @param build the build
* @return the message body
*/
protected String constructNotificationBody(Build build) {
VelocityContext context = new VelocityContext();
context.put("build_user_msg",
"You have received this email because you asked to be notified.");
return constructNotificationBody(build, context);
}
/**
* Creates a message body for a build notification.
*
* @param build the build
* @param ctx the Velocity context
* @return the message body
*/
private String constructNotificationBody(Build build, VelocityContext ctx) {
try {
init(build.getSchedule().getProject().getName().replaceAll(" ","_") + "_" + build.getSchedule().getName().replaceAll(" ","_"));
return processTemplate(build, ctx);
}
catch (ResourceNotFoundException rnfe) {
logger.error("Could not load template file: " + templateBuildFile +
"\nTemplateDir = " + templateDir, rnfe);
return "Could not load template file: " + templateBuildFile + "\nTemplateDir = " +
templateDir;
}
catch (ParseErrorException pee) {
logger.error("Unable to parse template file: " + templateBuildFile +
"\nTemplateDir = " + templateDir, pee);
return "Unable to parse template file: " + templateBuildFile + "\nTemplateDir = " +
templateDir;
}
catch(Exception ex) {
// Wrap in a runtime exception and throw it up the stack
logger.error("Failed to process template", ex);
throw new RuntimeException(ex);
}
}
/**
* Creates a message body for a schedule notification.
*
* @param schedule the schedule
* @param ctx the Velocity context
* @return the message body
*/
private String constructNotificationBody(Schedule schedule, VelocityContext ctx) {
try {
init(schedule.getProject().getName().replaceAll(" ","_") + "_" + schedule.getName().replaceAll(" ","_"));
return processTemplate(schedule, ctx);
}
catch (ResourceNotFoundException rnfe) {
logger.error("Could not load template file: " + templateScheduleFile +
"\nTemplateDir = " + templateDir, rnfe);
return "Could not load template file: " + templateScheduleFile + "\nTemplateDir = " +
templateDir;
}
catch (ParseErrorException pee) {
logger.error("Unable to parse template file: " + templateScheduleFile +
"\nTemplateDir = " + templateDir, pee);
return "Unable to parse template file: " + templateScheduleFile + "\nTemplateDir = " +
templateDir;
}
catch(Exception ex) {
// Wrap in a runtime exception and throw it up the stack
logger.error("Failed to process template", ex);
throw new RuntimeException(ex);
}
}
/**
* Gets the contents of a file.
*
* @param filename the name of the file
* @return the contents of the file
* @throws Exception if the file cannot be read
*/
private static final String readFile(String filename) throws Exception {
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
File file = new File(filename);
if (!file.exists())
throw new Exception("Cannot load system file: " + filename +
"\nFull Path = " + file.getAbsolutePath());
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
StringBuffer sbuf = new StringBuffer();
int readin = 0;
byte[] buf = new byte[1024];
while ((readin = bis.read(buf)) > 0) {
sbuf.append(new String(buf, 0, readin));
}
return sbuf.toString();
}
finally {
if (bis != null) bis.close();
if (fis != null) fis.close();
}
}
/**
* Determines the host name and port of the server.
*
* @param text the URL of the server
* @return the root of the URL with only the protocol, host name and port
*/
private static final String extractRootUrl(String text) throws Exception {
URL url = new URL(text);
return url.getProtocol() + "://" + url.getHost() + ":" + url.getPort();
}
/**
* Gets a random quote from the quote file in the specified directory.
*
* @param templateDir the template directory
* @return a random quote, or <code>null</code> if the quote file could not be found
* @throws Exception if the quote file cannot be read
*/
private static final String getRandomQuote(String templateDir) throws Exception {
try {
String quotes = readFile(templateDir + "/" + QUOTE_FILE);
StringTokenizer tokenizer = new StringTokenizer(quotes, "\r");
int tokens = tokenizer.countTokens();
int index = (int)(Math.random() * tokens);
while (--index > 1) tokenizer.nextToken();
return tokenizer.nextToken();
}
catch(FileNotFoundException ex) {
// If the files not there, the just ignore it
return null;
}
}
}
| true | true | private VelocityContext createContext(Build build, VelocityContext ctx) throws Exception {
VelocityContext context = new VelocityContext(ctx);
// System info
context.put("luntbuild_webroot", extractRootUrl(build.getUrl()));
context.put("luntbuild_servlet_url", Luntbuild.getServletUrl());
context.put("luntbuild_systemlog_url", Luntbuild.getSystemLogUrl());
// Project Info
context.put("build_project", build.getSchedule().getProject().getName());
context.put("build_project_desc", build.getSchedule().getProject().getDescription());
// Schedule Info
context.put("build_schedule", build.getSchedule().getName());
context.put("build_schedule_desc", build.getSchedule().getDescription());
context.put("build_schedule_url", build.getSchedule().getUrl());
context.put("build_schedule_status", Constants.getScheduleStatusText(build.getSchedule().getStatus()));
context.put("build_schedule_status_date",
Luntbuild.DATE_DISPLAY_FORMAT.format(build.getSchedule().getStatusDate()));
// Build Info
context.put("build_url", build.getUrl());
context.put("build_version", build.getVersion());
context.put("build_status", Constants.getBuildStatusText(build.getStatus()));
context.put("build_isSuccess", new Boolean(build.getStatus() == Constants.BUILD_STATUS_SUCCESS));
context.put("build_isFailure", new Boolean(build.getStatus() == Constants.BUILD_STATUS_FAILED));
context.put("build_artifactsdir", build.getArtifactsDir());
context.put("build_publishdir", build.getPublishDir());
context.put("build_type", Constants.getBuildTypeText(build.getBuildType()));
context.put("build_labelstrategy", Constants.getLabelStrategyText(build.getLabelStrategy()));
context.put("build_changelist", build.getChangelist());
// Time Info
context.put("build_start", Luntbuild.DATE_DISPLAY_FORMAT.format(build.getStartDate()));
context.put("build_end", Luntbuild.DATE_DISPLAY_FORMAT.format(build.getEndDate()));
long diffSec = (build.getEndDate().getTime()-build.getStartDate().getTime())/1000;
context.put("build_duration", "" + diffSec + " seconds");
// Log info
context.put("build_revisionlog_url", build.getRevisionLogUrl());
context.put("build_revisionlog_text", readFile(build.getPublishDir()
+ File.separator + BuildGenerator.REVISION_LOG));
context.put("build_buildlog_url", build.getBuildLogUrl());
String buildText = readFile(build.getPublishDir() + File.separator + BuildGenerator.BUILD_LOG);
context.put("build_buildlog_text", buildText);
// Reports
Enumeration reports = Luntbuild.reports.keys();
while (reports.hasMoreElements()) {
String report_name = (String) reports.nextElement();
context.put("build_" + report_name + "_reporturl", build.getPublishDir()
+ File.separator + ((Report)Luntbuild.reports.get(report_name)).getReportUrl(build.getPublishDir()));
}
visualStudioScraper.scrape(buildText, build, context);
// Just for fun
try {
context.put("build_randomquote", getRandomQuote(this.templateDir));
} catch (Exception ex) {
// If we fail, this should not affect the rest of the message
}
return context;
}
| private VelocityContext createContext(Build build, VelocityContext ctx) throws Exception {
VelocityContext context = new VelocityContext(ctx);
// System info
context.put("luntbuild_webroot", extractRootUrl(build.getUrl()));
context.put("luntbuild_servlet_url", Luntbuild.getServletUrl());
context.put("luntbuild_systemlog_url", Luntbuild.getSystemLogUrl());
// Project Info
context.put("build_project", build.getSchedule().getProject().getName());
context.put("build_project_desc", build.getSchedule().getProject().getDescription());
// Schedule Info
context.put("build_schedule", build.getSchedule().getName());
context.put("build_schedule_desc", build.getSchedule().getDescription());
context.put("build_schedule_url", build.getSchedule().getUrl());
context.put("build_schedule_status", Constants.getScheduleStatusText(build.getSchedule().getStatus()));
context.put("build_schedule_status_date",
Luntbuild.DATE_DISPLAY_FORMAT.format(build.getSchedule().getStatusDate()));
// Build Info
context.put("build_url", build.getUrl());
context.put("build_version", build.getVersion());
context.put("build_status", Constants.getBuildStatusText(build.getStatus()));
context.put("build_isSuccess", new Boolean(build.getStatus() == Constants.BUILD_STATUS_SUCCESS));
context.put("build_isFailure", new Boolean(build.getStatus() == Constants.BUILD_STATUS_FAILED));
context.put("build_artifactsdir", build.getArtifactsDir());
context.put("build_publishdir", build.getPublishDir());
context.put("build_type", Constants.getBuildTypeText(build.getBuildType()));
context.put("build_labelstrategy", Constants.getLabelStrategyText(build.getLabelStrategy()));
context.put("build_changelist", build.getChangelist());
// Time Info
context.put("build_start", Luntbuild.DATE_DISPLAY_FORMAT.format(build.getStartDate()));
context.put("build_end", Luntbuild.DATE_DISPLAY_FORMAT.format(build.getEndDate()));
long diffSec = (build.getEndDate().getTime()-build.getStartDate().getTime())/1000;
context.put("build_duration", "" + diffSec + " seconds");
// Log info
context.put("build_revisionlog_url", build.getRevisionLogUrl());
context.put("build_revisionlog_text", readFile(build.getPublishDir()
+ File.separator + BuildGenerator.REVISION_LOG));
context.put("build_buildlog_url", build.getBuildLogUrl());
String buildText = readFile(build.getPublishDir() + File.separator + BuildGenerator.BUILD_LOG);
context.put("build_buildlog_text", buildText);
// Reports
Enumeration reports = Luntbuild.reports.keys();
while (reports.hasMoreElements()) {
String report_name = (String) reports.nextElement();
context.put("build_" + report_name + "_reporturl", ((Report)Luntbuild.reports.get(report_name)).getReportUrl(build.getPublishDir()));
}
visualStudioScraper.scrape(buildText, build, context);
// Just for fun
try {
context.put("build_randomquote", getRandomQuote(this.templateDir));
} catch (Exception ex) {
// If we fail, this should not affect the rest of the message
}
return context;
}
|
diff --git a/src/net/enkun/mods/CompactLaser/CompactLaser.java b/src/net/enkun/mods/CompactLaser/CompactLaser.java
index fa73729..c2e55de 100644
--- a/src/net/enkun/mods/CompactLaser/CompactLaser.java
+++ b/src/net/enkun/mods/CompactLaser/CompactLaser.java
@@ -1,74 +1,74 @@
/**
* BuildCraft is open-source. It is distributed under the terms of the
* BuildCraft Open Source License. It grants rights to read, modify, compile
* or run the code. It does *NOT* grant the right to redistribute this software
* or its modifications in any form, binary or source, except if expressively
* granted by the copyright holder.
*/
package net.enkun.mods.CompactLaser;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.Property;
import buildcraft.BuildCraftCore;
import buildcraft.BuildCraftSilicon;
import buildcraft.BuildCraftTransport;
import buildcraft.api.bptblocks.BptBlockInventory;
import buildcraft.api.bptblocks.BptBlockRotateMeta;
import buildcraft.api.recipes.AssemblyRecipe;
import buildcraft.core.DefaultProps;
import buildcraft.core.Version;
import buildcraft.core.proxy.CoreProxy;
import net.enkun.mods.CompactLaser.BlockCompactLaser;
import net.enkun.mods.CompactLaser.CommonProxy;
import net.enkun.mods.CompactLaser.TileLaser;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
@Mod(name = "CompactLaser", version = "0.2", useMetadata = false, modid = "CompactLaser", dependencies = "required-after:BuildCraft|Core;required-after:BuildCraft|Silicon;required-after:BuildCraft|Transport")
@NetworkMod(channels = { "CompactLaser" }, packetHandler = PacketHandler.class, clientSideRequired = true, serverSideRequired = true)
public class CompactLaser {
public static BlockCompactLaser CompactLaserBlock;
public int CompactLaserBlockId;
@Instance("CompactLaser")
public static CompactLaser instance;
@Init
public void load(FMLInitializationEvent evt) {
CoreProxy.proxy.registerTileEntity(TileLaser.class, "net.enkun.mods.CompactLaser.TileLaser");
new BptBlockRotateMeta(CompactLaserBlock.blockID, new int[] { 2, 5, 3, 4 }, true);
CommonProxy.proxy.registerRenderers();
CoreProxy.proxy.addCraftingRecipe(new ItemStack(CompactLaserBlock),
new Object[] { "LLL", "L L", "LLL", Character.valueOf('L'), BuildCraftSilicon.laserBlock });
}
@PreInit
public void initialize(FMLPreInitializationEvent evt) {
Configuration cfg = new Configuration(evt.getSuggestedConfigurationFile());
cfg.load();
- Property PropCompactLaserBlock = cfg.get("", "CompactLaser", 1300);
+ Property PropCompactLaserBlock = cfg.get(Configuration.CATEGORY_BLOCK, "CompactLaser", 1300);
CompactLaserBlockId = PropCompactLaserBlock.getInt();
CompactLaserBlock = new BlockCompactLaser(CompactLaserBlockId);
CompactLaserBlock.setBlockName("CompactLaser");
LanguageRegistry.addName(CompactLaserBlock, "Compact Laser");
GameRegistry.registerBlock(CompactLaserBlock, "CompactLaser");
}
}
| true | true | public void initialize(FMLPreInitializationEvent evt) {
Configuration cfg = new Configuration(evt.getSuggestedConfigurationFile());
cfg.load();
Property PropCompactLaserBlock = cfg.get("", "CompactLaser", 1300);
CompactLaserBlockId = PropCompactLaserBlock.getInt();
CompactLaserBlock = new BlockCompactLaser(CompactLaserBlockId);
CompactLaserBlock.setBlockName("CompactLaser");
LanguageRegistry.addName(CompactLaserBlock, "Compact Laser");
GameRegistry.registerBlock(CompactLaserBlock, "CompactLaser");
}
| public void initialize(FMLPreInitializationEvent evt) {
Configuration cfg = new Configuration(evt.getSuggestedConfigurationFile());
cfg.load();
Property PropCompactLaserBlock = cfg.get(Configuration.CATEGORY_BLOCK, "CompactLaser", 1300);
CompactLaserBlockId = PropCompactLaserBlock.getInt();
CompactLaserBlock = new BlockCompactLaser(CompactLaserBlockId);
CompactLaserBlock.setBlockName("CompactLaser");
LanguageRegistry.addName(CompactLaserBlock, "Compact Laser");
GameRegistry.registerBlock(CompactLaserBlock, "CompactLaser");
}
|
diff --git a/src/raven/math/RandUtils.java b/src/raven/math/RandUtils.java
index da9a0a6..0700f03 100644
--- a/src/raven/math/RandUtils.java
+++ b/src/raven/math/RandUtils.java
@@ -1,25 +1,24 @@
/**
*
*/
package raven.math;
import java.util.Random;
/**
* @author chester
*
*/
public class RandUtils {
/**
* Generates a random double from the start to the end provided, exclusive.
* @param start
* @param end
* @return
*/
public static double RandInRange(double start, double end)
{
- Random rand = new Random(System.nanoTime());
- return rand.nextDouble() * end;
+ return Math.random() * (end - start) + start;
}
}
| true | true | public static double RandInRange(double start, double end)
{
Random rand = new Random(System.nanoTime());
return rand.nextDouble() * end;
}
| public static double RandInRange(double start, double end)
{
return Math.random() * (end - start) + start;
}
|
diff --git a/EscapeIR-Android/src/fr/umlv/escape/world/CollisionMonitor.java b/EscapeIR-Android/src/fr/umlv/escape/world/CollisionMonitor.java
index 21119de..34ab650 100644
--- a/EscapeIR-Android/src/fr/umlv/escape/world/CollisionMonitor.java
+++ b/EscapeIR-Android/src/fr/umlv/escape/world/CollisionMonitor.java
@@ -1,178 +1,176 @@
package fr.umlv.escape.world;
import java.util.ArrayList;
import java.util.Random;
import org.jbox2d.callbacks.ContactImpulse;
import org.jbox2d.callbacks.ContactListener;
import org.jbox2d.collision.Manifold;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.contacts.Contact;
import fr.umlv.escape.bonus.Bonus;
import fr.umlv.escape.bonus.BonusFactory;
import fr.umlv.escape.front.BattleField;
import fr.umlv.escape.game.Game;
import fr.umlv.escape.game.Player;
import fr.umlv.escape.ship.Ship;
import fr.umlv.escape.weapon.Bullet;
import fr.umlv.escape.weapon.ListWeapon;
/**
* This class manage what should happen when body collide. It is a contact listener of the {@link EscapeWorld}
* @implements Conctlistener
*/
public class CollisionMonitor implements ContactListener{
private final ArrayList<Body> elemToDelete;
private boolean createBonus;
private final Random random = new Random(0);
private final static int PROBABILITY_NEW_BONUS = 20;
private final BonusFactory bonusFactory;
private final BattleField battleField;
/**
* Constructor.
*/
public CollisionMonitor(BattleField battleField){
EscapeWorld.getTheWorld().setContactListener(this);
this.elemToDelete=new ArrayList<Body>();
this.bonusFactory = new BonusFactory(battleField);
this.battleField = battleField;
}
/**
* As no operations can be done on bodies while there are colliding some operations are postponed
* and are done in this method which have to be called just after a step.
*/
public void performPostStepCollision(){
for(int i=0; i<elemToDelete.size();++i){
Body body = elemToDelete.get(i);
EscapeWorld.getTheWorld().setActive(body, false);
EscapeWorld.getTheWorld().destroyBody(body);
if(this.createBonus){
Bonus bonus=bonusFactory.createBonus("weapon_reloader", (int)((body.getPosition().x*EscapeWorld.SCALE)), (int)((body.getPosition().y*EscapeWorld.SCALE)), (int)(Math.random()*(4-1))+1);
bonus.move();
battleField.addBonus(bonus);
this.createBonus=false;
}
}
elemToDelete.clear();
}
@Override
public void beginContact(Contact arg0) {
Player player=Game.getTheGame().getPlayer1();
Ship shipPlayer=player.getShip();
Body body;
Body body2;
Ship enemy;
Bullet bullet;
Bonus bonus;
//if one of the two body that collided is the body of the player's ship
if((arg0.getFixtureA().getBody()==shipPlayer.getBody())||
(arg0.getFixtureB().getBody()==shipPlayer.getBody())){
//get the other body that collided
if(arg0.getFixtureA().getBody()==shipPlayer.getBody()){
body=arg0.getFixtureB().getBody();
} else {
body=arg0.getFixtureA().getBody();
}
//if the second body that collided is an enemy
if((enemy=battleField.getShip(body))!=null){
shipPlayer.takeDamage(10);
enemy.takeDamage(20);
if(!enemy.isAlive()){
impactEnemyDead(enemy,player);
elemToDelete.add(body);
}
} //else if the second body that collided is a bullet
else if((bullet=battleField.getBullet(body))!=null){
shipPlayer.takeDamage(bullet.getDamage());
elemToDelete.add(body);
} //else if the second body that collided is a bonus
else if((bonus=battleField.getBonus(body))!=null){
ListWeapon playerWeapons = shipPlayer.getListWeapon();
playerWeapons.addWeapon(bonus.getType(), bonus.getQuantity());
elemToDelete.add(body);
- } else {
- System.out.println("WALLLLLLLLLLLLLLLLLLLLLLLLLLL");
}
} else {
body=arg0.getFixtureA().getBody();
body2=arg0.getFixtureB().getBody();
if((enemy=battleField.getShip(body))!=null){
if((bullet=battleField.getBullet(body2))==null){
throw new AssertionError();
}
enemy.takeDamage(bullet.getDamage());
if(bullet == player.getShip().getCurrentWeapon().getLoadingBullet()){
player.getShip().getCurrentWeapon().setLoadingBullet(null);
}
if(!enemy.isAlive()){
elemToDelete.add(body);
impactEnemyDead(enemy,player);
}
- if((!bullet.getNameLvl().equals("FireBall_3")) && (!bullet.getName().equals("XRay"))){
+ if((!bullet.getNameLvl().equals("fireball_3")) && (!bullet.getName().equals("xray"))){
elemToDelete.add(body2);
}
} else {
bullet=battleField.getBullet(body);
enemy=battleField.getShip(body2);
if((bullet==null)||(enemy==null)){
System.out.println(body.m_fixtureList.m_filter.categoryBits);
System.out.println(body.m_fixtureList.m_filter.maskBits);
System.out.println(body.getPosition().x*50+" - "+body.getPosition().y);
System.out.println(body2.m_fixtureList.m_filter.categoryBits);
System.out.println(body2.m_fixtureList.m_filter.maskBits);
System.out.println(body2.getPosition().x*50+" - "+body2.getPosition().y);
return;
//throw new AssertionError();
}
enemy.takeDamage(bullet.getDamage());
if(bullet == player.getShip().getCurrentWeapon().getLoadingBullet()){
player.getShip().getCurrentWeapon().setLoadingBullet(null);
}
if(!enemy.isAlive()){
elemToDelete.add(body2);
impactEnemyDead(enemy, player);
}
- if((!bullet.getNameLvl().equals("FireBall_3"))&&(!bullet.getName().equals("XRay"))){
+ if((!bullet.getNameLvl().equals("fireball_3"))&&(!bullet.getName().equals("xray"))){
elemToDelete.add(body);
}
}
}
}
@Override
public void endContact(Contact arg0) {
//nothing to do
}
@Override
public void postSolve(Contact arg0, ContactImpulse arg1) {
//Nothing to do
}
@Override
public void preSolve(Contact arg0, Manifold arg1) {
//Nothing to do
}
private void impactEnemyDead(Ship enemy, Player player){
int score=0;
String name = enemy.getName();
if(name.equals("DefaultShip")) score=25;
if(name.equals("KamikazeShip")) score=25;
if(name.equals("BatShip")) score=50;
if( name.equals("FirstBoss") ||
name.equals("SecondBoss") ||
name.equals("ThirdBoss")) score=1000;
player.addScore(score);
if(random.nextInt(100) <= PROBABILITY_NEW_BONUS){
this.createBonus=true;
}
}
}
| false | true | public void beginContact(Contact arg0) {
Player player=Game.getTheGame().getPlayer1();
Ship shipPlayer=player.getShip();
Body body;
Body body2;
Ship enemy;
Bullet bullet;
Bonus bonus;
//if one of the two body that collided is the body of the player's ship
if((arg0.getFixtureA().getBody()==shipPlayer.getBody())||
(arg0.getFixtureB().getBody()==shipPlayer.getBody())){
//get the other body that collided
if(arg0.getFixtureA().getBody()==shipPlayer.getBody()){
body=arg0.getFixtureB().getBody();
} else {
body=arg0.getFixtureA().getBody();
}
//if the second body that collided is an enemy
if((enemy=battleField.getShip(body))!=null){
shipPlayer.takeDamage(10);
enemy.takeDamage(20);
if(!enemy.isAlive()){
impactEnemyDead(enemy,player);
elemToDelete.add(body);
}
} //else if the second body that collided is a bullet
else if((bullet=battleField.getBullet(body))!=null){
shipPlayer.takeDamage(bullet.getDamage());
elemToDelete.add(body);
} //else if the second body that collided is a bonus
else if((bonus=battleField.getBonus(body))!=null){
ListWeapon playerWeapons = shipPlayer.getListWeapon();
playerWeapons.addWeapon(bonus.getType(), bonus.getQuantity());
elemToDelete.add(body);
} else {
System.out.println("WALLLLLLLLLLLLLLLLLLLLLLLLLLL");
}
} else {
body=arg0.getFixtureA().getBody();
body2=arg0.getFixtureB().getBody();
if((enemy=battleField.getShip(body))!=null){
if((bullet=battleField.getBullet(body2))==null){
throw new AssertionError();
}
enemy.takeDamage(bullet.getDamage());
if(bullet == player.getShip().getCurrentWeapon().getLoadingBullet()){
player.getShip().getCurrentWeapon().setLoadingBullet(null);
}
if(!enemy.isAlive()){
elemToDelete.add(body);
impactEnemyDead(enemy,player);
}
if((!bullet.getNameLvl().equals("FireBall_3")) && (!bullet.getName().equals("XRay"))){
elemToDelete.add(body2);
}
} else {
bullet=battleField.getBullet(body);
enemy=battleField.getShip(body2);
if((bullet==null)||(enemy==null)){
System.out.println(body.m_fixtureList.m_filter.categoryBits);
System.out.println(body.m_fixtureList.m_filter.maskBits);
System.out.println(body.getPosition().x*50+" - "+body.getPosition().y);
System.out.println(body2.m_fixtureList.m_filter.categoryBits);
System.out.println(body2.m_fixtureList.m_filter.maskBits);
System.out.println(body2.getPosition().x*50+" - "+body2.getPosition().y);
return;
//throw new AssertionError();
}
enemy.takeDamage(bullet.getDamage());
if(bullet == player.getShip().getCurrentWeapon().getLoadingBullet()){
player.getShip().getCurrentWeapon().setLoadingBullet(null);
}
if(!enemy.isAlive()){
elemToDelete.add(body2);
impactEnemyDead(enemy, player);
}
if((!bullet.getNameLvl().equals("FireBall_3"))&&(!bullet.getName().equals("XRay"))){
elemToDelete.add(body);
}
}
}
}
| public void beginContact(Contact arg0) {
Player player=Game.getTheGame().getPlayer1();
Ship shipPlayer=player.getShip();
Body body;
Body body2;
Ship enemy;
Bullet bullet;
Bonus bonus;
//if one of the two body that collided is the body of the player's ship
if((arg0.getFixtureA().getBody()==shipPlayer.getBody())||
(arg0.getFixtureB().getBody()==shipPlayer.getBody())){
//get the other body that collided
if(arg0.getFixtureA().getBody()==shipPlayer.getBody()){
body=arg0.getFixtureB().getBody();
} else {
body=arg0.getFixtureA().getBody();
}
//if the second body that collided is an enemy
if((enemy=battleField.getShip(body))!=null){
shipPlayer.takeDamage(10);
enemy.takeDamage(20);
if(!enemy.isAlive()){
impactEnemyDead(enemy,player);
elemToDelete.add(body);
}
} //else if the second body that collided is a bullet
else if((bullet=battleField.getBullet(body))!=null){
shipPlayer.takeDamage(bullet.getDamage());
elemToDelete.add(body);
} //else if the second body that collided is a bonus
else if((bonus=battleField.getBonus(body))!=null){
ListWeapon playerWeapons = shipPlayer.getListWeapon();
playerWeapons.addWeapon(bonus.getType(), bonus.getQuantity());
elemToDelete.add(body);
}
} else {
body=arg0.getFixtureA().getBody();
body2=arg0.getFixtureB().getBody();
if((enemy=battleField.getShip(body))!=null){
if((bullet=battleField.getBullet(body2))==null){
throw new AssertionError();
}
enemy.takeDamage(bullet.getDamage());
if(bullet == player.getShip().getCurrentWeapon().getLoadingBullet()){
player.getShip().getCurrentWeapon().setLoadingBullet(null);
}
if(!enemy.isAlive()){
elemToDelete.add(body);
impactEnemyDead(enemy,player);
}
if((!bullet.getNameLvl().equals("fireball_3")) && (!bullet.getName().equals("xray"))){
elemToDelete.add(body2);
}
} else {
bullet=battleField.getBullet(body);
enemy=battleField.getShip(body2);
if((bullet==null)||(enemy==null)){
System.out.println(body.m_fixtureList.m_filter.categoryBits);
System.out.println(body.m_fixtureList.m_filter.maskBits);
System.out.println(body.getPosition().x*50+" - "+body.getPosition().y);
System.out.println(body2.m_fixtureList.m_filter.categoryBits);
System.out.println(body2.m_fixtureList.m_filter.maskBits);
System.out.println(body2.getPosition().x*50+" - "+body2.getPosition().y);
return;
//throw new AssertionError();
}
enemy.takeDamage(bullet.getDamage());
if(bullet == player.getShip().getCurrentWeapon().getLoadingBullet()){
player.getShip().getCurrentWeapon().setLoadingBullet(null);
}
if(!enemy.isAlive()){
elemToDelete.add(body2);
impactEnemyDead(enemy, player);
}
if((!bullet.getNameLvl().equals("fireball_3"))&&(!bullet.getName().equals("xray"))){
elemToDelete.add(body);
}
}
}
}
|
diff --git a/src/org/sakaiproject/tool/assessment/ui/bean/delivery/DeliveryBean.java b/src/org/sakaiproject/tool/assessment/ui/bean/delivery/DeliveryBean.java
index 3c194f512..421e796bc 100755
--- a/src/org/sakaiproject/tool/assessment/ui/bean/delivery/DeliveryBean.java
+++ b/src/org/sakaiproject/tool/assessment/ui/bean/delivery/DeliveryBean.java
@@ -1,1686 +1,1687 @@
/*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* 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.
*/
/*
* Created on Aug 6, 2003
*
*/
package org.sakaiproject.tool.assessment.ui.bean.delivery;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import javax.faces.context.FacesContext;
import org.sakaiproject.tool.assessment.data.dao.assessment.AssessmentAccessControl;
import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData;
import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData;
import org.sakaiproject.tool.assessment.data.dao.grading.MediaData;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedSecuredIPAddress;
import org.sakaiproject.tool.assessment.data.ifc.grading.MediaIfc;
import org.sakaiproject.tool.assessment.ui.bean.util.Validator;
import org.sakaiproject.tool.assessment.ui.listener.delivery.DeliveryActionListener;
import org.sakaiproject.tool.assessment.ui.listener.delivery.SubmitToGradingActionListener;
import org.sakaiproject.tool.assessment.ui.listener.delivery.UpdateTimerListener;
import org.sakaiproject.tool.assessment.ui.listener.select.SelectActionListener;
import java.io.FileInputStream;
import java.io.File;
import java.io.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.sakaiproject.tool.assessment.facade.AgentFacade;
import org.sakaiproject.tool.assessment.facade.PublishedAssessmentFacade;
import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService;
import org.sakaiproject.tool.assessment.services.GradingService;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedItemData;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedItemText;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentAccessControlIfc;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.tool.assessment.util.MimeTypesLocator;
/**
*
* @author casong To change the template for this generated type comment go to
* $Id$
*
* Used to be org.navigoproject.ui.web.asi.delivery.XmlDeliveryForm.java
*/
public class DeliveryBean
implements Serializable
{
private static Log log = LogFactory.getLog(DeliveryBean.class);
private String assessmentId;
private String assessmentTitle;
private ArrayList markedForReview;
private ArrayList blankItems;
private ArrayList markedForReviewIdents;
private ArrayList blankItemIdents;
private boolean reviewMarked;
private boolean reviewAll;
private boolean reviewBlank;
private int itemIndex;
private int size;
private String action;
private Date beginTime;
private String endTime;
private String currentTime;
private String multipleAttempts;
private String timeOutSubmission;
private String submissionTicket;
private String timeElapse;
private String username;
private int sectionIndex;
private boolean previous;
private String duration;
private String url;
private String confirmation;
private String outcome;
//Settings
private String questionLayout;
private String navigation;
private String numbering;
private String feedback;
private String noFeedback;
private String statistics;
private String creatorName;
private FeedbackComponent feedbackComponent;
private String errorMessage;
private SettingsDeliveryBean settings;
private java.util.Date dueDate;
private boolean statsAvailable;
private boolean submitted;
private boolean graded;
private String graderComment;
private String rawScore;
private String grade;
private java.util.Date submissionDate;
private java.util.Date submissionTime;
private String image;
private boolean hasImage;
private String instructorMessage;
private String courseName;
private String timeLimit;
private int timeLimit_hour;
private int timeLimit_minute;
private ContentsDeliveryBean tableOfContents;
private String previewMode;
private String previewAssessment;
private String notPublished;
private String submissionId;
private String submissionMessage;
private String instructorName;
private ContentsDeliveryBean pageContents;
private int submissionsRemaining;
private boolean forGrade;
private String password;
// For paging
private int partIndex;
private int questionIndex;
private boolean next_page;
private boolean reload = true;
// daisy added these for SelectActionListener
private boolean notTakeable = true;
private boolean pastDue;
private long subTime;
private long raw;
private String takenHours;
private String takenMinutes;
private AssessmentGradingData adata;
private PublishedAssessmentFacade publishedAssessment;
private java.util.Date feedbackDate;
private String showScore;
private boolean hasTimeLimit;
// daisyf added for servlet Login.java, to support anonymous login with
// publishedUrl
private boolean anonymousLogin = false;
private boolean accessViaUrl = false;
private String contextPath;
/** Use serialVersionUID for interoperability. */
private final static long serialVersionUID = -1090852048737428722L;
private boolean showStudentScore;
// lydial added for allowing studentScore view for random draw parts
private boolean forGrading; // to reuse deliveryActionListener for grading pages
// SAM-387
// esmiley added to track if timer has been started in timed assessments
private boolean timeRunning;
/**
* Creates a new DeliveryBean object.
*/
public DeliveryBean()
{
}
/**
*
*
* @return
*/
public int getItemIndex()
{
return this.itemIndex;
}
/**
*
*
* @param itemIndex
*/
public void setItemIndex(int itemIndex)
{
this.itemIndex = itemIndex;
}
/**
*
*
* @return
*/
public int getSize()
{
return this.size;
}
/**
*
*
* @param size
*/
public void setSize(int size)
{
this.size = size;
}
/**
*
*
* @return
*/
public String getAssessmentId()
{
return assessmentId;
}
/**
*
*
* @param assessmentId
*/
public void setAssessmentId(String assessmentId)
{
this.assessmentId = assessmentId;
}
/**
*
*
* @return
*/
public ArrayList getMarkedForReview()
{
return markedForReview;
}
/**
*
*
* @param markedForReview
*/
public void setMarkedForReview(ArrayList markedForReview)
{
this.markedForReview = markedForReview;
}
/**
*
*
* @return
*/
public boolean getReviewMarked()
{
return this.reviewMarked;
}
/**
*
*
* @param reviewMarked
*/
public void setReviewMarked(boolean reviewMarked)
{
this.reviewMarked = reviewMarked;
}
/**
*
*
* @return
*/
public boolean getReviewAll()
{
return this.reviewAll;
}
/**
*
*
* @param reviewAll
*/
public void setReviewAll(boolean reviewAll)
{
this.reviewAll = reviewAll;
}
/**
*
*
* @return
*/
public String getAction()
{
return this.action;
}
/**
*
*
* @param action
*/
public void setAction(String action)
{
this.action = action;
}
/**
*
*
* @return
*/
public Date getBeginTime()
{
return beginTime;
}
/**
*
*
* @param beginTime
*/
public void setBeginTime(Date beginTime)
{
this.beginTime = beginTime;
}
/**
*
*
* @return
*/
public String getEndTime()
{
return endTime;
}
/**
*
*
* @param endTime
*/
public void setEndTime(String endTime)
{
this.endTime = endTime;
}
/**
*
*
* @return
*/
public String getCurrentTime()
{
return this.currentTime;
}
/**
*
*
* @param currentTime
*/
public void setCurrentTime(String currentTime)
{
this.currentTime = currentTime;
}
/**
*
*
* @return
*/
public String getMultipleAttempts()
{
return this.multipleAttempts;
}
/**
*
*
* @param multipleAttempts
*/
public void setMultipleAttempts(String multipleAttempts)
{
this.multipleAttempts = multipleAttempts;
}
/**
*
*
* @return
*/
public String getTimeOutSubmission()
{
return this.timeOutSubmission;
}
/**
*
*
* @param timeOutSubmission
*/
public void setTimeOutSubmission(String timeOutSubmission)
{
this.timeOutSubmission = timeOutSubmission;
}
/**
*
*
* @return
*/
public java.util.Date getSubmissionTime()
{
return submissionTime;
}
/**
*
*
* @param submissionTime
*/
public void setSubmissionTime(java.util.Date submissionTime)
{
this.submissionTime = submissionTime;
}
/**
*
*
* @return
*/
public String getTimeElapse()
{
return timeElapse;
}
/**
*
*
* @param timeElapse
*/
public void setTimeElapse(String timeElapse)
{
this.timeElapse = timeElapse;
}
/**
*
*
* @return
*/
public String getSubmissionTicket()
{
return submissionTicket;
}
/**
*
*
* @param submissionTicket
*/
public void setSubmissionTicket(String submissionTicket)
{
this.submissionTicket = submissionTicket;
}
/**
*
*
* @return
*/
public int getDisplayIndex()
{
return this.itemIndex + 1;
}
/**
*
*
* @return
*/
public String getUsername()
{
return username;
}
/**
*
*
* @param username
*/
public void setUsername(String username)
{
this.username = username;
}
/**
*
*
* @return
*/
public String getAssessmentTitle()
{
return assessmentTitle;
}
/**
*
*
* @param assessmentTitle
*/
public void setAssessmentTitle(String assessmentTitle)
{
this.assessmentTitle = assessmentTitle;
}
/**
*
*
* @return
*/
public ArrayList getBlankItems()
{
return this.blankItems;
}
/**
*
*
* @param blankItems
*/
public void setBlankItems(ArrayList blankItems)
{
this.blankItems = blankItems;
}
/**
*
*
* @return
*/
public boolean getReviewBlank()
{
return reviewBlank;
}
/**
*
*
* @param reviewBlank
*/
public void setReviewBlank(boolean reviewBlank)
{
this.reviewBlank = reviewBlank;
}
/**
*
*
* @return
*/
public ArrayList getMarkedForReviewIdents()
{
return markedForReviewIdents;
}
/**
*
*
* @param markedForReviewIdents
*/
public void setMarkedForReviewIdents(ArrayList markedForReviewIdents)
{
this.markedForReviewIdents = markedForReviewIdents;
}
/**
*
*
* @return
*/
public ArrayList getBlankItemIdents()
{
return blankItemIdents;
}
/**
*
*
* @param blankItemIdents
*/
public void setBlankItemIdents(ArrayList blankItemIdents)
{
this.blankItemIdents = blankItemIdents;
}
/**
*
*
* @return
*/
public int getSectionIndex()
{
return this.sectionIndex;
}
/**
*
*
* @param sectionIndex
*/
public void setSectionIndex(int sectionIndex)
{
this.sectionIndex = sectionIndex;
}
/**
*
*
* @return
*/
public boolean getPrevious()
{
return previous;
}
/**
*
*
* @param previous
*/
public void setPrevious(boolean previous)
{
this.previous = previous;
}
//Settings
public String getQuestionLayout()
{
return questionLayout;
}
/**
*
*
* @param questionLayout
*/
public void setQuestionLayout(String questionLayout)
{
this.questionLayout = questionLayout;
}
/**
*
*
* @return
*/
public String getNavigation()
{
return navigation;
}
/**
*
*
* @param navigation
*/
public void setNavigation(String navigation)
{
this.navigation = navigation;
}
/**
*
*
* @return
*/
public String getNumbering()
{
return numbering;
}
/**
*
*
* @param numbering
*/
public void setNumbering(String numbering)
{
this.numbering = numbering;
}
/**
*
*
* @return
*/
public String getFeedback()
{
return feedback;
}
/**
*
*
* @param feedback
*/
public void setFeedback(String feedback)
{
this.feedback = feedback;
}
/**
*
*
* @return
*/
public String getNoFeedback()
{
return noFeedback;
}
/**
*
*
* @param noFeedback
*/
public void setNoFeedback(String noFeedback)
{
this.noFeedback = noFeedback;
}
/**
*
*
* @return
*/
public String getStatistics()
{
return statistics;
}
/**
*
*
* @param statistics
*/
public void setStatistics(String statistics)
{
this.statistics = statistics;
}
/**
*
*
* @return
*/
public FeedbackComponent getFeedbackComponent()
{
return feedbackComponent;
}
/**
*
*
* @param feedbackComponent
*/
public void setFeedbackComponent(FeedbackComponent feedbackComponent)
{
this.feedbackComponent = feedbackComponent;
}
/**
* Types of feedback in FeedbackComponent:
*
* SHOW CORRECT SCORE
* SHOW STUDENT SCORE
* SHOW ITEM LEVEL
* SHOW SECTION LEVEL
* SHOW GRADER COMMENT
* SHOW STATS
* SHOW QUESTION
* SHOW RESPONSE
**/
/**
* @return
*/
public SettingsDeliveryBean getSettings()
{
return settings;
}
/**
* @param bean
*/
public void setSettings(SettingsDeliveryBean settings)
{
this.settings = settings;
}
/**
* @return
*/
public String getErrorMessage()
{
return errorMessage;
}
/**
* @param string
*/
public void setErrorMessage(String string)
{
errorMessage = string;
}
/**
* @return
*/
public String getDuration()
{
return duration;
}
/**
* @param string
*/
public void setDuration(String string)
{
duration = string;
}
/**
* @return
*/
public String getCreatorName()
{
return creatorName;
}
/**
* @param string
*/
public void setCreatorName(String string)
{
creatorName = string;
}
public java.util.Date getDueDate()
{
return dueDate;
}
public void setDueDate(java.util.Date dueDate)
{
this.dueDate = dueDate;
}
public boolean isStatsAvailable() {
return statsAvailable;
}
public void setStatsAvailable(boolean statsAvailable) {
this.statsAvailable = statsAvailable;
}
public boolean isSubmitted() {
return submitted;
}
public void setSubmitted(boolean submitted) {
this.submitted = submitted;
}
public boolean isGraded() {
return graded;
}
public void setGraded(boolean graded) {
this.graded = graded;
}
public String getGraderComment() {
if (graderComment == null)
return "";
return graderComment;
}
public void setGraderComment(String newComment)
{
graderComment = newComment;
}
public String getRawScore() {
return rawScore;
}
public void setRawScore(String rawScore) {
this.rawScore = rawScore;
}
public long getRaw() {
return raw;
}
public void setRaw(long raw) {
this.raw = raw;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public java.util.Date getSubmissionDate() {
return submissionDate;
}
public void setSubmissionDate(java.util.Date submissionDate) {
this.submissionDate = submissionDate;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public boolean isHasImage() {
return hasImage;
}
public void setHasImage(boolean hasImage) {
this.hasImage = hasImage;
}
public String getInstructorMessage() {
return instructorMessage;
}
public void setInstructorMessage(String instructorMessage) {
this.instructorMessage = instructorMessage;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getTimeLimit() {
return timeLimit;
}
public void setTimeLimit(String timeLimit) {
this.timeLimit = timeLimit;
}
public int getTimeLimit_hour() {
return timeLimit_hour;
}
public void setTimeLimit_hour(int timeLimit_hour) {
this.timeLimit_hour = timeLimit_hour;
}
public int getTimeLimit_minute() {
return timeLimit_minute;
}
public void setTimeLimit_minute(int timeLimit_minute) {
this.timeLimit_minute = timeLimit_minute;
}
/**
* Bean with table of contents information and
* a list of all the sections in the assessment
* which in turn has a list of all the item contents.
* @return table of contents
*/
public ContentsDeliveryBean getTableOfContents() {
return tableOfContents;
}
/**
* Bean with table of contents information and
* a list of all the sections in the assessment
* which in turn has a list of all the item contents.
* @param tableOfContents table of contents
*/
public void setTableOfContents(ContentsDeliveryBean tableOfContents) {
this.tableOfContents = tableOfContents;
}
/**
* Bean with a list of all the sections in the current page
* which in turn has a list of all the item contents for the page.
*
* This is like the table of contents, but the selections are restricted to
* that on one page.
*
* Since these properties are on a page delivery basis--if:
* 1. there is only one item per page the list of items will
* contain one item and the list of parts will return one part, or if--
*
* 2. there is one part per page the list of items will be that
* for that part only and there will only be one part, however--
*
* 3. if it is all parts and items on a single page there
* will be a list of all parts and items.
*
* @return ContentsDeliveryBean
*/
public ContentsDeliveryBean getPageContents() {
return pageContents;
}
/**
* Bean with a list of all the sections in the current page
* which in turn has a list of all the item contents for the page.
*
* Since these properties are on a page delivery basis--if:
* 1. there is only one item per page the list of items will
* contain one item and the list of parts will return one part, or if--
*
* 2. there is one part per page the list of items will be that
* for that part only and there will only be one part, however--
*
* 3. if it is all parts and items on a single page there
* will be a list of all parts and items.
*
* @param pageContents ContentsDeliveryBean
*/
public void setPageContents(ContentsDeliveryBean pageContents) {
this.pageContents = pageContents;
}
/**
* track whether delivery is "live" with update of database allowed and
* whether the Ui components are disabled.
* @return true if preview only
*/
public String getPreviewMode() {
return Validator.check(previewMode, "false");
}
/**
* track whether delivery is "live" with update of database allowed and
* whether the UI components are disabled.
* @param previewMode true if preview only
*/
public void setPreviewMode(boolean previewMode) {
this.previewMode = new Boolean(previewMode).toString();
}
public String getPreviewAssessment() {
return previewAssessment;
}
public void setPreviewAssessment(String previewAssessment) {
this.previewAssessment = previewAssessment;
}
public String getNotPublished() {
return notPublished;
}
public void setNotPublished(String notPublished) {
this.notPublished = notPublished;
}
public String getSubmissionId() {
return submissionId;
}
public void setSubmissionId(String submissionId) {
this.submissionId = submissionId;
}
public String getSubmissionMessage() {
return submissionMessage;
}
public void setSubmissionMessage(String submissionMessage) {
this.submissionMessage = submissionMessage;
}
public int getSubmissionsRemaining() {
return submissionsRemaining;
}
public void setSubmissionsRemaining(int submissionsRemaining) {
this.submissionsRemaining = submissionsRemaining;
}
public String getInstructorName() {
return instructorName;
}
public void setInstructorName(String instructorName) {
this.instructorName = instructorName;
}
public boolean getForGrade() {
return forGrade;
}
public void setForGrade(boolean newfor) {
forGrade = newfor;
}
public String submitForGrade()
{
forGrade = true;
SubmitToGradingActionListener listener =
new SubmitToGradingActionListener();
listener.processAction(null);
forGrade = false;
SelectActionListener l2 = new SelectActionListener();
l2.processAction(null);
reload = true;
if (getAccessViaUrl()) // this is for accessing via published url
return "anonymousThankYou";
else
return "submitAssessment";
}
public String saveAndExit()
{
FacesContext context = FacesContext.getCurrentInstance();
System.out.println("***DeliverBean.saveAndEXit face context ="+context);
// If this was automatically triggered by running out of time,
// check for autosubmit, and do it if so.
if (timeOutSubmission != null && timeOutSubmission.equals("true"))
{
if (getSettings().getAutoSubmit())
{
submitForGrade();
return "timeout";
}
}
forGrade = false;
SubmitToGradingActionListener listener =
new SubmitToGradingActionListener();
listener.processAction(null);
SelectActionListener l2 = new SelectActionListener();
l2.processAction(null);
reload = true;
if (timeOutSubmission != null && timeOutSubmission.equals("true"))
{
return "timeout";
}
if (getAccessViaUrl()){ // if this is access via url, display quit message
System.out.println("**anonymous login, go to quit");
return "anonymousQuit";
}
else{
System.out.println("**NOT anonymous login, go to select");
return "select";
}
}
public String next_page()
{
if (getSettings().isFormatByPart())
partIndex++;
if (getSettings().isFormatByQuestion())
questionIndex++;
forGrade = false;
if (!("true").equals(previewAssessment))
{
SubmitToGradingActionListener listener =
new SubmitToGradingActionListener();
listener.processAction(null);
}
DeliveryActionListener l2 = new DeliveryActionListener();
l2.processAction(null);
reload = false;
return "takeAssessment";
}
public String previous()
{
if (getSettings().isFormatByPart())
partIndex--;
if (getSettings().isFormatByQuestion())
questionIndex--;
forGrade = false;
if (!("true").equals(previewAssessment))
{
SubmitToGradingActionListener listener =
new SubmitToGradingActionListener();
listener.processAction(null);
}
DeliveryActionListener l2 = new DeliveryActionListener();
l2.processAction(null);
reload = false;
return "takeAssessment";
}
// this is the PublishedAccessControl.finalPageUrl
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url= url;
}
public String getConfirmation() {
return confirmation;
}
public void setConfirmation(String confirmation) {
this.confirmation= confirmation;
}
/**
* if required, assessment password
* @return password
*/
public String getPassword()
{
return password;
}
/**
* if required, assessment password
* @param string assessment password
*/
public void setPassword(String string)
{
password = string;
}
public String validatePassword() {
log.debug("**** username="+username);
log.debug("**** password="+password);
log.debug("**** setting username="+getSettings().getUsername());
log.debug("**** setting password="+getSettings().getPassword());
if (password == null || username == null)
return "passwordAccessError";
if (password.equals(getSettings().getPassword()) &&
username.equals(getSettings().getUsername()))
{
if (getNavigation().equals
(AssessmentAccessControl.RANDOM_ACCESS.toString()))
return "tableOfContents";
else
return "takeAssessment";
}
else
return "passwordAccessError";
}
public String validateIP() {
String thisIp = ((javax.servlet.http.HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRemoteAddr();
Iterator addresses = getSettings().getIpAddresses().iterator();
while (addresses.hasNext())
{
String next = ((PublishedSecuredIPAddress) addresses.next()).
getIpAddress();
if (next != null && next.indexOf("*") > -1)
next = next.substring(0, next.indexOf("*"));
if (next == null || next.trim().equals("") ||
thisIp.trim().startsWith(next.trim()))
{
if (getNavigation().equals
(AssessmentAccessControl.RANDOM_ACCESS.toString()))
return "tableOfContents";
else
return "takeAssessment";
}
}
return "ipAccessError";
}
public String validate() {
try {
String results = "";
if (!getSettings().getUsername().equals(""))
results = validatePassword();
if (!results.equals("passwordAccessError") &&
getSettings().getIpAddresses() != null &&
!getSettings().getIpAddresses().isEmpty())
results = validateIP();
if (results.equals(""))
{
if (getNavigation().equals
(AssessmentAccessControl.RANDOM_ACCESS.toString()))
return "tableOfContents";
else
return "takeAssessment";
}
return results;
} catch (Exception e) {
e.printStackTrace();
return "accessError";
}
}
// Skipped paging methods
public int getPartIndex()
{
return partIndex;
}
public void setPartIndex(int newindex)
{
partIndex = newindex;
}
public int getQuestionIndex()
{
return questionIndex;
}
public void setQuestionIndex(int newindex)
{
questionIndex = newindex;
}
public boolean getContinue()
{
return next_page;
}
public void setContinue(boolean docontinue)
{
next_page = docontinue;
}
public boolean getReload()
{
return reload;
}
public void setReload(boolean doreload)
{
reload = doreload;
}
// Store for paging
public AssessmentGradingData getAssessmentGrading()
{
return adata;
}
public void setAssessmentGrading(AssessmentGradingData newdata)
{
adata = newdata;
}
private byte[] getMediaStream(String mediaLocation){
FileInputStream mediaStream=null;
FileInputStream mediaStream2=null;
byte[] mediaByte = new byte[0];
try {
int i = 0;
int size = 0;
mediaStream = new FileInputStream(mediaLocation);
if (mediaStream != null){
while((i = mediaStream.read()) != -1){
size++;
}
}
mediaStream2 = new FileInputStream(mediaLocation);
mediaByte = new byte[size];
mediaStream2.read(mediaByte, 0, size);
FileOutputStream out = new FileOutputStream("/tmp/test.txt");
out.write(mediaByte);
}
catch (FileNotFoundException ex) {
log.debug("file not found="+ex.getMessage());
}
catch (IOException ex) {
log.debug("io exception="+ex.getMessage());
}
finally{
try {
mediaStream.close();
}
catch (IOException ex1) {
}
}
return mediaByte;
}
/**
* This method is used by jsf/delivery/deliveryFileUpload.jsp
* <corejsf:upload
* target="/jsf/upload_tmp/assessment#{delivery.assessmentId}/
* question#{question.itemData.itemId}/admin"
* valueChangeListener="#{delivery.addMediaToItemGrading}" />
*/
public String addMediaToItemGrading(javax.faces.event.ValueChangeEvent e)
{
GradingService gradingService = new GradingService();
PublishedAssessmentService publishedService = new PublishedAssessmentService();
PublishedAssessmentFacade publishedAssessment = publishedService.getPublishedAssessment(assessmentId);
String agent = AgentFacade.getAgentString();
if (publishedAssessment.getAssessmentAccessControl().getReleaseTo().indexOf("Anonymous Users") > -1)
agent = AgentFacade.getAnonymousId();
// 1. create assessmentGrading if it is null
if (this.adata == null)
{
adata = new AssessmentGradingData();
adata.setAgentId(agent);
adata.setPublishedAssessment(publishedAssessment.getData());
log.debug("***1a. addMediaToItemGrading, getForGrade()="+getForGrade());
adata.setForGrade(new Boolean(getForGrade()));
adata.setAttemptDate(getBeginTime());
gradingService.saveOrUpdateAssessmentGrading(adata);
}
log.debug("***1b. addMediaToItemGrading, adata="+adata);
// 2. format of the media location is: assessmentXXX/questionXXX/agentId/myfile
String mediaLocation = (String) e.getNewValue();
log.debug("***2a. addMediaToItemGrading, new value ="+mediaLocation);
File media = new File(mediaLocation);
byte[] mediaByte = getMediaStream(mediaLocation);
// 3. get the questionId (which is the PublishedItemData.itemId)
int assessmentIndex = mediaLocation.lastIndexOf("assessment");
int questionIndex = mediaLocation.lastIndexOf("question");
int agentIndex = mediaLocation.indexOf("/", questionIndex+8);
String pubAssessmentId = mediaLocation.substring(assessmentIndex+10,questionIndex-1);
String questionId = mediaLocation.substring(questionIndex+8,agentIndex);
log.debug("***3a. addMediaToItemGrading, questionId ="+questionId);
log.debug("***3b. addMediaToItemGrading, assessmentId ="+assessmentId);
// 4. prepare itemGradingData and attach it to assessmentGarding
PublishedItemData item = publishedService.loadPublishedItem(questionId);
log.debug("***4a. addMediaToItemGrading, item ="+item);
log.debug("***4b. addMediaToItemGrading, itemTextArray ="+item.getItemTextArray());
log.debug("***4c. addMediaToItemGrading, itemText(0) ="+item.getItemTextArray().get(0));
// there is only one text in audio question
PublishedItemText itemText = (PublishedItemText) item.getItemTextArraySorted().get(0);
ItemGradingData itemGradingData = getItemGradingData(questionId);
if (itemGradingData == null){
itemGradingData = new ItemGradingData();
itemGradingData.setAssessmentGrading(adata);
itemGradingData.setPublishedItem(item);
itemGradingData.setPublishedItemText(itemText);
itemGradingData.setSubmittedDate(new Date());
itemGradingData.setAgentId(agent);
itemGradingData.setOverrideScore(new Float(0));
}
setAssessmentGrading(adata);
// 5. save AssessmentGardingData with ItemGardingData
Set itemDataSet = adata.getItemGradingSet();
log.debug("***5a. addMediaToItemGrading, itemDataSet="+itemDataSet);
if (itemDataSet == null)
itemDataSet = new HashSet();
itemDataSet.add(itemGradingData);
adata.setItemGradingSet(itemDataSet);
gradingService.saveOrUpdateAssessmentGrading(adata);
log.debug("***5b. addMediaToItemGrading, saved="+adata);
// 6. create a media record
String mimeType = MimeTypesLocator.getInstance().getContentType(media);
boolean SAVETODB = MediaData.saveToDB();
log.debug("**** SAVETODB="+SAVETODB);
MediaData mediaData=null;
log.debug("***6a. addMediaToItemGrading, itemGradinDataId="+itemGradingData.getItemGradingId());
log.debug("***6b. addMediaToItemGrading, publishedItemId="+((PublishedItemData)itemGradingData.getPublishedItem()).getItemId());
if (SAVETODB){ // put the byte[] in
mediaData = new MediaData(itemGradingData, mediaByte,
new Long(mediaByte.length + ""),
mimeType, "description", null,
media.getName(), false, false, new Integer(1),
agent, new Date(),
agent, new Date());
}
else{ // put the location in
mediaData = new MediaData(itemGradingData, null,
new Long(mediaByte.length + ""),
mimeType, "description", mediaLocation,
media.getName(), false, false, new Integer(1),
agent, new Date(),
agent, new Date());
}
Long mediaId = gradingService.saveMedia(mediaData);
log.debug("mediaId="+mediaId);
log.debug("***6c. addMediaToItemGrading, media.itemGradinDataId="+((ItemGradingData)mediaData.getItemGradingData()).getItemGradingId());
log.debug("***6d. addMediaToItemGrading, mediaId="+mediaData.getMediaId());
// 7. store mediaId in itemGradingRecord.answerText
log.debug("***7. addMediaToItemGrading, adata="+adata);
itemGradingData.setAnswerText(mediaId+"");
gradingService.saveItemGrading(itemGradingData);
// 8. do whatever need doing
DeliveryActionListener l2 = new DeliveryActionListener();
l2.processAction(null);
// 9. do the timer thing
Integer timeLimit = null;
- if (adata.getPublishedAssessment().getAssessmentAccessControl()!=null)
- timeLimit = adata.getPublishedAssessment().getAssessmentAccessControl().getTimeLimit();
+ if (adata!=null && adata.getPublishedAssessment()!=null
+ && adata.getPublishedAssessment().getAssessmentAccessControl()!=null)
+ timeLimit = adata.getPublishedAssessment().getAssessmentAccessControl().getTimeLimit();
if (timeLimit!=null && timeLimit.intValue()>0){
UpdateTimerListener l3 = new UpdateTimerListener();
l3.processAction(null);
}
reload = true;
return "takeAssessment";
}
public boolean getNotTakeable() {
return notTakeable;
}
public void setNotTakeable(boolean notTakeable) {
this.notTakeable = notTakeable;
}
public boolean getPastDue() {
return pastDue;
}
public void setPastDue(boolean pastDue) {
this.pastDue = pastDue;
}
public long getSubTime() {
return subTime;
}
public void setSubTime(long newSubTime)
{
subTime = newSubTime;
}
public String getSubmissionHours() {
return takenHours;
}
public void setSubmissionHours(String newHours)
{
takenHours = newHours;
}
public String getSubmissionMinutes() {
return takenMinutes;
}
public void setSubmissionMinutes(String newMinutes)
{
takenMinutes = newMinutes;
}
public PublishedAssessmentFacade getPublishedAssessment() {
return publishedAssessment;
}
public void setPublishedAssessment(PublishedAssessmentFacade publishedAssessment)
{
this.publishedAssessment = publishedAssessment;
}
public java.util.Date getFeedbackDate() {
return feedbackDate;
}
public void setFeedbackDate(java.util.Date feedbackDate) {
this.feedbackDate = feedbackDate;
}
public String getShowScore()
{
return showScore;
}
public void setShowScore(String showScore)
{
this.showScore = showScore;
}
public boolean getHasTimeLimit() {
return hasTimeLimit;
}
public void setHasTimeLimit(boolean hasTimeLimit) {
this.hasTimeLimit = hasTimeLimit;
}
public String getOutcome()
{
return outcome;
}
public void setOutcome(String outcome)
{
this.outcome = outcome;
}
public String doit(){
return outcome;
}
/*
public ItemGradingData getItemGradingData(String publishedItemId){
ItemGradingData itemGradingData = new ItemGradingData();
if (adata != null){
GradingService service = new GradingService();
itemGradingData = service.getItemGradingData(adata.getAssessmentGradingId().toString(), publishedItemId);
if (itemGradingData == null)
itemGradingData = new ItemGradingData();
}
return itemGradingData;
}
*/
public boolean getAnonymousLogin() {
return anonymousLogin;
}
public void setAnonymousLogin(boolean anonymousLogin) {
this.anonymousLogin = anonymousLogin;
}
public boolean getAccessViaUrl() {
return accessViaUrl;
}
public void setAccessViaUrl(boolean accessViaUrl) {
this.accessViaUrl = accessViaUrl;
}
public ItemGradingData getItemGradingData(String publishedItemId){
ItemGradingData selected = null;
if (adata != null){
Set items = adata.getItemGradingSet();
if (items!=null){
Iterator iter = items.iterator();
while (iter.hasNext()){
ItemGradingData itemGradingData = (ItemGradingData)iter.next();
String itemPublishedId = itemGradingData.getPublishedItem().getItemId().toString();
if ((publishedItemId).equals(itemPublishedId)){
log.debug("*** addMediaToItemGrading, same : found it");
selected = itemGradingData;
}
else{
log.debug("*** addMediaToItemGrading, not the same");
}
}
log.debug("*** addMediaToItemGrading, publishedItemId ="+publishedItemId);
if (selected!=null)
log.debug("*** addMediaToItemGrading, itemGradingData.publishedItemId ="+selected.getPublishedItem().getItemId().toString());
}
}
return selected;
}
public String getContextPath() {
return contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public boolean isShowStudentScore()
{
return showStudentScore;
}
public void setShowStudentScore(boolean showStudentScore)
{
this.showStudentScore = showStudentScore;
}
public boolean getForGrading()
{
return forGrading;
}
public void setForGrading(boolean param)
{
this.forGrading= param;
}
public boolean isTimeRunning()
{
return timeRunning;
}
public void setTimeRunning(boolean timeRunning)
{
this.timeRunning = timeRunning;
}
}
| true | true | public String addMediaToItemGrading(javax.faces.event.ValueChangeEvent e)
{
GradingService gradingService = new GradingService();
PublishedAssessmentService publishedService = new PublishedAssessmentService();
PublishedAssessmentFacade publishedAssessment = publishedService.getPublishedAssessment(assessmentId);
String agent = AgentFacade.getAgentString();
if (publishedAssessment.getAssessmentAccessControl().getReleaseTo().indexOf("Anonymous Users") > -1)
agent = AgentFacade.getAnonymousId();
// 1. create assessmentGrading if it is null
if (this.adata == null)
{
adata = new AssessmentGradingData();
adata.setAgentId(agent);
adata.setPublishedAssessment(publishedAssessment.getData());
log.debug("***1a. addMediaToItemGrading, getForGrade()="+getForGrade());
adata.setForGrade(new Boolean(getForGrade()));
adata.setAttemptDate(getBeginTime());
gradingService.saveOrUpdateAssessmentGrading(adata);
}
log.debug("***1b. addMediaToItemGrading, adata="+adata);
// 2. format of the media location is: assessmentXXX/questionXXX/agentId/myfile
String mediaLocation = (String) e.getNewValue();
log.debug("***2a. addMediaToItemGrading, new value ="+mediaLocation);
File media = new File(mediaLocation);
byte[] mediaByte = getMediaStream(mediaLocation);
// 3. get the questionId (which is the PublishedItemData.itemId)
int assessmentIndex = mediaLocation.lastIndexOf("assessment");
int questionIndex = mediaLocation.lastIndexOf("question");
int agentIndex = mediaLocation.indexOf("/", questionIndex+8);
String pubAssessmentId = mediaLocation.substring(assessmentIndex+10,questionIndex-1);
String questionId = mediaLocation.substring(questionIndex+8,agentIndex);
log.debug("***3a. addMediaToItemGrading, questionId ="+questionId);
log.debug("***3b. addMediaToItemGrading, assessmentId ="+assessmentId);
// 4. prepare itemGradingData and attach it to assessmentGarding
PublishedItemData item = publishedService.loadPublishedItem(questionId);
log.debug("***4a. addMediaToItemGrading, item ="+item);
log.debug("***4b. addMediaToItemGrading, itemTextArray ="+item.getItemTextArray());
log.debug("***4c. addMediaToItemGrading, itemText(0) ="+item.getItemTextArray().get(0));
// there is only one text in audio question
PublishedItemText itemText = (PublishedItemText) item.getItemTextArraySorted().get(0);
ItemGradingData itemGradingData = getItemGradingData(questionId);
if (itemGradingData == null){
itemGradingData = new ItemGradingData();
itemGradingData.setAssessmentGrading(adata);
itemGradingData.setPublishedItem(item);
itemGradingData.setPublishedItemText(itemText);
itemGradingData.setSubmittedDate(new Date());
itemGradingData.setAgentId(agent);
itemGradingData.setOverrideScore(new Float(0));
}
setAssessmentGrading(adata);
// 5. save AssessmentGardingData with ItemGardingData
Set itemDataSet = adata.getItemGradingSet();
log.debug("***5a. addMediaToItemGrading, itemDataSet="+itemDataSet);
if (itemDataSet == null)
itemDataSet = new HashSet();
itemDataSet.add(itemGradingData);
adata.setItemGradingSet(itemDataSet);
gradingService.saveOrUpdateAssessmentGrading(adata);
log.debug("***5b. addMediaToItemGrading, saved="+adata);
// 6. create a media record
String mimeType = MimeTypesLocator.getInstance().getContentType(media);
boolean SAVETODB = MediaData.saveToDB();
log.debug("**** SAVETODB="+SAVETODB);
MediaData mediaData=null;
log.debug("***6a. addMediaToItemGrading, itemGradinDataId="+itemGradingData.getItemGradingId());
log.debug("***6b. addMediaToItemGrading, publishedItemId="+((PublishedItemData)itemGradingData.getPublishedItem()).getItemId());
if (SAVETODB){ // put the byte[] in
mediaData = new MediaData(itemGradingData, mediaByte,
new Long(mediaByte.length + ""),
mimeType, "description", null,
media.getName(), false, false, new Integer(1),
agent, new Date(),
agent, new Date());
}
else{ // put the location in
mediaData = new MediaData(itemGradingData, null,
new Long(mediaByte.length + ""),
mimeType, "description", mediaLocation,
media.getName(), false, false, new Integer(1),
agent, new Date(),
agent, new Date());
}
Long mediaId = gradingService.saveMedia(mediaData);
log.debug("mediaId="+mediaId);
log.debug("***6c. addMediaToItemGrading, media.itemGradinDataId="+((ItemGradingData)mediaData.getItemGradingData()).getItemGradingId());
log.debug("***6d. addMediaToItemGrading, mediaId="+mediaData.getMediaId());
// 7. store mediaId in itemGradingRecord.answerText
log.debug("***7. addMediaToItemGrading, adata="+adata);
itemGradingData.setAnswerText(mediaId+"");
gradingService.saveItemGrading(itemGradingData);
// 8. do whatever need doing
DeliveryActionListener l2 = new DeliveryActionListener();
l2.processAction(null);
// 9. do the timer thing
Integer timeLimit = null;
if (adata.getPublishedAssessment().getAssessmentAccessControl()!=null)
timeLimit = adata.getPublishedAssessment().getAssessmentAccessControl().getTimeLimit();
if (timeLimit!=null && timeLimit.intValue()>0){
UpdateTimerListener l3 = new UpdateTimerListener();
l3.processAction(null);
}
reload = true;
return "takeAssessment";
}
| public String addMediaToItemGrading(javax.faces.event.ValueChangeEvent e)
{
GradingService gradingService = new GradingService();
PublishedAssessmentService publishedService = new PublishedAssessmentService();
PublishedAssessmentFacade publishedAssessment = publishedService.getPublishedAssessment(assessmentId);
String agent = AgentFacade.getAgentString();
if (publishedAssessment.getAssessmentAccessControl().getReleaseTo().indexOf("Anonymous Users") > -1)
agent = AgentFacade.getAnonymousId();
// 1. create assessmentGrading if it is null
if (this.adata == null)
{
adata = new AssessmentGradingData();
adata.setAgentId(agent);
adata.setPublishedAssessment(publishedAssessment.getData());
log.debug("***1a. addMediaToItemGrading, getForGrade()="+getForGrade());
adata.setForGrade(new Boolean(getForGrade()));
adata.setAttemptDate(getBeginTime());
gradingService.saveOrUpdateAssessmentGrading(adata);
}
log.debug("***1b. addMediaToItemGrading, adata="+adata);
// 2. format of the media location is: assessmentXXX/questionXXX/agentId/myfile
String mediaLocation = (String) e.getNewValue();
log.debug("***2a. addMediaToItemGrading, new value ="+mediaLocation);
File media = new File(mediaLocation);
byte[] mediaByte = getMediaStream(mediaLocation);
// 3. get the questionId (which is the PublishedItemData.itemId)
int assessmentIndex = mediaLocation.lastIndexOf("assessment");
int questionIndex = mediaLocation.lastIndexOf("question");
int agentIndex = mediaLocation.indexOf("/", questionIndex+8);
String pubAssessmentId = mediaLocation.substring(assessmentIndex+10,questionIndex-1);
String questionId = mediaLocation.substring(questionIndex+8,agentIndex);
log.debug("***3a. addMediaToItemGrading, questionId ="+questionId);
log.debug("***3b. addMediaToItemGrading, assessmentId ="+assessmentId);
// 4. prepare itemGradingData and attach it to assessmentGarding
PublishedItemData item = publishedService.loadPublishedItem(questionId);
log.debug("***4a. addMediaToItemGrading, item ="+item);
log.debug("***4b. addMediaToItemGrading, itemTextArray ="+item.getItemTextArray());
log.debug("***4c. addMediaToItemGrading, itemText(0) ="+item.getItemTextArray().get(0));
// there is only one text in audio question
PublishedItemText itemText = (PublishedItemText) item.getItemTextArraySorted().get(0);
ItemGradingData itemGradingData = getItemGradingData(questionId);
if (itemGradingData == null){
itemGradingData = new ItemGradingData();
itemGradingData.setAssessmentGrading(adata);
itemGradingData.setPublishedItem(item);
itemGradingData.setPublishedItemText(itemText);
itemGradingData.setSubmittedDate(new Date());
itemGradingData.setAgentId(agent);
itemGradingData.setOverrideScore(new Float(0));
}
setAssessmentGrading(adata);
// 5. save AssessmentGardingData with ItemGardingData
Set itemDataSet = adata.getItemGradingSet();
log.debug("***5a. addMediaToItemGrading, itemDataSet="+itemDataSet);
if (itemDataSet == null)
itemDataSet = new HashSet();
itemDataSet.add(itemGradingData);
adata.setItemGradingSet(itemDataSet);
gradingService.saveOrUpdateAssessmentGrading(adata);
log.debug("***5b. addMediaToItemGrading, saved="+adata);
// 6. create a media record
String mimeType = MimeTypesLocator.getInstance().getContentType(media);
boolean SAVETODB = MediaData.saveToDB();
log.debug("**** SAVETODB="+SAVETODB);
MediaData mediaData=null;
log.debug("***6a. addMediaToItemGrading, itemGradinDataId="+itemGradingData.getItemGradingId());
log.debug("***6b. addMediaToItemGrading, publishedItemId="+((PublishedItemData)itemGradingData.getPublishedItem()).getItemId());
if (SAVETODB){ // put the byte[] in
mediaData = new MediaData(itemGradingData, mediaByte,
new Long(mediaByte.length + ""),
mimeType, "description", null,
media.getName(), false, false, new Integer(1),
agent, new Date(),
agent, new Date());
}
else{ // put the location in
mediaData = new MediaData(itemGradingData, null,
new Long(mediaByte.length + ""),
mimeType, "description", mediaLocation,
media.getName(), false, false, new Integer(1),
agent, new Date(),
agent, new Date());
}
Long mediaId = gradingService.saveMedia(mediaData);
log.debug("mediaId="+mediaId);
log.debug("***6c. addMediaToItemGrading, media.itemGradinDataId="+((ItemGradingData)mediaData.getItemGradingData()).getItemGradingId());
log.debug("***6d. addMediaToItemGrading, mediaId="+mediaData.getMediaId());
// 7. store mediaId in itemGradingRecord.answerText
log.debug("***7. addMediaToItemGrading, adata="+adata);
itemGradingData.setAnswerText(mediaId+"");
gradingService.saveItemGrading(itemGradingData);
// 8. do whatever need doing
DeliveryActionListener l2 = new DeliveryActionListener();
l2.processAction(null);
// 9. do the timer thing
Integer timeLimit = null;
if (adata!=null && adata.getPublishedAssessment()!=null
&& adata.getPublishedAssessment().getAssessmentAccessControl()!=null)
timeLimit = adata.getPublishedAssessment().getAssessmentAccessControl().getTimeLimit();
if (timeLimit!=null && timeLimit.intValue()>0){
UpdateTimerListener l3 = new UpdateTimerListener();
l3.processAction(null);
}
reload = true;
return "takeAssessment";
}
|
diff --git a/app/src/processing/app/Editor.java b/app/src/processing/app/Editor.java
index b62fb96c..405b16b3 100644
--- a/app/src/processing/app/Editor.java
+++ b/app/src/processing/app/Editor.java
@@ -1,2783 +1,2785 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-09 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app;
import processing.app.debug.*;
import processing.app.syntax.*;
import processing.app.tools.*;
import processing.core.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.print.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.zip.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;
import gnu.io.*;
/**
* Main editor panel for the Processing Development Environment.
*/
@SuppressWarnings("serial")
public class Editor extends JFrame implements RunnerListener {
Base base;
// otherwise, if the window is resized with the message label
// set to blank, it's preferredSize() will be fukered
static protected final String EMPTY =
" " +
" " +
" ";
/** Command on Mac OS X, Ctrl on Windows and Linux */
static final int SHORTCUT_KEY_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/** Command-W on Mac OS X, Ctrl-W on Windows and Linux */
static final KeyStroke WINDOW_CLOSE_KEYSTROKE =
KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK);
/** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */
static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK |
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/**
* true if this file has not yet been given a name by the user
*/
boolean untitled;
PageFormat pageFormat;
PrinterJob printerJob;
// file, sketch, and tools menus for re-inserting items
JMenu fileMenu;
JMenu sketchMenu;
JMenu toolsMenu;
int numTools = 0;
EditorToolbar toolbar;
// these menus are shared so that they needn't be rebuilt for all windows
// each time a sketch is created, renamed, or moved.
static JMenu toolbarMenu;
static JMenu sketchbookMenu;
static JMenu examplesMenu;
static JMenu importMenu;
// these menus are shared so that the board and serial port selections
// are the same for all windows (since the board and serial port that are
// actually used are determined by the preferences, which are shared)
static JMenu boardsMenu;
static JMenu serialMenu;
static SerialMenuListener serialMenuListener;
static SerialMonitor serialMonitor;
EditorHeader header;
EditorStatus status;
EditorConsole console;
JSplitPane splitPane;
JPanel consolePanel;
JLabel lineNumberComponent;
// currently opened program
Sketch sketch;
EditorLineStatus lineStatus;
//JEditorPane editorPane;
JEditTextArea textarea;
EditorListener listener;
// runtime information and window placement
Point sketchWindowLocation;
//Runner runtime;
JMenuItem exportAppItem;
JMenuItem saveMenuItem;
JMenuItem saveAsMenuItem;
boolean running;
//boolean presenting;
boolean uploading;
// undo fellers
JMenuItem undoItem, redoItem;
protected UndoAction undoAction;
protected RedoAction redoAction;
UndoManager undo;
// used internally, and only briefly
CompoundEdit compoundEdit;
FindReplace find;
Runnable runHandler;
Runnable presentHandler;
Runnable stopHandler;
Runnable exportHandler;
Runnable exportAppHandler;
public Editor(Base ibase, String path, int[] location) {
super("Arduino");
this.base = ibase;
Base.setIcon(this);
// Install default actions for Run, Present, etc.
resetHandlers();
// add listener to handle window close box hit event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
base.handleClose(Editor.this);
}
});
// don't close the window when clicked, the app will take care
// of that via the handleQuitInternal() methods
// http://dev.processing.org/bugs/show_bug.cgi?id=440
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// When bringing a window to front, let the Base know
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
// System.err.println("activate"); // not coming through
base.handleActivated(Editor.this);
// re-add the sub-menus that are shared by all windows
fileMenu.insert(sketchbookMenu, 2);
fileMenu.insert(examplesMenu, 3);
sketchMenu.insert(importMenu, 4);
toolsMenu.insert(boardsMenu, numTools);
toolsMenu.insert(serialMenu, numTools + 1);
}
// added for 1.0.5
// http://dev.processing.org/bugs/show_bug.cgi?id=1260
public void windowDeactivated(WindowEvent e) {
// System.err.println("deactivate"); // not coming through
fileMenu.remove(sketchbookMenu);
fileMenu.remove(examplesMenu);
sketchMenu.remove(importMenu);
toolsMenu.remove(boardsMenu);
toolsMenu.remove(serialMenu);
}
});
//PdeKeywords keywords = new PdeKeywords();
//sketchbook = new Sketchbook(this);
- if (serialMonitor == null)
+ if (serialMonitor == null) {
serialMonitor = new SerialMonitor(Preferences.get("serial.port"));
+ serialMonitor.setIconImage(getIconImage());
+ }
buildMenuBar();
// For rev 0120, placing things inside a JPanel
Container contentPain = getContentPane();
contentPain.setLayout(new BorderLayout());
JPanel pain = new JPanel();
pain.setLayout(new BorderLayout());
contentPain.add(pain, BorderLayout.CENTER);
Box box = Box.createVerticalBox();
Box upper = Box.createVerticalBox();
if (toolbarMenu == null) {
toolbarMenu = new JMenu();
base.rebuildToolbarMenu(toolbarMenu);
}
toolbar = new EditorToolbar(this, toolbarMenu);
upper.add(toolbar);
header = new EditorHeader(this);
upper.add(header);
textarea = new JEditTextArea(new PdeTextAreaDefaults());
textarea.setRightClickPopup(new TextAreaPopup());
textarea.setHorizontalOffset(6);
// assemble console panel, consisting of status area and the console itself
consolePanel = new JPanel();
consolePanel.setLayout(new BorderLayout());
status = new EditorStatus(this);
consolePanel.add(status, BorderLayout.NORTH);
console = new EditorConsole(this);
// windows puts an ugly border on this guy
console.setBorder(null);
consolePanel.add(console, BorderLayout.CENTER);
lineStatus = new EditorLineStatus(textarea);
consolePanel.add(lineStatus, BorderLayout.SOUTH);
upper.add(textarea);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
upper, consolePanel);
splitPane.setOneTouchExpandable(true);
// repaint child panes while resizing
splitPane.setContinuousLayout(true);
// if window increases in size, give all of increase to
// the textarea in the uppper pane
splitPane.setResizeWeight(1D);
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
splitPane.setBorder(null);
// the default size on windows is too small and kinda ugly
int dividerSize = Preferences.getInteger("editor.divider.size");
if (dividerSize != 0) {
splitPane.setDividerSize(dividerSize);
}
splitPane.setMinimumSize(new Dimension(600, 400));
box.add(splitPane);
// hopefully these are no longer needed w/ swing
// (har har har.. that was wishful thinking)
listener = new EditorListener(this, textarea);
pain.add(box);
// get shift down/up events so we can show the alt version of toolbar buttons
textarea.addKeyListener(toolbar);
pain.setTransferHandler(new FileDropHandler());
// System.out.println("t1");
// Finish preparing Editor (formerly found in Base)
pack();
// System.out.println("t2");
// Set the window bounds and the divider location before setting it visible
setPlacement(location);
// If the window is resized too small this will resize it again to the
// minimums. Adapted by Chris Lonnen from comments here:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4320050
// as a fix for http://dev.processing.org/bugs/show_bug.cgi?id=25
final int minW = Preferences.getInteger("editor.window.width.min");
final int minH = Preferences.getInteger("editor.window.height.min");
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(ComponentEvent event) {
setSize((getWidth() < minW) ? minW : getWidth(),
(getHeight() < minH) ? minH : getHeight());
}
});
// System.out.println("t3");
// Bring back the general options for the editor
applyPreferences();
// System.out.println("t4");
// Open the document that was passed in
boolean loaded = handleOpenInternal(path);
if (!loaded) sketch = null;
// System.out.println("t5");
// All set, now show the window
//setVisible(true);
}
/**
* Handles files dragged & dropped from the desktop and into the editor
* window. Dragging files into the editor window is the same as using
* "Sketch → Add File" for each file.
*/
class FileDropHandler extends TransferHandler {
public boolean canImport(JComponent dest, DataFlavor[] flavors) {
return true;
}
@SuppressWarnings("unchecked")
public boolean importData(JComponent src, Transferable transferable) {
int successful = 0;
try {
DataFlavor uriListFlavor =
new DataFlavor("text/uri-list;class=java.lang.String");
if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
java.util.List list = (java.util.List)
transferable.getTransferData(DataFlavor.javaFileListFlavor);
for (int i = 0; i < list.size(); i++) {
File file = (File) list.get(i);
if (sketch.addFile(file)) {
successful++;
}
}
} else if (transferable.isDataFlavorSupported(uriListFlavor)) {
// Some platforms (Mac OS X and Linux, when this began) preferred
// this method of moving files.
String data = (String)transferable.getTransferData(uriListFlavor);
String[] pieces = PApplet.splitTokens(data, "\r\n");
for (int i = 0; i < pieces.length; i++) {
if (pieces[i].startsWith("#")) continue;
String path = null;
if (pieces[i].startsWith("file:///")) {
path = pieces[i].substring(7);
} else if (pieces[i].startsWith("file:/")) {
path = pieces[i].substring(5);
}
if (sketch.addFile(new File(path))) {
successful++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
if (successful == 0) {
statusError("No files were added to the sketch.");
} else if (successful == 1) {
statusNotice("One file added to the sketch.");
} else {
statusNotice(successful + " files added to the sketch.");
}
return true;
}
}
protected void setPlacement(int[] location) {
setBounds(location[0], location[1], location[2], location[3]);
if (location[4] != 0) {
splitPane.setDividerLocation(location[4]);
}
}
protected int[] getPlacement() {
int[] location = new int[5];
// Get the dimensions of the Frame
Rectangle bounds = getBounds();
location[0] = bounds.x;
location[1] = bounds.y;
location[2] = bounds.width;
location[3] = bounds.height;
// Get the current placement of the divider
location[4] = splitPane.getDividerLocation();
return location;
}
/**
* Hack for #@#)$(* Mac OS X 10.2.
* <p/>
* This appears to only be required on OS X 10.2, and is not
* even being called on later versions of OS X or Windows.
*/
// public Dimension getMinimumSize() {
// //System.out.println("getting minimum size");
// return new Dimension(500, 550);
// }
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Read and apply new values from the preferences, either because
* the app is just starting up, or the user just finished messing
* with things in the Preferences window.
*/
protected void applyPreferences() {
// apply the setting for 'use external editor'
boolean external = Preferences.getBoolean("editor.external");
textarea.setEditable(!external);
saveMenuItem.setEnabled(!external);
saveAsMenuItem.setEnabled(!external);
TextAreaPainter painter = textarea.getPainter();
if (external) {
// disable line highlight and turn off the caret when disabling
Color color = Theme.getColor("editor.external.bgcolor");
painter.setBackground(color);
painter.setLineHighlightEnabled(false);
textarea.setCaretVisible(false);
} else {
Color color = Theme.getColor("editor.bgcolor");
painter.setBackground(color);
boolean highlight = Preferences.getBoolean("editor.linehighlight");
painter.setLineHighlightEnabled(highlight);
textarea.setCaretVisible(true);
}
// apply changes to the font size for the editor
//TextAreaPainter painter = textarea.getPainter();
painter.setFont(Preferences.getFont("editor.font"));
//Font font = painter.getFont();
//textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36));
// in case tab expansion stuff has changed
listener.applyPreferences();
// in case moved to a new location
// For 0125, changing to async version (to be implemented later)
//sketchbook.rebuildMenus();
// For 0126, moved into Base, which will notify all editors.
//base.rebuildMenusAsync();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
protected void buildMenuBar() {
JMenuBar menubar = new JMenuBar();
menubar = new JMenuBar();
menubar.add(buildFileMenu());
menubar.add(buildEditMenu());
menubar.add(buildSketchMenu());
menubar.add(buildToolsMenu());
menubar.add(buildHelpMenu());
setJMenuBar(menubar);
}
protected JMenu buildFileMenu() {
JMenuItem item;
fileMenu = new JMenu("File");
item = newJMenuItem("New", 'N');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleNew();
}
});
fileMenu.add(item);
item = Editor.newJMenuItem("Open...", 'O');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleOpenPrompt();
}
});
fileMenu.add(item);
if (sketchbookMenu == null) {
sketchbookMenu = new JMenu("Sketchbook");
base.rebuildSketchbookMenu(sketchbookMenu);
}
fileMenu.add(sketchbookMenu);
if (examplesMenu == null) {
examplesMenu = new JMenu("Examples");
base.rebuildExamplesMenu(examplesMenu);
}
fileMenu.add(examplesMenu);
item = Editor.newJMenuItem("Close", 'W');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleClose(Editor.this);
}
});
fileMenu.add(item);
saveMenuItem = newJMenuItem("Save", 'S');
saveMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSave(false);
}
});
fileMenu.add(saveMenuItem);
saveAsMenuItem = newJMenuItemShift("Save As...", 'S');
saveAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSaveAs();
}
});
fileMenu.add(saveAsMenuItem);
item = newJMenuItem("Upload", 'U');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleExport(false);
}
});
fileMenu.add(item);
item = newJMenuItemShift("Upload Using Programmer", 'U');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleExport(true);
}
});
fileMenu.add(item);
fileMenu.addSeparator();
item = newJMenuItemShift("Page Setup", 'P');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePageSetup();
}
});
fileMenu.add(item);
item = newJMenuItem("Print", 'P');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePrint();
}
});
fileMenu.add(item);
// macosx already has its own preferences and quit menu
if (!Base.isMacOS()) {
fileMenu.addSeparator();
item = newJMenuItem("Preferences", ',');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handlePrefs();
}
});
fileMenu.add(item);
fileMenu.addSeparator();
item = newJMenuItem("Quit", 'Q');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleQuit();
}
});
fileMenu.add(item);
}
return fileMenu;
}
protected JMenu buildSketchMenu() {
JMenuItem item;
sketchMenu = new JMenu("Sketch");
item = newJMenuItem("Verify / Compile", 'R');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleRun(false);
}
});
sketchMenu.add(item);
// item = newJMenuItemShift("Verify / Compile (verbose)", 'R');
// item.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// handleRun(true);
// }
// });
// sketchMenu.add(item);
// item = new JMenuItem("Stop");
// item.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// handleStop();
// }
// });
// sketchMenu.add(item);
sketchMenu.addSeparator();
if (importMenu == null) {
importMenu = new JMenu("Import Library...");
base.rebuildImportMenu(importMenu);
}
sketchMenu.add(importMenu);
item = newJMenuItem("Show Sketch Folder", 'K');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openFolder(sketch.getFolder());
}
});
sketchMenu.add(item);
item.setEnabled(Base.openFolderAvailable());
item = new JMenuItem("Add File...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sketch.handleAddFile();
}
});
sketchMenu.add(item);
return sketchMenu;
}
protected JMenu buildToolsMenu() {
toolsMenu = new JMenu("Tools");
JMenu menu = toolsMenu;
JMenuItem item;
addInternalTools(menu);
item = newJMenuItemShift("Serial Monitor", 'M');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSerial();
}
});
menu.add(item);
addTools(menu, Base.getToolsFolder());
File sketchbookTools = new File(Base.getSketchbookFolder(), "tools");
addTools(menu, sketchbookTools);
menu.addSeparator();
numTools = menu.getItemCount();
// XXX: DAM: these should probably be implemented using the Tools plugin
// API, if possible (i.e. if it supports custom actions, etc.)
if (boardsMenu == null) {
boardsMenu = new JMenu("Board");
base.rebuildBoardsMenu(boardsMenu);
}
menu.add(boardsMenu);
if (serialMenuListener == null)
serialMenuListener = new SerialMenuListener();
if (serialMenu == null)
serialMenu = new JMenu("Serial Port");
populateSerialMenu();
menu.add(serialMenu);
menu.addSeparator();
JMenu programmerMenu = new JMenu("Programmer");
base.rebuildProgrammerMenu(programmerMenu);
menu.add(programmerMenu);
item = new JMenuItem("Burn Bootloader");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleBurnBootloader();
}
});
menu.add(item);
menu.addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent e) {}
public void menuDeselected(MenuEvent e) {}
public void menuSelected(MenuEvent e) {
//System.out.println("Tools menu selected.");
populateSerialMenu();
}
});
return menu;
}
protected void addTools(JMenu menu, File sourceFolder) {
HashMap<String, JMenuItem> toolItems = new HashMap<String, JMenuItem>();
File[] folders = sourceFolder.listFiles(new FileFilter() {
public boolean accept(File folder) {
if (folder.isDirectory()) {
//System.out.println("checking " + folder);
File subfolder = new File(folder, "tool");
return subfolder.exists();
}
return false;
}
});
if (folders == null || folders.length == 0) {
return;
}
for (int i = 0; i < folders.length; i++) {
File toolDirectory = new File(folders[i], "tool");
try {
// add dir to classpath for .classes
//urlList.add(toolDirectory.toURL());
// add .jar files to classpath
File[] archives = toolDirectory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.toLowerCase().endsWith(".jar") ||
name.toLowerCase().endsWith(".zip"));
}
});
URL[] urlList = new URL[archives.length];
for (int j = 0; j < urlList.length; j++) {
urlList[j] = archives[j].toURI().toURL();
}
URLClassLoader loader = new URLClassLoader(urlList);
String className = null;
for (int j = 0; j < archives.length; j++) {
className = findClassInZipFile(folders[i].getName(), archives[j]);
if (className != null) break;
}
/*
// Alternatively, could use manifest files with special attributes:
// http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html
// Example code for loading from a manifest file:
// http://forums.sun.com/thread.jspa?messageID=3791501
File infoFile = new File(toolDirectory, "tool.txt");
if (!infoFile.exists()) continue;
String[] info = PApplet.loadStrings(infoFile);
//Main-Class: org.poo.shoe.AwesomerTool
//String className = folders[i].getName();
String className = null;
for (int k = 0; k < info.length; k++) {
if (info[k].startsWith(";")) continue;
String[] pieces = PApplet.splitTokens(info[k], ": ");
if (pieces.length == 2) {
if (pieces[0].equals("Main-Class")) {
className = pieces[1];
}
}
}
*/
// If no class name found, just move on.
if (className == null) continue;
Class<?> toolClass = Class.forName(className, true, loader);
final Tool tool = (Tool) toolClass.newInstance();
tool.init(Editor.this);
String title = tool.getMenuTitle();
JMenuItem item = new JMenuItem(title);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(tool);
//new Thread(tool).start();
}
});
//menu.add(item);
toolItems.put(title, item);
} catch (Exception e) {
e.printStackTrace();
}
}
ArrayList<String> toolList = new ArrayList<String>(toolItems.keySet());
if (toolList.size() == 0) return;
menu.addSeparator();
Collections.sort(toolList);
for (String title : toolList) {
menu.add((JMenuItem) toolItems.get(title));
}
}
protected String findClassInZipFile(String base, File file) {
// Class file to search for
String classFileName = "/" + base + ".class";
try {
ZipFile zipFile = new ZipFile(file);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (!entry.isDirectory()) {
String name = entry.getName();
//System.out.println("entry: " + name);
if (name.endsWith(classFileName)) {
//int slash = name.lastIndexOf('/');
//String packageName = (slash == -1) ? "" : name.substring(0, slash);
// Remove .class and convert slashes to periods.
return name.substring(0, name.length() - 6).replace('/', '.');
}
}
}
} catch (IOException e) {
//System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")");
e.printStackTrace();
}
return null;
}
protected JMenuItem createToolMenuItem(String className) {
try {
Class<?> toolClass = Class.forName(className);
final Tool tool = (Tool) toolClass.newInstance();
JMenuItem item = new JMenuItem(tool.getMenuTitle());
tool.init(Editor.this);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(tool);
}
});
return item;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected JMenu addInternalTools(JMenu menu) {
JMenuItem item;
item = createToolMenuItem("processing.app.tools.AutoFormat");
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers));
menu.add(item);
//menu.add(createToolMenuItem("processing.app.tools.CreateFont"));
//menu.add(createToolMenuItem("processing.app.tools.ColorSelector"));
menu.add(createToolMenuItem("processing.app.tools.Archiver"));
menu.add(createToolMenuItem("processing.app.tools.FixEncoding"));
// // These are temporary entries while Android mode is being worked out.
// // The mode will not be in the tools menu, and won't involve a cmd-key
// if (!Base.RELEASE) {
// item = createToolMenuItem("processing.app.tools.android.AndroidTool");
// item.setAccelerator(KeyStroke.getKeyStroke('D', modifiers));
// menu.add(item);
// menu.add(createToolMenuItem("processing.app.tools.android.Reset"));
// }
return menu;
}
class SerialMenuListener implements ActionListener {
//public SerialMenuListener() { }
public void actionPerformed(ActionEvent e) {
selectSerialPort(((JCheckBoxMenuItem)e.getSource()).getText());
base.onBoardOrPortChange();
}
/*
public void actionPerformed(ActionEvent e) {
System.out.println(e.getSource());
String name = e.getActionCommand();
PdeBase.properties.put("serial.port", name);
System.out.println("set to " + get("serial.port"));
//editor.skOpen(path + File.separator + name, name);
// need to push "serial.port" into PdeBase.properties
}
*/
}
protected void selectSerialPort(String name) {
if(serialMenu == null) {
System.out.println("serialMenu is null");
return;
}
if (name == null) {
System.out.println("name is null");
return;
}
JCheckBoxMenuItem selection = null;
for (int i = 0; i < serialMenu.getItemCount(); i++) {
JCheckBoxMenuItem item = ((JCheckBoxMenuItem)serialMenu.getItem(i));
if (item == null) {
System.out.println("name is null");
continue;
}
item.setState(false);
if (name.equals(item.getText())) selection = item;
}
if (selection != null) selection.setState(true);
//System.out.println(item.getLabel());
Preferences.set("serial.port", name);
serialMonitor.closeSerialPort();
serialMonitor.setVisible(false);
serialMonitor = new SerialMonitor(Preferences.get("serial.port"));
//System.out.println("set to " + get("serial.port"));
}
protected void populateSerialMenu() {
// getting list of ports
JMenuItem rbMenuItem;
//System.out.println("Clearing serial port menu.");
serialMenu.removeAll();
boolean empty = true;
try
{
for (Enumeration enumeration = CommPortIdentifier.getPortIdentifiers(); enumeration.hasMoreElements();)
{
CommPortIdentifier commportidentifier = (CommPortIdentifier)enumeration.nextElement();
//System.out.println("Found communication port: " + commportidentifier);
if (commportidentifier.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
//System.out.println("Adding port to serial port menu: " + commportidentifier);
String curr_port = commportidentifier.getName();
rbMenuItem = new JCheckBoxMenuItem(curr_port, curr_port.equals(Preferences.get("serial.port")));
rbMenuItem.addActionListener(serialMenuListener);
//serialGroup.add(rbMenuItem);
serialMenu.add(rbMenuItem);
empty = false;
}
}
if (!empty) {
//System.out.println("enabling the serialMenu");
serialMenu.setEnabled(true);
}
}
catch (Exception exception)
{
System.out.println("error retrieving port list");
exception.printStackTrace();
}
if (serialMenu.getItemCount() == 0) {
serialMenu.setEnabled(false);
}
//serialMenu.addSeparator();
//serialMenu.add(item);
}
protected JMenu buildHelpMenu() {
// To deal with a Mac OS X 10.5 bug, add an extra space after the name
// so that the OS doesn't try to insert its slow help menu.
JMenu menu = new JMenu("Help ");
JMenuItem item;
/*
// testing internal web server to serve up docs from a zip file
item = new JMenuItem("Web Server Test");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//WebServer ws = new WebServer();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
int port = WebServer.launch("/Users/fry/coconut/processing/build/shared/reference.zip");
Base.openURL("http://127.0.0.1:" + port + "/reference/setup_.html");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
});
menu.add(item);
*/
/*
item = new JMenuItem("Browser Test");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Base.openURL("http://processing.org/learning/gettingstarted/");
//JFrame browserFrame = new JFrame("Browser");
BrowserStartup bs = new BrowserStartup("jar:file:/Users/fry/coconut/processing/build/shared/reference.zip!/reference/setup_.html");
bs.initUI();
bs.launch();
}
});
menu.add(item);
*/
item = new JMenuItem("Getting Started");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showGettingStarted();
}
});
menu.add(item);
item = new JMenuItem("Environment");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showEnvironment();
}
});
menu.add(item);
item = new JMenuItem("Troubleshooting");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showTroubleshooting();
}
});
menu.add(item);
item = new JMenuItem("Reference");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showReference();
}
});
menu.add(item);
item = newJMenuItemShift("Find in Reference", 'F');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (textarea.isSelectionActive()) {
handleFindReference();
}
}
});
menu.add(item);
item = new JMenuItem("Frequently Asked Questions");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showFAQ();
}
});
menu.add(item);
item = new JMenuItem("Visit Arduino.cc");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openURL("http://arduino.cc/");
}
});
menu.add(item);
// macosx already has its own about menu
if (!Base.isMacOS()) {
menu.addSeparator();
item = new JMenuItem("About Arduino");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleAbout();
}
});
menu.add(item);
}
return menu;
}
protected JMenu buildEditMenu() {
JMenu menu = new JMenu("Edit");
JMenuItem item;
undoItem = newJMenuItem("Undo", 'Z');
undoItem.addActionListener(undoAction = new UndoAction());
menu.add(undoItem);
redoItem = newJMenuItem("Redo", 'Y');
redoItem.addActionListener(redoAction = new RedoAction());
menu.add(redoItem);
menu.addSeparator();
// TODO "cut" and "copy" should really only be enabled
// if some text is currently selected
item = newJMenuItem("Cut", 'X');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCut();
}
});
menu.add(item);
item = newJMenuItem("Copy", 'C');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.copy();
}
});
menu.add(item);
item = newJMenuItemShift("Copy for Forum", 'C');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
new DiscourseFormat(Editor.this, false).show();
// }
// });
}
});
menu.add(item);
item = newJMenuItemAlt("Copy as HTML", 'C');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
new DiscourseFormat(Editor.this, true).show();
// }
// });
}
});
menu.add(item);
item = newJMenuItem("Paste", 'V');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.paste();
sketch.setModified(true);
}
});
menu.add(item);
item = newJMenuItem("Select All", 'A');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.selectAll();
}
});
menu.add(item);
menu.addSeparator();
item = newJMenuItem("Comment/Uncomment", '/');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCommentUncomment();
}
});
menu.add(item);
item = newJMenuItem("Increase Indent", ']');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(true);
}
});
menu.add(item);
item = newJMenuItem("Decrease Indent", '[');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(false);
}
});
menu.add(item);
menu.addSeparator();
item = newJMenuItem("Find...", 'F');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find == null) {
find = new FindReplace(Editor.this);
}
//new FindReplace(Editor.this).show();
find.setVisible(true);
//find.setVisible(true);
}
});
menu.add(item);
// TODO find next should only be enabled after a
// search has actually taken place
item = newJMenuItem("Find Next", 'G');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find != null) {
//find.find(true);
//FindReplace find = new FindReplace(Editor.this); //.show();
find.find(true);
}
}
});
menu.add(item);
return menu;
}
/**
* A software engineer, somewhere, needs to have his abstraction
* taken away. In some countries they jail or beat people for writing
* the sort of API that would require a five line helper function
* just to set the command key for a menu item.
*/
static public JMenuItem newJMenuItem(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers));
return menuItem;
}
/**
* Like newJMenuItem() but adds shift as a modifier for the key command.
*/
static public JMenuItem newJMenuItemShift(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
modifiers |= ActionEvent.SHIFT_MASK;
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers));
return menuItem;
}
/**
* Same as newJMenuItem(), but adds the ALT (on Linux and Windows)
* or OPTION (on Mac OS X) key as a modifier.
*/
static public JMenuItem newJMenuItemAlt(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
//int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
//menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers));
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK));
return menuItem;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
class UndoAction extends AbstractAction {
public UndoAction() {
super("Undo");
this.setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.undo();
} catch (CannotUndoException ex) {
//System.out.println("Unable to undo: " + ex);
//ex.printStackTrace();
}
updateUndoState();
redoAction.updateRedoState();
}
protected void updateUndoState() {
if (undo.canUndo()) {
this.setEnabled(true);
undoItem.setEnabled(true);
undoItem.setText(undo.getUndoPresentationName());
putValue(Action.NAME, undo.getUndoPresentationName());
if (sketch != null) {
sketch.setModified(true); // 0107
}
} else {
this.setEnabled(false);
undoItem.setEnabled(false);
undoItem.setText("Undo");
putValue(Action.NAME, "Undo");
if (sketch != null) {
sketch.setModified(false); // 0107
}
}
}
}
class RedoAction extends AbstractAction {
public RedoAction() {
super("Redo");
this.setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.redo();
} catch (CannotRedoException ex) {
//System.out.println("Unable to redo: " + ex);
//ex.printStackTrace();
}
updateRedoState();
undoAction.updateUndoState();
}
protected void updateRedoState() {
if (undo.canRedo()) {
redoItem.setEnabled(true);
redoItem.setText(undo.getRedoPresentationName());
putValue(Action.NAME, undo.getRedoPresentationName());
} else {
this.setEnabled(false);
redoItem.setEnabled(false);
redoItem.setText("Redo");
putValue(Action.NAME, "Redo");
}
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
// these will be done in a more generic way soon, more like:
// setHandler("action name", Runnable);
// but for the time being, working out the kinks of how many things to
// abstract from the editor in this fashion.
public void setHandlers(Runnable runHandler, Runnable presentHandler,
Runnable stopHandler,
Runnable exportHandler, Runnable exportAppHandler) {
this.runHandler = runHandler;
this.presentHandler = presentHandler;
this.stopHandler = stopHandler;
this.exportHandler = exportHandler;
this.exportAppHandler = exportAppHandler;
}
public void resetHandlers() {
runHandler = new DefaultRunHandler();
presentHandler = new DefaultPresentHandler();
stopHandler = new DefaultStopHandler();
exportHandler = new DefaultExportHandler();
exportAppHandler = new DefaultExportAppHandler();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Gets the current sketch object.
*/
public Sketch getSketch() {
return sketch;
}
/**
* Get the JEditTextArea object for use (not recommended). This should only
* be used in obscure cases that really need to hack the internals of the
* JEditTextArea. Most tools should only interface via the get/set functions
* found in this class. This will maintain compatibility with future releases,
* which will not use JEditTextArea.
*/
public JEditTextArea getTextArea() {
return textarea;
}
/**
* Get the contents of the current buffer. Used by the Sketch class.
*/
public String getText() {
return textarea.getText();
}
/**
* Get a range of text from the current buffer.
*/
public String getText(int start, int stop) {
return textarea.getText(start, stop - start);
}
/**
* Replace the entire contents of the front-most tab.
*/
public void setText(String what) {
startCompoundEdit();
textarea.setText(what);
stopCompoundEdit();
}
public void insertText(String what) {
startCompoundEdit();
int caret = getCaretOffset();
setSelection(caret, caret);
textarea.setSelectedText(what);
stopCompoundEdit();
}
/**
* Called to update the text but not switch to a different set of code
* (which would affect the undo manager).
*/
// public void setText2(String what, int start, int stop) {
// beginCompoundEdit();
// textarea.setText(what);
// endCompoundEdit();
//
// // make sure that a tool isn't asking for a bad location
// start = Math.max(0, Math.min(start, textarea.getDocumentLength()));
// stop = Math.max(0, Math.min(start, textarea.getDocumentLength()));
// textarea.select(start, stop);
//
// textarea.requestFocus(); // get the caret blinking
// }
public String getSelectedText() {
return textarea.getSelectedText();
}
public void setSelectedText(String what) {
textarea.setSelectedText(what);
}
public void setSelection(int start, int stop) {
// make sure that a tool isn't asking for a bad location
start = PApplet.constrain(start, 0, textarea.getDocumentLength());
stop = PApplet.constrain(stop, 0, textarea.getDocumentLength());
textarea.select(start, stop);
}
/**
* Get the position (character offset) of the caret. With text selected,
* this will be the last character actually selected, no matter the direction
* of the selection. That is, if the user clicks and drags to select lines
* 7 up to 4, then the caret position will be somewhere on line four.
*/
public int getCaretOffset() {
return textarea.getCaretPosition();
}
/**
* True if some text is currently selected.
*/
public boolean isSelectionActive() {
return textarea.isSelectionActive();
}
/**
* Get the beginning point of the current selection.
*/
public int getSelectionStart() {
return textarea.getSelectionStart();
}
/**
* Get the end point of the current selection.
*/
public int getSelectionStop() {
return textarea.getSelectionStop();
}
/**
* Get text for a specified line.
*/
public String getLineText(int line) {
return textarea.getLineText(line);
}
/**
* Replace the text on a specified line.
*/
public void setLineText(int line, String what) {
startCompoundEdit();
textarea.select(getLineStartOffset(line), getLineStopOffset(line));
textarea.setSelectedText(what);
stopCompoundEdit();
}
/**
* Get character offset for the start of a given line of text.
*/
public int getLineStartOffset(int line) {
return textarea.getLineStartOffset(line);
}
/**
* Get character offset for end of a given line of text.
*/
public int getLineStopOffset(int line) {
return textarea.getLineStopOffset(line);
}
/**
* Get the number of lines in the currently displayed buffer.
*/
public int getLineCount() {
return textarea.getLineCount();
}
/**
* Use before a manipulating text to group editing operations together as a
* single undo. Use stopCompoundEdit() once finished.
*/
public void startCompoundEdit() {
compoundEdit = new CompoundEdit();
}
/**
* Use with startCompoundEdit() to group edit operations in a single undo.
*/
public void stopCompoundEdit() {
compoundEdit.end();
undo.addEdit(compoundEdit);
undoAction.updateUndoState();
redoAction.updateRedoState();
compoundEdit = null;
}
public int getScrollPosition() {
return textarea.getScrollPosition();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Switch between tabs, this swaps out the Document object
* that's currently being manipulated.
*/
protected void setCode(SketchCode code) {
SyntaxDocument document = (SyntaxDocument) code.getDocument();
if (document == null) { // this document not yet inited
document = new SyntaxDocument();
code.setDocument(document);
// turn on syntax highlighting
document.setTokenMarker(new PdeKeywords());
// insert the program text into the document object
try {
document.insertString(0, code.getProgram(), null);
} catch (BadLocationException bl) {
bl.printStackTrace();
}
// set up this guy's own undo manager
// code.undo = new UndoManager();
// connect the undo listener to the editor
document.addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent e) {
if (compoundEdit != null) {
compoundEdit.addEdit(e.getEdit());
} else if (undo != null) {
undo.addEdit(e.getEdit());
undoAction.updateUndoState();
redoAction.updateRedoState();
}
}
});
}
// update the document object that's in use
textarea.setDocument(document,
code.getSelectionStart(), code.getSelectionStop(),
code.getScrollPosition());
textarea.requestFocus(); // get the caret blinking
this.undo = code.getUndo();
undoAction.updateUndoState();
redoAction.updateRedoState();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Implements Edit → Cut.
*/
public void handleCut() {
textarea.cut();
sketch.setModified(true);
}
/**
* Implements Edit → Copy.
*/
public void handleCopy() {
textarea.copy();
}
protected void handleDiscourseCopy() {
new DiscourseFormat(Editor.this, false).show();
}
protected void handleHTMLCopy() {
new DiscourseFormat(Editor.this, true).show();
}
/**
* Implements Edit → Paste.
*/
public void handlePaste() {
textarea.paste();
sketch.setModified(true);
}
/**
* Implements Edit → Select All.
*/
public void handleSelectAll() {
textarea.selectAll();
}
protected void handleCommentUncomment() {
startCompoundEdit();
int startLine = textarea.getSelectionStartLine();
int stopLine = textarea.getSelectionStopLine();
int lastLineStart = textarea.getLineStartOffset(stopLine);
int selectionStop = textarea.getSelectionStop();
// If the selection ends at the beginning of the last line,
// then don't (un)comment that line.
if (selectionStop == lastLineStart) {
// Though if there's no selection, don't do that
if (textarea.isSelectionActive()) {
stopLine--;
}
}
// If the text is empty, ignore the user.
// Also ensure that all lines are commented (not just the first)
// when determining whether to comment or uncomment.
int length = textarea.getDocumentLength();
boolean commented = true;
for (int i = startLine; commented && (i <= stopLine); i++) {
int pos = textarea.getLineStartOffset(i);
if (pos + 2 > length) {
commented = false;
} else {
// Check the first two characters to see if it's already a comment.
String begin = textarea.getText(pos, 2);
//System.out.println("begin is '" + begin + "'");
commented = begin.equals("//");
}
}
for (int line = startLine; line <= stopLine; line++) {
int location = textarea.getLineStartOffset(line);
if (commented) {
// remove a comment
textarea.select(location, location+2);
if (textarea.getSelectedText().equals("//")) {
textarea.setSelectedText("");
}
} else {
// add a comment
textarea.select(location, location);
textarea.setSelectedText("//");
}
}
// Subtract one from the end, otherwise selects past the current line.
// (Which causes subsequent calls to keep expanding the selection)
textarea.select(textarea.getLineStartOffset(startLine),
textarea.getLineStopOffset(stopLine) - 1);
stopCompoundEdit();
}
protected void handleIndentOutdent(boolean indent) {
int tabSize = Preferences.getInteger("editor.tabs.size");
String tabString = Editor.EMPTY.substring(0, tabSize);
startCompoundEdit();
int startLine = textarea.getSelectionStartLine();
int stopLine = textarea.getSelectionStopLine();
// If the selection ends at the beginning of the last line,
// then don't (un)comment that line.
int lastLineStart = textarea.getLineStartOffset(stopLine);
int selectionStop = textarea.getSelectionStop();
if (selectionStop == lastLineStart) {
// Though if there's no selection, don't do that
if (textarea.isSelectionActive()) {
stopLine--;
}
}
for (int line = startLine; line <= stopLine; line++) {
int location = textarea.getLineStartOffset(line);
if (indent) {
textarea.select(location, location);
textarea.setSelectedText(tabString);
} else { // outdent
textarea.select(location, location + tabSize);
// Don't eat code if it's not indented
if (textarea.getSelectedText().equals(tabString)) {
textarea.setSelectedText("");
}
}
}
// Subtract one from the end, otherwise selects past the current line.
// (Which causes subsequent calls to keep expanding the selection)
textarea.select(textarea.getLineStartOffset(startLine),
textarea.getLineStopOffset(stopLine) - 1);
stopCompoundEdit();
}
protected void handleFindReference() {
String text = textarea.getSelectedText().trim();
if (text.length() == 0) {
statusNotice("First select a word to find in the reference.");
} else {
String referenceFile = PdeKeywords.getReference(text);
//System.out.println("reference file is " + referenceFile);
if (referenceFile == null) {
statusNotice("No reference available for \"" + text + "\"");
} else {
Base.showReference(referenceFile + ".html");
}
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Implements Sketch → Run.
* @param verbose Set true to run with verbose output.
*/
public void handleRun(final boolean verbose) {
internalCloseRunner();
running = true;
toolbar.activate(EditorToolbar.RUN);
status.progress("Compiling sketch...");
// do this to advance/clear the terminal window / dos prompt / etc
for (int i = 0; i < 10; i++) System.out.println();
// clear the console on each run, unless the user doesn't want to
if (Preferences.getBoolean("console.auto_clear")) {
console.clear();
}
// Cannot use invokeLater() here, otherwise it gets
// placed on the event thread and causes a hang--bad idea all around.
new Thread(verbose ? presentHandler : runHandler).start();
}
// DAM: in Arduino, this is compile
class DefaultRunHandler implements Runnable {
public void run() {
try {
sketch.prepare();
sketch.build(false);
statusNotice("Done compiling.");
} catch (Exception e) {
status.unprogress();
statusError(e);
}
status.unprogress();
toolbar.deactivate(EditorToolbar.RUN);
}
}
// DAM: in Arduino, this is compile (with verbose output)
class DefaultPresentHandler implements Runnable {
public void run() {
try {
sketch.prepare();
sketch.build(true);
statusNotice("Done compiling.");
} catch (Exception e) {
status.unprogress();
statusError(e);
}
status.unprogress();
toolbar.deactivate(EditorToolbar.RUN);
}
}
class DefaultStopHandler implements Runnable {
public void run() {
try {
// DAM: we should try to kill the compilation or upload process here.
} catch (Exception e) {
statusError(e);
}
}
}
/**
* Set the location of the sketch run window. Used by Runner to update the
* Editor about window drag events while the sketch is running.
*/
public void setSketchLocation(Point p) {
sketchWindowLocation = p;
}
/**
* Get the last location of the sketch's run window. Used by Runner to make
* the window show up in the same location as when it was last closed.
*/
public Point getSketchLocation() {
return sketchWindowLocation;
}
/**
* Implements Sketch → Stop, or pressing Stop on the toolbar.
*/
public void handleStop() { // called by menu or buttons
// toolbar.activate(EditorToolbar.STOP);
internalCloseRunner();
toolbar.deactivate(EditorToolbar.RUN);
// toolbar.deactivate(EditorToolbar.STOP);
// focus the PDE again after quitting presentation mode [toxi 030903]
toFront();
}
/**
* Deactivate the Run button. This is called by Runner to notify that the
* sketch has stopped running, usually in response to an error (or maybe
* the sketch completing and exiting?) Tools should not call this function.
* To initiate a "stop" action, call handleStop() instead.
*/
public void internalRunnerClosed() {
running = false;
toolbar.deactivate(EditorToolbar.RUN);
}
/**
* Handle internal shutdown of the runner.
*/
public void internalCloseRunner() {
running = false;
if (stopHandler != null)
try {
stopHandler.run();
} catch (Exception e) { }
sketch.cleanup();
}
/**
* Check if the sketch is modified and ask user to save changes.
* @return false if canceling the close/quit operation
*/
protected boolean checkModified() {
if (!sketch.isModified()) return true;
// As of Processing 1.0.10, this always happens immediately.
// http://dev.processing.org/bugs/show_bug.cgi?id=1456
String prompt = "Save changes to " + sketch.getName() + "? ";
if (!Base.isMacOS()) {
int result =
JOptionPane.showConfirmDialog(this, prompt, "Close",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
return handleSave(true);
} else if (result == JOptionPane.NO_OPTION) {
return true; // ok to continue
} else if (result == JOptionPane.CANCEL_OPTION) {
return false;
} else {
throw new IllegalStateException();
}
} else {
// This code is disabled unless Java 1.5 is being used on Mac OS X
// because of a Java bug that prevents the initial value of the
// dialog from being set properly (at least on my MacBook Pro).
// The bug causes the "Don't Save" option to be the highlighted,
// blinking, default. This sucks. But I'll tell you what doesn't
// suck--workarounds for the Mac and Apple's snobby attitude about it!
// I think it's nifty that they treat their developers like dirt.
// Pane formatting adapted from the quaqua guide
// http://www.randelshofer.ch/quaqua/guide/joptionpane.html
JOptionPane pane =
new JOptionPane("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Do you want to save changes to this sketch<BR>" +
" before closing?</b>" +
"<p>If you don't save, your changes will be lost.",
JOptionPane.QUESTION_MESSAGE);
String[] options = new String[] {
"Save", "Cancel", "Don't Save"
};
pane.setOptions(options);
// highlight the safest option ala apple hig
pane.setInitialValue(options[0]);
// on macosx, setting the destructive property places this option
// away from the others at the lefthand side
pane.putClientProperty("Quaqua.OptionPane.destructiveOption",
new Integer(2));
JDialog dialog = pane.createDialog(this, null);
dialog.setVisible(true);
Object result = pane.getValue();
if (result == options[0]) { // save (and close/quit)
return handleSave(true);
} else if (result == options[2]) { // don't save (still close/quit)
return true;
} else { // cancel?
return false;
}
}
}
/**
* Open a sketch from a particular path, but don't check to save changes.
* Used by Sketch.saveAs() to re-open a sketch after the "Save As"
*/
protected void handleOpenUnchecked(String path, int codeIndex,
int selStart, int selStop, int scrollPos) {
internalCloseRunner();
handleOpenInternal(path);
// Replacing a document that may be untitled. If this is an actual
// untitled document, then editor.untitled will be set by Base.
untitled = false;
sketch.setCurrentCode(codeIndex);
textarea.select(selStart, selStop);
textarea.setScrollPosition(scrollPos);
}
/**
* Second stage of open, occurs after having checked to see if the
* modifications (if any) to the previous sketch need to be saved.
*/
protected boolean handleOpenInternal(String path) {
// rename .pde files to .ino
File[] oldFiles = (new File(path)).getParentFile().listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.toLowerCase().endsWith(".pde"));
}
});
if (oldFiles != null && oldFiles.length > 0) {
if (!Preferences.getBoolean("editor.update_extension")) {
Object[] options = { "OK", "Cancel" };
String prompt =
"In Arduino 1.0, the file extension for sketches changed\n" +
"from \".pde\" to \".ino\". This version of the software only\n" +
"supports the new extension. Rename the files in this sketch\n" +
"(and future sketches) and continue?";
int result = JOptionPane.showOptionDialog(this,
prompt,
"New extension",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result != JOptionPane.YES_OPTION) {
return false;
}
Preferences.setBoolean("editor.update_extension", true);
}
for (int i = 0; i < oldFiles.length; i++) {
String oldPath = oldFiles[i].getPath();
File newFile = new File(oldPath.substring(0, oldPath.length() - 4) + ".ino");
try {
Base.copyFile(oldFiles[i], newFile);
} catch (IOException e) {
Base.showWarning("Error", "Could not copy to a proper location.", e);
return false;
}
// remove the original file, so user doesn't get confused
oldFiles[i].delete();
// update with the new path
if (oldFiles[i].compareTo(new File(path)) == 0) {
path = newFile.getAbsolutePath();
}
}
}
// check to make sure that this .pde file is
// in a folder of the same name
File file = new File(path);
File parentFile = new File(file.getParent());
String parentName = parentFile.getName();
String pdeName = parentName + ".ino";
File altFile = new File(file.getParent(), pdeName);
if (pdeName.equals(file.getName())) {
// no beef with this guy
} else if (altFile.exists()) {
// user selected a .java from the same sketch,
// but open the .pde instead
path = altFile.getAbsolutePath();
//System.out.println("found alt file in same folder");
} else if (!path.endsWith(".ino")) {
Base.showWarning("Bad file selected",
"Processing can only open its own sketches\n" +
"and other files ending in .ino", null);
return false;
} else {
String properParent =
file.getName().substring(0, file.getName().length() - 4);
Object[] options = { "OK", "Cancel" };
String prompt =
"The file \"" + file.getName() + "\" needs to be inside\n" +
"a sketch folder named \"" + properParent + "\".\n" +
"Create this folder, move the file, and continue?";
int result = JOptionPane.showOptionDialog(this,
prompt,
"Moving",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.YES_OPTION) {
// create properly named folder
File properFolder = new File(file.getParent(), properParent);
if (properFolder.exists()) {
Base.showWarning("Error",
"A folder named \"" + properParent + "\" " +
"already exists. Can't open sketch.", null);
return false;
}
if (!properFolder.mkdirs()) {
//throw new IOException("Couldn't create sketch folder");
Base.showWarning("Error",
"Could not create the sketch folder.", null);
return false;
}
// copy the sketch inside
File properPdeFile = new File(properFolder, file.getName());
File origPdeFile = new File(path);
try {
Base.copyFile(origPdeFile, properPdeFile);
} catch (IOException e) {
Base.showWarning("Error", "Could not copy to a proper location.", e);
return false;
}
// remove the original file, so user doesn't get confused
origPdeFile.delete();
// update with the new path
path = properPdeFile.getAbsolutePath();
} else if (result == JOptionPane.NO_OPTION) {
return false;
}
}
try {
sketch = new Sketch(this, path);
} catch (IOException e) {
Base.showWarning("Error", "Could not create the sketch.", e);
return false;
}
header.rebuild();
// Set the title of the window to "sketch_070752a - Processing 0126"
setTitle(sketch.getName() + " | Arduino " + Base.VERSION_NAME);
// Disable untitled setting from previous document, if any
untitled = false;
// Store information on who's open and running
// (in case there's a crash or something that can't be recovered)
base.storeSketches();
Preferences.save();
// opening was successful
return true;
// } catch (Exception e) {
// e.printStackTrace();
// statusError(e);
// return false;
// }
}
/**
* Actually handle the save command. If 'immediately' is set to false,
* this will happen in another thread so that the message area
* will update and the save button will stay highlighted while the
* save is happening. If 'immediately' is true, then it will happen
* immediately. This is used during a quit, because invokeLater()
* won't run properly while a quit is happening. This fixes
* <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=276">Bug 276</A>.
*/
public boolean handleSave(boolean immediately) {
//stopRunner();
handleStop(); // 0136
if (untitled) {
return handleSaveAs();
// need to get the name, user might also cancel here
} else if (immediately) {
handleSave2();
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
handleSave2();
}
});
}
return true;
}
protected void handleSave2() {
toolbar.activate(EditorToolbar.SAVE);
statusNotice("Saving...");
try {
if (sketch.save()) {
statusNotice("Done Saving.");
} else {
statusEmpty();
}
// rebuild sketch menu in case a save-as was forced
// Disabling this for 0125, instead rebuild the menu inside
// the Save As method of the Sketch object, since that's the
// only one who knows whether something was renamed.
//sketchbook.rebuildMenus();
//sketchbook.rebuildMenusAsync();
} catch (Exception e) {
// show the error as a message in the window
statusError(e);
// zero out the current action,
// so that checkModified2 will just do nothing
//checkModifiedMode = 0;
// this is used when another operation calls a save
}
//toolbar.clear();
toolbar.deactivate(EditorToolbar.SAVE);
}
public boolean handleSaveAs() {
//stopRunner(); // formerly from 0135
handleStop();
toolbar.activate(EditorToolbar.SAVE);
//SwingUtilities.invokeLater(new Runnable() {
//public void run() {
statusNotice("Saving...");
try {
if (sketch.saveAs()) {
statusNotice("Done Saving.");
// Disabling this for 0125, instead rebuild the menu inside
// the Save As method of the Sketch object, since that's the
// only one who knows whether something was renamed.
//sketchbook.rebuildMenusAsync();
} else {
statusNotice("Save Canceled.");
return false;
}
} catch (Exception e) {
// show the error as a message in the window
statusError(e);
} finally {
// make sure the toolbar button deactivates
toolbar.deactivate(EditorToolbar.SAVE);
}
return true;
}
public boolean serialPrompt() {
int count = serialMenu.getItemCount();
Object[] names = new Object[count];
for (int i = 0; i < count; i++) {
names[i] = ((JCheckBoxMenuItem)serialMenu.getItem(i)).getText();
}
String result = (String)
JOptionPane.showInputDialog(this,
"Serial port " +
Preferences.get("serial.port") +
" not found.\n" +
"Retry the upload with another serial port?",
"Serial port not found",
JOptionPane.PLAIN_MESSAGE,
null,
names,
0);
if (result == null) return false;
selectSerialPort(result);
base.onBoardOrPortChange();
return true;
}
/**
* Called by Sketch → Export.
* Handles calling the export() function on sketch, and
* queues all the gui status stuff that comes along with it.
* <p/>
* Made synchronized to (hopefully) avoid problems of people
* hitting export twice, quickly, and horking things up.
*/
/**
* Handles calling the export() function on sketch, and
* queues all the gui status stuff that comes along with it.
*
* Made synchronized to (hopefully) avoid problems of people
* hitting export twice, quickly, and horking things up.
*/
synchronized public void handleExport(final boolean usingProgrammer) {
//if (!handleExportCheckModified()) return;
toolbar.activate(EditorToolbar.EXPORT);
console.clear();
status.progress("Uploading to I/O Board...");
new Thread(usingProgrammer ? exportAppHandler : exportHandler).start();
}
// DAM: in Arduino, this is upload
class DefaultExportHandler implements Runnable {
public void run() {
try {
serialMonitor.closeSerialPort();
serialMonitor.setVisible(false);
uploading = true;
boolean success = sketch.exportApplet(false);
if (success) {
statusNotice("Done uploading.");
} else {
// error message will already be visible
}
} catch (SerialNotFoundException e) {
populateSerialMenu();
if (serialMenu.getItemCount() == 0) statusError(e);
else if (serialPrompt()) run();
else statusNotice("Upload canceled.");
} catch (RunnerException e) {
//statusError("Error during upload.");
//e.printStackTrace();
status.unprogress();
statusError(e);
} catch (Exception e) {
e.printStackTrace();
}
status.unprogress();
uploading = false;
//toolbar.clear();
toolbar.deactivate(EditorToolbar.EXPORT);
}
}
// DAM: in Arduino, this is upload (with verbose output)
class DefaultExportAppHandler implements Runnable {
public void run() {
try {
serialMonitor.closeSerialPort();
serialMonitor.setVisible(false);
uploading = true;
boolean success = sketch.exportApplet(true);
if (success) {
statusNotice("Done uploading.");
} else {
// error message will already be visible
}
} catch (SerialNotFoundException e) {
populateSerialMenu();
if (serialMenu.getItemCount() == 0) statusError(e);
else if (serialPrompt()) run();
else statusNotice("Upload canceled.");
} catch (RunnerException e) {
//statusError("Error during upload.");
//e.printStackTrace();
status.unprogress();
statusError(e);
} catch (Exception e) {
e.printStackTrace();
}
status.unprogress();
uploading = false;
//toolbar.clear();
toolbar.deactivate(EditorToolbar.EXPORT);
}
}
/**
* Checks to see if the sketch has been modified, and if so,
* asks the user to save the sketch or cancel the export.
* This prevents issues where an incomplete version of the sketch
* would be exported, and is a fix for
* <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=157">Bug 157</A>
*/
protected boolean handleExportCheckModified() {
if (!sketch.isModified()) return true;
Object[] options = { "OK", "Cancel" };
int result = JOptionPane.showOptionDialog(this,
"Save changes before export?",
"Save",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.OK_OPTION) {
handleSave(true);
} else {
// why it's not CANCEL_OPTION is beyond me (at least on the mac)
// but f-- it.. let's get this shite done..
//} else if (result == JOptionPane.CANCEL_OPTION) {
statusNotice("Export canceled, changes must first be saved.");
//toolbar.clear();
return false;
}
return true;
}
public void handleSerial() {
if (uploading) return;
try {
serialMonitor.openSerialPort();
serialMonitor.setVisible(true);
} catch (SerialException e) {
statusError(e);
}
}
protected void handleBurnBootloader() {
console.clear();
statusNotice("Burning bootloader to I/O Board (this may take a minute)...");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Uploader uploader = new AvrdudeUploader();
if (uploader.burnBootloader()) {
statusNotice("Done burning bootloader.");
} else {
statusError("Error while burning bootloader.");
// error message will already be visible
}
} catch (RunnerException e) {
statusError("Error while burning bootloader.");
e.printStackTrace();
//statusError(e);
} catch (Exception e) {
statusError("Error while burning bootloader.");
e.printStackTrace();
}
}});
}
/**
* Handler for File → Page Setup.
*/
public void handlePageSetup() {
//printerJob = null;
if (printerJob == null) {
printerJob = PrinterJob.getPrinterJob();
}
if (pageFormat == null) {
pageFormat = printerJob.defaultPage();
}
pageFormat = printerJob.pageDialog(pageFormat);
//System.out.println("page format is " + pageFormat);
}
/**
* Handler for File → Print.
*/
public void handlePrint() {
statusNotice("Printing...");
//printerJob = null;
if (printerJob == null) {
printerJob = PrinterJob.getPrinterJob();
}
if (pageFormat != null) {
//System.out.println("setting page format " + pageFormat);
printerJob.setPrintable(textarea.getPainter(), pageFormat);
} else {
printerJob.setPrintable(textarea.getPainter());
}
// set the name of the job to the code name
printerJob.setJobName(sketch.getCurrentCode().getPrettyName());
if (printerJob.printDialog()) {
try {
printerJob.print();
statusNotice("Done printing.");
} catch (PrinterException pe) {
statusError("Error while printing.");
pe.printStackTrace();
}
} else {
statusNotice("Printing canceled.");
}
//printerJob = null; // clear this out?
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Show an error int the status bar.
*/
public void statusError(String what) {
status.error(what);
//new Exception("deactivating RUN").printStackTrace();
toolbar.deactivate(EditorToolbar.RUN);
}
/**
* Show an exception in the editor status bar.
*/
public void statusError(Exception e) {
e.printStackTrace();
// if (e == null) {
// System.err.println("Editor.statusError() was passed a null exception.");
// return;
// }
if (e instanceof RunnerException) {
RunnerException re = (RunnerException) e;
if (re.hasCodeIndex()) {
sketch.setCurrentCode(re.getCodeIndex());
}
if (re.hasCodeLine()) {
int line = re.getCodeLine();
// subtract one from the end so that the \n ain't included
if (line >= textarea.getLineCount()) {
// The error is at the end of this current chunk of code,
// so the last line needs to be selected.
line = textarea.getLineCount() - 1;
if (textarea.getLineText(line).length() == 0) {
// The last line may be zero length, meaning nothing to select.
// If so, back up one more line.
line--;
}
}
if (line < 0 || line >= textarea.getLineCount()) {
System.err.println("Bad error line: " + line);
} else {
textarea.select(textarea.getLineStartOffset(line),
textarea.getLineStopOffset(line) - 1);
}
}
}
// Since this will catch all Exception types, spend some time figuring
// out which kind and try to give a better error message to the user.
String mess = e.getMessage();
if (mess != null) {
String javaLang = "java.lang.";
if (mess.indexOf(javaLang) == 0) {
mess = mess.substring(javaLang.length());
}
String rxString = "RuntimeException: ";
if (mess.indexOf(rxString) == 0) {
mess = mess.substring(rxString.length());
}
statusError(mess);
}
// e.printStackTrace();
}
/**
* Show a notice message in the editor status bar.
*/
public void statusNotice(String msg) {
status.notice(msg);
}
/**
* Clear the status area.
*/
public void statusEmpty() {
statusNotice(EMPTY);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
protected void onBoardOrPortChange() {
Map<String, String> boardPreferences = Base.getBoardPreferences();
lineStatus.setBoardName(boardPreferences.get("name"));
lineStatus.setSerialPort(Preferences.get("serial.port"));
lineStatus.repaint();
}
/**
* Returns the edit popup menu.
*/
class TextAreaPopup extends JPopupMenu {
//private String currentDir = System.getProperty("user.dir");
private String referenceFile = null;
private JMenuItem cutItem;
private JMenuItem copyItem;
private JMenuItem discourseItem;
private JMenuItem referenceItem;
private JMenuItem openURLItem;
private JSeparator openURLItemSeparator;
private String clickedURL;
public TextAreaPopup() {
openURLItem = new JMenuItem("Open URL");
openURLItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Base.openURL(clickedURL);
}
});
add(openURLItem);
openURLItemSeparator = new JSeparator();
add(openURLItemSeparator);
cutItem = new JMenuItem("Cut");
cutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCut();
}
});
add(cutItem);
copyItem = new JMenuItem("Copy");
copyItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCopy();
}
});
add(copyItem);
discourseItem = new JMenuItem("Copy for Forum");
discourseItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleDiscourseCopy();
}
});
add(discourseItem);
discourseItem = new JMenuItem("Copy as HTML");
discourseItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleHTMLCopy();
}
});
add(discourseItem);
JMenuItem item = new JMenuItem("Paste");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePaste();
}
});
add(item);
item = new JMenuItem("Select All");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSelectAll();
}
});
add(item);
addSeparator();
item = new JMenuItem("Comment/Uncomment");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCommentUncomment();
}
});
add(item);
item = new JMenuItem("Increase Indent");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(true);
}
});
add(item);
item = new JMenuItem("Decrease Indent");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(false);
}
});
add(item);
addSeparator();
referenceItem = new JMenuItem("Find in Reference");
referenceItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleFindReference();
}
});
add(referenceItem);
}
// if no text is selected, disable copy and cut menu items
public void show(Component component, int x, int y) {
int lineNo = textarea.getLineOfOffset(textarea.xyToOffset(x, y));
int offset = textarea.xToOffset(lineNo, x);
String line = textarea.getLineText(lineNo);
clickedURL = textarea.checkClickedURL(line, offset);
if (clickedURL != null) {
openURLItem.setVisible(true);
openURLItemSeparator.setVisible(true);
} else {
openURLItem.setVisible(false);
openURLItemSeparator.setVisible(false);
}
if (textarea.isSelectionActive()) {
cutItem.setEnabled(true);
copyItem.setEnabled(true);
discourseItem.setEnabled(true);
String sel = textarea.getSelectedText().trim();
referenceFile = PdeKeywords.getReference(sel);
referenceItem.setEnabled(referenceFile != null);
} else {
cutItem.setEnabled(false);
copyItem.setEnabled(false);
discourseItem.setEnabled(false);
referenceItem.setEnabled(false);
}
super.show(component, x, y);
}
}
}
| false | true | public Editor(Base ibase, String path, int[] location) {
super("Arduino");
this.base = ibase;
Base.setIcon(this);
// Install default actions for Run, Present, etc.
resetHandlers();
// add listener to handle window close box hit event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
base.handleClose(Editor.this);
}
});
// don't close the window when clicked, the app will take care
// of that via the handleQuitInternal() methods
// http://dev.processing.org/bugs/show_bug.cgi?id=440
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// When bringing a window to front, let the Base know
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
// System.err.println("activate"); // not coming through
base.handleActivated(Editor.this);
// re-add the sub-menus that are shared by all windows
fileMenu.insert(sketchbookMenu, 2);
fileMenu.insert(examplesMenu, 3);
sketchMenu.insert(importMenu, 4);
toolsMenu.insert(boardsMenu, numTools);
toolsMenu.insert(serialMenu, numTools + 1);
}
// added for 1.0.5
// http://dev.processing.org/bugs/show_bug.cgi?id=1260
public void windowDeactivated(WindowEvent e) {
// System.err.println("deactivate"); // not coming through
fileMenu.remove(sketchbookMenu);
fileMenu.remove(examplesMenu);
sketchMenu.remove(importMenu);
toolsMenu.remove(boardsMenu);
toolsMenu.remove(serialMenu);
}
});
//PdeKeywords keywords = new PdeKeywords();
//sketchbook = new Sketchbook(this);
if (serialMonitor == null)
serialMonitor = new SerialMonitor(Preferences.get("serial.port"));
buildMenuBar();
// For rev 0120, placing things inside a JPanel
Container contentPain = getContentPane();
contentPain.setLayout(new BorderLayout());
JPanel pain = new JPanel();
pain.setLayout(new BorderLayout());
contentPain.add(pain, BorderLayout.CENTER);
Box box = Box.createVerticalBox();
Box upper = Box.createVerticalBox();
if (toolbarMenu == null) {
toolbarMenu = new JMenu();
base.rebuildToolbarMenu(toolbarMenu);
}
toolbar = new EditorToolbar(this, toolbarMenu);
upper.add(toolbar);
header = new EditorHeader(this);
upper.add(header);
textarea = new JEditTextArea(new PdeTextAreaDefaults());
textarea.setRightClickPopup(new TextAreaPopup());
textarea.setHorizontalOffset(6);
// assemble console panel, consisting of status area and the console itself
consolePanel = new JPanel();
consolePanel.setLayout(new BorderLayout());
status = new EditorStatus(this);
consolePanel.add(status, BorderLayout.NORTH);
console = new EditorConsole(this);
// windows puts an ugly border on this guy
console.setBorder(null);
consolePanel.add(console, BorderLayout.CENTER);
lineStatus = new EditorLineStatus(textarea);
consolePanel.add(lineStatus, BorderLayout.SOUTH);
upper.add(textarea);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
upper, consolePanel);
splitPane.setOneTouchExpandable(true);
// repaint child panes while resizing
splitPane.setContinuousLayout(true);
// if window increases in size, give all of increase to
// the textarea in the uppper pane
splitPane.setResizeWeight(1D);
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
splitPane.setBorder(null);
// the default size on windows is too small and kinda ugly
int dividerSize = Preferences.getInteger("editor.divider.size");
if (dividerSize != 0) {
splitPane.setDividerSize(dividerSize);
}
splitPane.setMinimumSize(new Dimension(600, 400));
box.add(splitPane);
// hopefully these are no longer needed w/ swing
// (har har har.. that was wishful thinking)
listener = new EditorListener(this, textarea);
pain.add(box);
// get shift down/up events so we can show the alt version of toolbar buttons
textarea.addKeyListener(toolbar);
pain.setTransferHandler(new FileDropHandler());
// System.out.println("t1");
// Finish preparing Editor (formerly found in Base)
pack();
// System.out.println("t2");
// Set the window bounds and the divider location before setting it visible
setPlacement(location);
// If the window is resized too small this will resize it again to the
// minimums. Adapted by Chris Lonnen from comments here:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4320050
// as a fix for http://dev.processing.org/bugs/show_bug.cgi?id=25
final int minW = Preferences.getInteger("editor.window.width.min");
final int minH = Preferences.getInteger("editor.window.height.min");
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(ComponentEvent event) {
setSize((getWidth() < minW) ? minW : getWidth(),
(getHeight() < minH) ? minH : getHeight());
}
});
// System.out.println("t3");
// Bring back the general options for the editor
applyPreferences();
// System.out.println("t4");
// Open the document that was passed in
boolean loaded = handleOpenInternal(path);
if (!loaded) sketch = null;
// System.out.println("t5");
// All set, now show the window
//setVisible(true);
}
| public Editor(Base ibase, String path, int[] location) {
super("Arduino");
this.base = ibase;
Base.setIcon(this);
// Install default actions for Run, Present, etc.
resetHandlers();
// add listener to handle window close box hit event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
base.handleClose(Editor.this);
}
});
// don't close the window when clicked, the app will take care
// of that via the handleQuitInternal() methods
// http://dev.processing.org/bugs/show_bug.cgi?id=440
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// When bringing a window to front, let the Base know
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
// System.err.println("activate"); // not coming through
base.handleActivated(Editor.this);
// re-add the sub-menus that are shared by all windows
fileMenu.insert(sketchbookMenu, 2);
fileMenu.insert(examplesMenu, 3);
sketchMenu.insert(importMenu, 4);
toolsMenu.insert(boardsMenu, numTools);
toolsMenu.insert(serialMenu, numTools + 1);
}
// added for 1.0.5
// http://dev.processing.org/bugs/show_bug.cgi?id=1260
public void windowDeactivated(WindowEvent e) {
// System.err.println("deactivate"); // not coming through
fileMenu.remove(sketchbookMenu);
fileMenu.remove(examplesMenu);
sketchMenu.remove(importMenu);
toolsMenu.remove(boardsMenu);
toolsMenu.remove(serialMenu);
}
});
//PdeKeywords keywords = new PdeKeywords();
//sketchbook = new Sketchbook(this);
if (serialMonitor == null) {
serialMonitor = new SerialMonitor(Preferences.get("serial.port"));
serialMonitor.setIconImage(getIconImage());
}
buildMenuBar();
// For rev 0120, placing things inside a JPanel
Container contentPain = getContentPane();
contentPain.setLayout(new BorderLayout());
JPanel pain = new JPanel();
pain.setLayout(new BorderLayout());
contentPain.add(pain, BorderLayout.CENTER);
Box box = Box.createVerticalBox();
Box upper = Box.createVerticalBox();
if (toolbarMenu == null) {
toolbarMenu = new JMenu();
base.rebuildToolbarMenu(toolbarMenu);
}
toolbar = new EditorToolbar(this, toolbarMenu);
upper.add(toolbar);
header = new EditorHeader(this);
upper.add(header);
textarea = new JEditTextArea(new PdeTextAreaDefaults());
textarea.setRightClickPopup(new TextAreaPopup());
textarea.setHorizontalOffset(6);
// assemble console panel, consisting of status area and the console itself
consolePanel = new JPanel();
consolePanel.setLayout(new BorderLayout());
status = new EditorStatus(this);
consolePanel.add(status, BorderLayout.NORTH);
console = new EditorConsole(this);
// windows puts an ugly border on this guy
console.setBorder(null);
consolePanel.add(console, BorderLayout.CENTER);
lineStatus = new EditorLineStatus(textarea);
consolePanel.add(lineStatus, BorderLayout.SOUTH);
upper.add(textarea);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
upper, consolePanel);
splitPane.setOneTouchExpandable(true);
// repaint child panes while resizing
splitPane.setContinuousLayout(true);
// if window increases in size, give all of increase to
// the textarea in the uppper pane
splitPane.setResizeWeight(1D);
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
splitPane.setBorder(null);
// the default size on windows is too small and kinda ugly
int dividerSize = Preferences.getInteger("editor.divider.size");
if (dividerSize != 0) {
splitPane.setDividerSize(dividerSize);
}
splitPane.setMinimumSize(new Dimension(600, 400));
box.add(splitPane);
// hopefully these are no longer needed w/ swing
// (har har har.. that was wishful thinking)
listener = new EditorListener(this, textarea);
pain.add(box);
// get shift down/up events so we can show the alt version of toolbar buttons
textarea.addKeyListener(toolbar);
pain.setTransferHandler(new FileDropHandler());
// System.out.println("t1");
// Finish preparing Editor (formerly found in Base)
pack();
// System.out.println("t2");
// Set the window bounds and the divider location before setting it visible
setPlacement(location);
// If the window is resized too small this will resize it again to the
// minimums. Adapted by Chris Lonnen from comments here:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4320050
// as a fix for http://dev.processing.org/bugs/show_bug.cgi?id=25
final int minW = Preferences.getInteger("editor.window.width.min");
final int minH = Preferences.getInteger("editor.window.height.min");
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(ComponentEvent event) {
setSize((getWidth() < minW) ? minW : getWidth(),
(getHeight() < minH) ? minH : getHeight());
}
});
// System.out.println("t3");
// Bring back the general options for the editor
applyPreferences();
// System.out.println("t4");
// Open the document that was passed in
boolean loaded = handleOpenInternal(path);
if (!loaded) sketch = null;
// System.out.println("t5");
// All set, now show the window
//setVisible(true);
}
|
diff --git a/core/src/main/java/hudson/tasks/junit/SuiteResult.java b/core/src/main/java/hudson/tasks/junit/SuiteResult.java
index ccc7f57ca..a4d251a8d 100644
--- a/core/src/main/java/hudson/tasks/junit/SuiteResult.java
+++ b/core/src/main/java/hudson/tasks/junit/SuiteResult.java
@@ -1,198 +1,198 @@
package hudson.tasks.junit;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Result of one test suite.
*
* <p>
* The notion of "test suite" is rather arbitrary in JUnit ant task.
* It's basically one invocation of junit.
*
* <p>
* This object is really only used as a part of the persisted
* object tree.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public final class SuiteResult implements Serializable {
private final String name;
private final String stdout;
private final String stderr;
private float duration;
/**
* The 'timestamp' attribute of the test suite.
* AFAICT, this is not a required attribute in XML, so the value may be null.
*/
private String timestamp;
/**
* All test cases.
*/
private final List<CaseResult> cases = new ArrayList<CaseResult>();
private transient TestResult parent;
SuiteResult(String name, String stdout, String stderr) {
this.name = name;
this.stderr = stderr;
this.stdout = stdout;
}
/**
* Parses the JUnit XML file into {@link SuiteResult}s.
* This method returns a collection, as a single XML may have multiple <testsuite>
* elements wrapped into the top-level <testsuites>.
*/
static List<SuiteResult> parse(File xmlReport) throws DocumentException {
List<SuiteResult> r = new ArrayList<SuiteResult>();
// parse into DOM
SAXReader saxReader = new SAXReader();
// install EntityResolver for resolving DTDs, which are in files created by TestNG.
// (see https://hudson.dev.java.net/servlets/ReadMsg?listName=users&msgNo=5530)
XMLEntityResolver resolver = new XMLEntityResolver();
saxReader.setEntityResolver(resolver);
Document result = saxReader.read(xmlReport);
Element root = result.getRootElement();
if(root.getName().equals("testsuites")) {
// multi-suite file
for (Element suite : (List<Element>)root.elements("testsuite"))
r.add(new SuiteResult(xmlReport,suite));
} else {
// single suite file
r.add(new SuiteResult(xmlReport,root));
}
return r;
}
private SuiteResult(File xmlReport, Element suite) throws DocumentException {
String name = suite.attributeValue("name");
if(name==null)
// some user reported that name is null in their environment.
// see http://www.nabble.com/Unexpected-Null-Pointer-Exception-in-Hudson-1.131-tf4314802.html
name = '('+xmlReport.getName()+')';
else {
String pkg = suite.attributeValue("package");
- if(pkg!=null&&!pkg.isEmpty()) name=pkg+'.'+name;
+ if(pkg!=null&& pkg.length()>0) name=pkg+'.'+name;
}
this.name = TestObject.safe(name);
this.timestamp = suite.attributeValue("timestamp");
stdout = suite.elementText("system-out");
stderr = suite.elementText("system-err");
Element ex = suite.element("error");
if(ex!=null) {
// according to junit-noframes.xsl l.229, this happens when the test class failed to load
addCase(new CaseResult(this,suite,"<init>"));
}
for (Element e : (List<Element>)suite.elements("testcase")) {
// https://hudson.dev.java.net/issues/show_bug.cgi?id=1233 indicates that
// when <testsuites> is present, we are better off using @classname on the
// individual testcase class.
// https://hudson.dev.java.net/issues/show_bug.cgi?id=1463 indicates that
// @classname may not exist in individual testcase elements. We now
// also test if the testsuite element has a package name that can be used
// as the class name instead of the file name which is default.
String classname = e.attributeValue("classname");
if (classname == null) {
classname = suite.attributeValue("name");
}
// https://hudson.dev.java.net/issues/show_bug.cgi?id=1233 and
// http://www.nabble.com/difference-in-junit-publisher-and-ant-junitreport-tf4308604.html#a12265700
// are at odds with each other --- when both are present,
// one wants to use @name from <testsuite>,
// the other wants to use @classname from <testcase>.
addCase(new CaseResult(this,classname,e));
}
}
/*package*/ void addCase(CaseResult cr) {
cases.add(cr);
duration += cr.getDuration();
}
@Exported
public String getName() {
return name;
}
@Exported
public float getDuration() {
return duration;
}
@Exported
public String getStdout() {
return stdout;
}
@Exported
public String getStderr() {
return stderr;
}
public TestResult getParent() {
return parent;
}
@Exported
public String getTimestamp() {
return timestamp;
}
@Exported
public List<CaseResult> getCases() {
return cases;
}
public SuiteResult getPreviousResult() {
TestResult pr = parent.getPreviousResult();
if(pr==null) return null;
return pr.getSuite(name);
}
/**
* Returns the {@link CaseResult} whose {@link CaseResult#getName()}
* is the same as the given string.
*
* <p>
* Note that test name needs not be unique.
*/
public CaseResult getCase(String name) {
for (CaseResult c : cases) {
if(c.getName().equals(name))
return c;
}
return null;
}
/*package*/ boolean freeze(TestResult owner) {
if(this.parent!=null)
return false; // already frozen
this.parent = owner;
for (CaseResult c : cases)
c.freeze(this);
return true;
}
private static final long serialVersionUID = 1L;
}
| true | true | private SuiteResult(File xmlReport, Element suite) throws DocumentException {
String name = suite.attributeValue("name");
if(name==null)
// some user reported that name is null in their environment.
// see http://www.nabble.com/Unexpected-Null-Pointer-Exception-in-Hudson-1.131-tf4314802.html
name = '('+xmlReport.getName()+')';
else {
String pkg = suite.attributeValue("package");
if(pkg!=null&&!pkg.isEmpty()) name=pkg+'.'+name;
}
this.name = TestObject.safe(name);
this.timestamp = suite.attributeValue("timestamp");
stdout = suite.elementText("system-out");
stderr = suite.elementText("system-err");
Element ex = suite.element("error");
if(ex!=null) {
// according to junit-noframes.xsl l.229, this happens when the test class failed to load
addCase(new CaseResult(this,suite,"<init>"));
}
for (Element e : (List<Element>)suite.elements("testcase")) {
// https://hudson.dev.java.net/issues/show_bug.cgi?id=1233 indicates that
// when <testsuites> is present, we are better off using @classname on the
// individual testcase class.
// https://hudson.dev.java.net/issues/show_bug.cgi?id=1463 indicates that
// @classname may not exist in individual testcase elements. We now
// also test if the testsuite element has a package name that can be used
// as the class name instead of the file name which is default.
String classname = e.attributeValue("classname");
if (classname == null) {
classname = suite.attributeValue("name");
}
// https://hudson.dev.java.net/issues/show_bug.cgi?id=1233 and
// http://www.nabble.com/difference-in-junit-publisher-and-ant-junitreport-tf4308604.html#a12265700
// are at odds with each other --- when both are present,
// one wants to use @name from <testsuite>,
// the other wants to use @classname from <testcase>.
addCase(new CaseResult(this,classname,e));
}
}
| private SuiteResult(File xmlReport, Element suite) throws DocumentException {
String name = suite.attributeValue("name");
if(name==null)
// some user reported that name is null in their environment.
// see http://www.nabble.com/Unexpected-Null-Pointer-Exception-in-Hudson-1.131-tf4314802.html
name = '('+xmlReport.getName()+')';
else {
String pkg = suite.attributeValue("package");
if(pkg!=null&& pkg.length()>0) name=pkg+'.'+name;
}
this.name = TestObject.safe(name);
this.timestamp = suite.attributeValue("timestamp");
stdout = suite.elementText("system-out");
stderr = suite.elementText("system-err");
Element ex = suite.element("error");
if(ex!=null) {
// according to junit-noframes.xsl l.229, this happens when the test class failed to load
addCase(new CaseResult(this,suite,"<init>"));
}
for (Element e : (List<Element>)suite.elements("testcase")) {
// https://hudson.dev.java.net/issues/show_bug.cgi?id=1233 indicates that
// when <testsuites> is present, we are better off using @classname on the
// individual testcase class.
// https://hudson.dev.java.net/issues/show_bug.cgi?id=1463 indicates that
// @classname may not exist in individual testcase elements. We now
// also test if the testsuite element has a package name that can be used
// as the class name instead of the file name which is default.
String classname = e.attributeValue("classname");
if (classname == null) {
classname = suite.attributeValue("name");
}
// https://hudson.dev.java.net/issues/show_bug.cgi?id=1233 and
// http://www.nabble.com/difference-in-junit-publisher-and-ant-junitreport-tf4308604.html#a12265700
// are at odds with each other --- when both are present,
// one wants to use @name from <testsuite>,
// the other wants to use @classname from <testcase>.
addCase(new CaseResult(this,classname,e));
}
}
|
diff --git a/com/narrowtux/DropChest/DropChestPlayerListener.java b/com/narrowtux/DropChest/DropChestPlayerListener.java
index fc6005f..ce45740 100644
--- a/com/narrowtux/DropChest/DropChestPlayerListener.java
+++ b/com/narrowtux/DropChest/DropChestPlayerListener.java
@@ -1,173 +1,173 @@
package com.narrowtux.DropChest;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.ContainerBlock;
import org.bukkit.entity.Player;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerListener;
/**
* Handle events for all Player related events
* @author narrowtux
*/
public class DropChestPlayerListener extends PlayerListener {
private final DropChest plugin;
public DropChestPlayerListener(DropChest instance) {
plugin = instance;
}
@Override
public void onPlayerInteract(PlayerInteractEvent event){
if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK)){
if(event.isCancelled()){
return;
}
DropChestPlayer dplayer = DropChestPlayer.getPlayerByName(event.getPlayer().getName());
Block b = event.getClickedBlock();
if(DropChestItem.acceptsBlockType(b.getType())){
List<DropChestItem> chests = plugin.getChests();
DropChestItem chestdci = plugin.getChestByBlock(b);
if(chestdci!=null&&chestdci.isProtect()&&(!chestdci.getOwner().equals(dplayer.getPlayer().getName()))){
event.setCancelled(true);
dplayer.getPlayer().sendMessage("That's not your chest");
return;
}
if(dplayer!=null&&!dplayer.getChestRequestType().equals(ChestRequestType.NONE)){
switch(dplayer.getChestRequestType()){
case CREATE:
if(chestdci==null){
ContainerBlock chest = (ContainerBlock)b.getState();
int radius = dplayer.getRequestedRadius();
if(radius < 2)
radius = 2;
DropChestItem dci = new DropChestItem(chest, radius, b, plugin);
chests.add(dci);
dci.setOwner(dplayer.getPlayer().getName());
dci.setProtect(false);
if(event.getPlayer()!=null)
{
event.getPlayer().sendMessage("Created DropChest. ID: #"+dci.getId());
}
plugin.save();
} else {
dplayer.getPlayer().sendMessage(ChatColor.RED+"This DropChest already exists. ID: #"+chestdci.getId());
}
break;
case WHICH:
if(chestdci!=null){
String ret = ChatColor.WHITE.toString();
String filterString = "";
ret+="ID: "+ChatColor.YELLOW+chestdci.getId()+ChatColor.WHITE+
" Name: "+ChatColor.YELLOW+chestdci.getName()+
ChatColor.WHITE+" Radius: "+ChatColor.YELLOW+chestdci.getRadius()+
ChatColor.WHITE+" Owner: "+ChatColor.YELLOW+chestdci.getOwner()+"\n";
for(FilterType type:FilterType.values()){
List<Material> filter = chestdci.getFilter(type);
if(filter.size()!=0)
{
filterString+=ChatColor.AQUA+type.toString()+":\n";
boolean useId = false;
if(filter.size()<5){
useId = false;
} else {
useId = true;
}
for(int i = 0; i<filter.size();i++){
Material m = filter.get(i);
filterString+=ChatColor.YELLOW.toString();
if(useId){
filterString+=m.getId();
} else {
filterString+=m.toString();
}
if(i+1!=filter.size()){
filterString+=ChatColor.WHITE+", ";
} else {
filterString+=ChatColor.WHITE+"\n";
}
}
}
}
if(!filterString.equals("")){
ret+=ChatColor.AQUA+"Filters:\n";
ret+=filterString;
}
String strings[] = ret.split("\n");
for (String val:strings){
- dplayer.getPlayer().sendMessage(val);
+ event.getPlayer().sendMessage(val);
}
} else {
- dplayer.getPlayer().sendMessage("This is not a DropChest!");
+ event.getPlayer().sendMessage("This is not a DropChest!");
}
break;
}
dplayer.setChestRequestType(ChestRequestType.NONE);
event.setCancelled(true);
}
}
} else if(event.getAction()==Action.LEFT_CLICK_BLOCK){
Player player = event.getPlayer();
DropChestPlayer dplayer = DropChestPlayer.getPlayerByName(player.getName());
Block b = event.getClickedBlock();
if(DropChestItem.acceptsBlockType(b.getType())){
int radius = plugin.getRequestedRadius();
if(radius < 2)
radius = 2;
List<DropChestItem> chests = plugin.getChests();
boolean chestexists = false;
DropChestItem chestdci = null;
int i = 0;
for(DropChestItem dcic : chests){
Block block = b;
if(plugin.locationsEqual(dcic.getBlock().getLocation(), block.getLocation())){
chestexists = true;
chestdci = dcic;
break;
}
i++;
}
if(chestexists&&plugin.hasPermission(player, "dropchest.filter.set")&&dplayer.isEditingFilter()){
Material m = player.getItemInHand().getType();
boolean found = false;
if(m.getId()==0&&plugin.hasPermission(player, "dropchest.filter.reset")){
chestdci.getFilter(dplayer.getEditingFilterType()).clear();
player.sendMessage(ChatColor.GREEN.toString()+"All items will be accepted.");
} else{
for (Material ma : chestdci.getFilter(dplayer.getEditingFilterType())){
if(m.getId()==ma.getId()){
chestdci.getFilter(dplayer.getEditingFilterType()).remove(ma);
found = true;
if(chestdci.getFilter(dplayer.getEditingFilterType()).size()==0){
player.sendMessage(ChatColor.GREEN.toString()+"All items will be accepted.");
} else {
player.sendMessage(ChatColor.RED.toString()+ma.toString()+" won't be accepted.");
}
break;
}
}
if(!found)
{
chestdci.getFilter(dplayer.getEditingFilterType()).add(m);
player.sendMessage(ChatColor.GREEN.toString()+m.toString()+" will be accepted.");
}
}
plugin.save();
}
}
}
}
}
| false | true | public void onPlayerInteract(PlayerInteractEvent event){
if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK)){
if(event.isCancelled()){
return;
}
DropChestPlayer dplayer = DropChestPlayer.getPlayerByName(event.getPlayer().getName());
Block b = event.getClickedBlock();
if(DropChestItem.acceptsBlockType(b.getType())){
List<DropChestItem> chests = plugin.getChests();
DropChestItem chestdci = plugin.getChestByBlock(b);
if(chestdci!=null&&chestdci.isProtect()&&(!chestdci.getOwner().equals(dplayer.getPlayer().getName()))){
event.setCancelled(true);
dplayer.getPlayer().sendMessage("That's not your chest");
return;
}
if(dplayer!=null&&!dplayer.getChestRequestType().equals(ChestRequestType.NONE)){
switch(dplayer.getChestRequestType()){
case CREATE:
if(chestdci==null){
ContainerBlock chest = (ContainerBlock)b.getState();
int radius = dplayer.getRequestedRadius();
if(radius < 2)
radius = 2;
DropChestItem dci = new DropChestItem(chest, radius, b, plugin);
chests.add(dci);
dci.setOwner(dplayer.getPlayer().getName());
dci.setProtect(false);
if(event.getPlayer()!=null)
{
event.getPlayer().sendMessage("Created DropChest. ID: #"+dci.getId());
}
plugin.save();
} else {
dplayer.getPlayer().sendMessage(ChatColor.RED+"This DropChest already exists. ID: #"+chestdci.getId());
}
break;
case WHICH:
if(chestdci!=null){
String ret = ChatColor.WHITE.toString();
String filterString = "";
ret+="ID: "+ChatColor.YELLOW+chestdci.getId()+ChatColor.WHITE+
" Name: "+ChatColor.YELLOW+chestdci.getName()+
ChatColor.WHITE+" Radius: "+ChatColor.YELLOW+chestdci.getRadius()+
ChatColor.WHITE+" Owner: "+ChatColor.YELLOW+chestdci.getOwner()+"\n";
for(FilterType type:FilterType.values()){
List<Material> filter = chestdci.getFilter(type);
if(filter.size()!=0)
{
filterString+=ChatColor.AQUA+type.toString()+":\n";
boolean useId = false;
if(filter.size()<5){
useId = false;
} else {
useId = true;
}
for(int i = 0; i<filter.size();i++){
Material m = filter.get(i);
filterString+=ChatColor.YELLOW.toString();
if(useId){
filterString+=m.getId();
} else {
filterString+=m.toString();
}
if(i+1!=filter.size()){
filterString+=ChatColor.WHITE+", ";
} else {
filterString+=ChatColor.WHITE+"\n";
}
}
}
}
if(!filterString.equals("")){
ret+=ChatColor.AQUA+"Filters:\n";
ret+=filterString;
}
String strings[] = ret.split("\n");
for (String val:strings){
dplayer.getPlayer().sendMessage(val);
}
} else {
dplayer.getPlayer().sendMessage("This is not a DropChest!");
}
break;
}
dplayer.setChestRequestType(ChestRequestType.NONE);
event.setCancelled(true);
}
}
} else if(event.getAction()==Action.LEFT_CLICK_BLOCK){
Player player = event.getPlayer();
DropChestPlayer dplayer = DropChestPlayer.getPlayerByName(player.getName());
Block b = event.getClickedBlock();
if(DropChestItem.acceptsBlockType(b.getType())){
int radius = plugin.getRequestedRadius();
if(radius < 2)
radius = 2;
List<DropChestItem> chests = plugin.getChests();
boolean chestexists = false;
DropChestItem chestdci = null;
int i = 0;
for(DropChestItem dcic : chests){
Block block = b;
if(plugin.locationsEqual(dcic.getBlock().getLocation(), block.getLocation())){
chestexists = true;
chestdci = dcic;
break;
}
i++;
}
if(chestexists&&plugin.hasPermission(player, "dropchest.filter.set")&&dplayer.isEditingFilter()){
Material m = player.getItemInHand().getType();
boolean found = false;
if(m.getId()==0&&plugin.hasPermission(player, "dropchest.filter.reset")){
chestdci.getFilter(dplayer.getEditingFilterType()).clear();
player.sendMessage(ChatColor.GREEN.toString()+"All items will be accepted.");
} else{
for (Material ma : chestdci.getFilter(dplayer.getEditingFilterType())){
if(m.getId()==ma.getId()){
chestdci.getFilter(dplayer.getEditingFilterType()).remove(ma);
found = true;
if(chestdci.getFilter(dplayer.getEditingFilterType()).size()==0){
player.sendMessage(ChatColor.GREEN.toString()+"All items will be accepted.");
} else {
player.sendMessage(ChatColor.RED.toString()+ma.toString()+" won't be accepted.");
}
break;
}
}
if(!found)
{
chestdci.getFilter(dplayer.getEditingFilterType()).add(m);
player.sendMessage(ChatColor.GREEN.toString()+m.toString()+" will be accepted.");
}
}
plugin.save();
}
}
}
}
| public void onPlayerInteract(PlayerInteractEvent event){
if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK)){
if(event.isCancelled()){
return;
}
DropChestPlayer dplayer = DropChestPlayer.getPlayerByName(event.getPlayer().getName());
Block b = event.getClickedBlock();
if(DropChestItem.acceptsBlockType(b.getType())){
List<DropChestItem> chests = plugin.getChests();
DropChestItem chestdci = plugin.getChestByBlock(b);
if(chestdci!=null&&chestdci.isProtect()&&(!chestdci.getOwner().equals(dplayer.getPlayer().getName()))){
event.setCancelled(true);
dplayer.getPlayer().sendMessage("That's not your chest");
return;
}
if(dplayer!=null&&!dplayer.getChestRequestType().equals(ChestRequestType.NONE)){
switch(dplayer.getChestRequestType()){
case CREATE:
if(chestdci==null){
ContainerBlock chest = (ContainerBlock)b.getState();
int radius = dplayer.getRequestedRadius();
if(radius < 2)
radius = 2;
DropChestItem dci = new DropChestItem(chest, radius, b, plugin);
chests.add(dci);
dci.setOwner(dplayer.getPlayer().getName());
dci.setProtect(false);
if(event.getPlayer()!=null)
{
event.getPlayer().sendMessage("Created DropChest. ID: #"+dci.getId());
}
plugin.save();
} else {
dplayer.getPlayer().sendMessage(ChatColor.RED+"This DropChest already exists. ID: #"+chestdci.getId());
}
break;
case WHICH:
if(chestdci!=null){
String ret = ChatColor.WHITE.toString();
String filterString = "";
ret+="ID: "+ChatColor.YELLOW+chestdci.getId()+ChatColor.WHITE+
" Name: "+ChatColor.YELLOW+chestdci.getName()+
ChatColor.WHITE+" Radius: "+ChatColor.YELLOW+chestdci.getRadius()+
ChatColor.WHITE+" Owner: "+ChatColor.YELLOW+chestdci.getOwner()+"\n";
for(FilterType type:FilterType.values()){
List<Material> filter = chestdci.getFilter(type);
if(filter.size()!=0)
{
filterString+=ChatColor.AQUA+type.toString()+":\n";
boolean useId = false;
if(filter.size()<5){
useId = false;
} else {
useId = true;
}
for(int i = 0; i<filter.size();i++){
Material m = filter.get(i);
filterString+=ChatColor.YELLOW.toString();
if(useId){
filterString+=m.getId();
} else {
filterString+=m.toString();
}
if(i+1!=filter.size()){
filterString+=ChatColor.WHITE+", ";
} else {
filterString+=ChatColor.WHITE+"\n";
}
}
}
}
if(!filterString.equals("")){
ret+=ChatColor.AQUA+"Filters:\n";
ret+=filterString;
}
String strings[] = ret.split("\n");
for (String val:strings){
event.getPlayer().sendMessage(val);
}
} else {
event.getPlayer().sendMessage("This is not a DropChest!");
}
break;
}
dplayer.setChestRequestType(ChestRequestType.NONE);
event.setCancelled(true);
}
}
} else if(event.getAction()==Action.LEFT_CLICK_BLOCK){
Player player = event.getPlayer();
DropChestPlayer dplayer = DropChestPlayer.getPlayerByName(player.getName());
Block b = event.getClickedBlock();
if(DropChestItem.acceptsBlockType(b.getType())){
int radius = plugin.getRequestedRadius();
if(radius < 2)
radius = 2;
List<DropChestItem> chests = plugin.getChests();
boolean chestexists = false;
DropChestItem chestdci = null;
int i = 0;
for(DropChestItem dcic : chests){
Block block = b;
if(plugin.locationsEqual(dcic.getBlock().getLocation(), block.getLocation())){
chestexists = true;
chestdci = dcic;
break;
}
i++;
}
if(chestexists&&plugin.hasPermission(player, "dropchest.filter.set")&&dplayer.isEditingFilter()){
Material m = player.getItemInHand().getType();
boolean found = false;
if(m.getId()==0&&plugin.hasPermission(player, "dropchest.filter.reset")){
chestdci.getFilter(dplayer.getEditingFilterType()).clear();
player.sendMessage(ChatColor.GREEN.toString()+"All items will be accepted.");
} else{
for (Material ma : chestdci.getFilter(dplayer.getEditingFilterType())){
if(m.getId()==ma.getId()){
chestdci.getFilter(dplayer.getEditingFilterType()).remove(ma);
found = true;
if(chestdci.getFilter(dplayer.getEditingFilterType()).size()==0){
player.sendMessage(ChatColor.GREEN.toString()+"All items will be accepted.");
} else {
player.sendMessage(ChatColor.RED.toString()+ma.toString()+" won't be accepted.");
}
break;
}
}
if(!found)
{
chestdci.getFilter(dplayer.getEditingFilterType()).add(m);
player.sendMessage(ChatColor.GREEN.toString()+m.toString()+" will be accepted.");
}
}
plugin.save();
}
}
}
}
|
diff --git a/modules/quality-immutable-object/src/test/java/net/sf/qualitycheck/immutableobject/ImmutableObjectGeneratorTest.java b/modules/quality-immutable-object/src/test/java/net/sf/qualitycheck/immutableobject/ImmutableObjectGeneratorTest.java
index 86886b5..9eb5789 100644
--- a/modules/quality-immutable-object/src/test/java/net/sf/qualitycheck/immutableobject/ImmutableObjectGeneratorTest.java
+++ b/modules/quality-immutable-object/src/test/java/net/sf/qualitycheck/immutableobject/ImmutableObjectGeneratorTest.java
@@ -1,488 +1,488 @@
package net.sf.qualitycheck.immutableobject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
import net.sf.qualitycheck.exception.IllegalStateOfArgumentException;
import net.sf.qualitycheck.immutableobject.domain.ImmutableSettings;
import net.sf.qualitycheck.immutableobject.generator.ImmutableObjectGenerator;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.CharStreams;
public class ImmutableObjectGeneratorTest {
private static final Logger LOG = LoggerFactory.getLogger(ImmutableObjectGeneratorTest.class);
private ImmutableSettings.Builder settingsBuilder;
@Before
public void before() {
settingsBuilder = new ImmutableSettings.Builder();
// global settings
settingsBuilder.fieldPrefix("");
settingsBuilder.jsr305Annotations(false);
settingsBuilder.guava(false);
settingsBuilder.qualityCheck(false);
// immutable settings
settingsBuilder.serializable(false);
// builder settings
settingsBuilder.builderCopyConstructor(false);
settingsBuilder.builderFlatMutators(false);
settingsBuilder.builderFluentMutators(false);
settingsBuilder.builderName("");
settingsBuilder.builderImplementsInterface(false);
}
private String readInterfaceAndGenerate(final String name, final ImmutableSettings settings) throws IOException {
final InputStream stream = getClass().getClassLoader().getResourceAsStream(name);
return ImmutableObjectGenerator.generate(CharStreams.toString(new InputStreamReader(stream)), settings).getImplCode();
}
private String readReferenceImmutable(final String name) throws IOException {
final InputStream stream = getClass().getClassLoader().getResourceAsStream("Immutable" + name);
return CharStreams.toString(new InputStreamReader(stream));
}
@Test
public void renderingOf_builder() {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("import java.util.List;\n");
b.append("interface TestObject {\n");
b.append("List<String> getNames();\n");
b.append("}");
final ImmutableSettings settingsWithoutBuilder = settingsBuilder.builderName("").build();
final String generatedCodeWithoutBuilder = ImmutableObjectGenerator.generate(b.toString(), settingsWithoutBuilder).getImplCode();
assertFalse(Pattern.compile("public\\s+static\\s+final\\s+class\\s+").matcher(generatedCodeWithoutBuilder).find());
final ImmutableSettings settingsWithBuilder = settingsBuilder.builderName("Builder").build();
final String generatedCodeWithBuilder = ImmutableObjectGenerator.generate(b.toString(), settingsWithBuilder).getImplCode();
assertTrue(Pattern.compile("public\\s+static\\s+final\\s+class\\s+Builder\\s+").matcher(generatedCodeWithBuilder).find());
}
@Test
public void renderingOf_copyMethods() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("interface TestObject {\n");
b.append("String getName();\n");
b.append("}");
final ImmutableSettings settingsWithCopyMethods = settingsBuilder.copyMethods(true).build();
final String codeWithCopyMethods = ImmutableObjectGenerator.generate(b.toString(), settingsWithCopyMethods).getImplCode();
assertTrue(codeWithCopyMethods.contains("public static ImmutableTestObject copyOf(final TestObject testObject) {"));
assertTrue(codeWithCopyMethods.contains("return new ImmutableTestObject(testObject.getName());"));
assertTrue(codeWithCopyMethods.contains("public static ImmutableTestObject copyOnlyIfNecessary(final TestObject testObject) {"));
assertTrue(codeWithCopyMethods
.contains("return testObject instanceof ImmutableTestObject ? (ImmutableTestObject) testObject : copyOf(testObject);"));
final ImmutableSettings settingsWithoutCopyMethods = settingsBuilder.copyMethods(false).build();
final String codeWithoutCopyMethods = ImmutableObjectGenerator.generate(b.toString(), settingsWithoutCopyMethods).getImplCode();
assertFalse(codeWithoutCopyMethods.contains("public static ImmutableTestObject copyOf(final TestObject testObject) {"));
assertFalse(codeWithoutCopyMethods.contains("return new ImmutableTestObject(testObject.getName());"));
assertFalse(codeWithoutCopyMethods.contains("public static ImmutableTestObject copyOnlyIfNecessary(final TestObject testObject) {"));
assertFalse(codeWithoutCopyMethods
.contains("return testObject instanceof ImmutableTestObject ? (ImmutableTestObject) testObject : copyOf(testObject);"));
}
@Test
public void renderingOf_fieldPrefix() {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("interface TestObject {\n");
b.append("String getName();\n");
b.append("}");
final ImmutableSettings settings = settingsBuilder.fieldPrefix("_").build();
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settings).getImplCode();
assertTrue(generatedCode.contains("private final String _name;"));
}
@Test
public void renderingOf_guava() {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("import java.util.List;\n");
b.append("interface TestObject {\n");
b.append("List<String> getNames();\n");
b.append("}");
final ImmutableSettings settingsWithGuava = settingsBuilder.guava(true).hashCodeAndEquals(true).build();
final String generatedCodeWithGuava = ImmutableObjectGenerator.generate(b.toString(), settingsWithGuava).getImplCode();
assertTrue(generatedCodeWithGuava.contains("this.names = ImmutableList.copyOf(names);"));
assertTrue(generatedCodeWithGuava.contains("return Objects.equal(this.names, other.names);"));
assertTrue(generatedCodeWithGuava.contains("return Objects.hashCode(names);"));
final ImmutableSettings settingsWithoutGuava = settingsBuilder.guava(false).hashCodeAndEquals(true).build();
final String generatedCodeWithoutGuava = ImmutableObjectGenerator.generate(b.toString(), settingsWithoutGuava).getImplCode();
assertTrue(generatedCodeWithoutGuava.contains("this.names = Collections.unmodifiableList(new ArrayList<String>(names));"));
assertTrue(generatedCodeWithoutGuava.contains("} else if (!names.equals(other.names))"));
assertTrue(generatedCodeWithoutGuava.contains("result = prime * result + (names == null ? 0 : names.hashCode());"));
}
@Test
public void renderingOf_hashCodeAndEquals() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("interface TestObject {\n");
b.append("String getName();\n");
b.append("}");
final ImmutableSettings settingsWithHaE = settingsBuilder.hashCodeAndEquals(true).build();
final String generatedCodeWithHaE = ImmutableObjectGenerator.generate(b.toString(), settingsWithHaE).getImplCode();
assertTrue(generatedCodeWithHaE.contains("public boolean equals(final Object obj) {"));
assertTrue(generatedCodeWithHaE.contains("public int hashCode() {"));
final ImmutableSettings settingsWithoutHaE = settingsBuilder.hashCodeAndEquals(false).build();
final String generatedCodeWithoutHaE = ImmutableObjectGenerator.generate(b.toString(), settingsWithoutHaE).getImplCode();
assertFalse(generatedCodeWithoutHaE.contains("public boolean equals(final Object obj) {"));
assertFalse(generatedCodeWithoutHaE.contains("public int hashCode() {"));
}
@Test
public void renderingOf_hashCodePrecomputation() {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("import java.util.List;\n");
b.append("interface TestObject {\n");
b.append("String getName();\n");
b.append("List<String> getNames();\n");
b.append("}");
final ImmutableSettings settingsWithHashCodePrecomp = settingsBuilder.hashCodePrecomputation(true).hashCodeAndEquals(true).build();
final String withHashCodePrecomp = ImmutableObjectGenerator.generate(b.toString(), settingsWithHashCodePrecomp).getImplCode();
assertTrue(withHashCodePrecomp.contains("private static int buildHashCode(final String name, final List<String> names) {"));
assertTrue(withHashCodePrecomp.contains("private final int hash;"));
assertTrue(withHashCodePrecomp.contains("hash = buildHashCode(name, names);"));
assertTrue(withHashCodePrecomp.contains("return hash;"));
final ImmutableSettings settingsWithoutHashCodePrecomp = settingsBuilder.hashCodePrecomputation(false).hashCodeAndEquals(true)
.build();
final String withoutHashCodePrecomp = ImmutableObjectGenerator.generate(b.toString(), settingsWithoutHashCodePrecomp).getImplCode();
assertFalse(withoutHashCodePrecomp.contains("private static int buildHashCode(final String name, final List<String> names) {"));
assertFalse(withoutHashCodePrecomp.contains("private final int hash;"));
assertFalse(withoutHashCodePrecomp.contains("hash = buildHashCode(name, names);"));
assertFalse(withoutHashCodePrecomp.contains("return hash;"));
}
@Test
public void renderingOf_jsr305Annotations() {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("import javax.annotation.Nonnull;");
b.append("interface TestObject {\n");
b.append("@Nonnull String getName();\n");
b.append("}");
final ImmutableSettings settings = settingsBuilder.jsr305Annotations(true).copyMethods(true).build();
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settings).getImplCode();
assertTrue(generatedCode.contains("@Immutable\npublic final class"));
assertTrue(generatedCode.contains("@Nonnull\n\tpublic static ImmutableTestObject copyOf(@Nonnull "));
assertTrue(generatedCode.contains("public ImmutableTestObject(@Nonnull "));
assertTrue(generatedCode.contains("@Nonnull\n\tprivate final String name;"));
assertTrue(generatedCode.contains("@Nonnull\n\tpublic String getName() {"));
}
@Test
public void renderingOf_packageDeclaration() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("interface TestObject {\n");
b.append("String getName();\n");
b.append("}");
final String generatedCodeWithUndefinedPackage = ImmutableObjectGenerator.generate(b.toString(), settingsBuilder.build())
.getImplCode();
assertFalse(generatedCodeWithUndefinedPackage.contains("package "));
final String withPackage = "package net.sf.qualitycheck;\n";
final String generatedCodeWithPackage = ImmutableObjectGenerator.generate(withPackage + b.toString(), settingsBuilder.build())
.getImplCode();
assertTrue(generatedCodeWithPackage.contains(withPackage));
}
@Test
public void renderingOf_qualityCheck() {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("import javax.annotation.Nonnull;");
b.append("interface TestObject {\n");
b.append("@Nonnull String getName();\n");
b.append("}");
final ImmutableSettings settings = settingsBuilder.qualityCheck(true).copyMethods(true).build();
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settings).getImplCode();
assertTrue(generatedCode.contains("Check.notNull(testObject, \"testObject\");"));
assertTrue(generatedCode.contains("this.name = Check.notNull(name, \"name\");"));
}
@Test
public void renderingOf_replacement() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("interface TestObject {\n");
b.append("String getName();\n");
b.append("}");
final ImmutableSettings settings = settingsBuilder.replacement(true).build();
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settings).getImplCode();
assertTrue(generatedCode.contains("class TestObject {"));
assertTrue(generatedCode.contains("public TestObject(final String name) {"));
}
@Test
public void renderingOf_replacement_serializable() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("interface TestObject {\n");
b.append("String getName();\n");
b.append("}");
final ImmutableSettings settings = settingsBuilder.replacement(true).serializable(true).build();
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settings).getImplCode();
assertTrue(generatedCode.contains("class TestObject implements Serializable {"));
assertTrue(generatedCode.contains("private static final long serialVersionUID = 1L;"));
assertTrue(generatedCode.contains("public TestObject(final String name) {"));
}
@Test
public void renderingOf_serializable() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("interface TestObject {\n");
b.append("String getName();\n");
b.append("}");
final ImmutableSettings settings = settingsBuilder.serializable(true).build();
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settings).getImplCode();
assertTrue(generatedCode.contains("class ImmutableTestObject implements TestObject, Serializable {"));
assertTrue(generatedCode.contains("private static final long serialVersionUID = 1L;"));
}
@Test
public void renderingOf_toString() {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("import java.util.List;\n");
b.append("interface TestObject {\n");
b.append("List<String> getNames();\n");
b.append("int getCount();\n");
b.append("}");
final ImmutableSettings settingsWithToString = settingsBuilder.toString(true).hashCodeAndEquals(true).build();
final String generatedCodeWithToString = ImmutableObjectGenerator.generate(b.toString(), settingsWithToString).getImplCode();
assertTrue(generatedCodeWithToString.contains("public String toString() {"));
assertTrue(generatedCodeWithToString
.contains("return \"ImmutableTestObject [names=\" + this.names + \", count=\" + this.count + \"]\";"));
final ImmutableSettings settingsWithoutToString = settingsBuilder.toString(false).hashCodeAndEquals(true).build();
final String generatedCodeWithoutToString = ImmutableObjectGenerator.generate(b.toString(), settingsWithoutToString).getImplCode();
assertFalse(generatedCodeWithoutToString.contains("public String toString() {"));
}
@Test
public void renderingOf_withBuilder_withBuilderCopyConstructor() {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("import java.util.List;\n");
b.append("interface TestObject {\n");
b.append("List<String> getNamesOfFields();\n");
b.append("}");
final ImmutableSettings settings = settingsBuilder.builderName("Builder").builderCopyConstructor(true).build();
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settings).getImplCode();
assertTrue(generatedCode.contains("public Builder(final TestObject testObject) {"));
assertTrue(generatedCode.contains("this.namesOfFields = new ArrayList<String>(testObject.getNamesOfFields());"));
}
@Test
public void renderingOf_withBuilder_withoutBuilderCopyConstructor() {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("import java.util.List;\n");
b.append("interface TestObject {\n");
b.append("List<String> getNamesOfFields();\n");
b.append("}");
final ImmutableSettings settings = settingsBuilder.builderName("Builder").builderCopyConstructor(false).build();
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settings).getImplCode();
assertFalse(generatedCode.contains("public Builder(final TestObject testObject) {"));
}
@Test
public void renderingOf_withCollection_withoutGeneric() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("import java.util.List;\n");
b.append("interface TestObject {\n");
b.append("List getElements();\n");
b.append("}");
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settingsBuilder.build()).getImplCode();
assertTrue(generatedCode.contains("private final List elements;"));
assertTrue(generatedCode.contains("this.elements = Collections.unmodifiableList(new ArrayList(elements));"));
assertTrue(generatedCode.contains("public List getElements() {"));
}
@Test
public void renderingOf_withConstants() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("interface TestObject {\n");
b.append("String DEFAULT_NAME = \"default\";\n");
b.append("String getName();\n");
b.append("}");
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settingsBuilder.build()).getImplCode();
assertFalse(generatedCode.contains("DEFAULT_NAME"));
}
@Test
public void renderingOf_withCovariance() {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("import java.util.List;\n");
b.append("interface TestObject {\n");
b.append("List<? extends TestObject> getChildren();\n");
b.append("}");
final ImmutableSettings settings = settingsBuilder.fieldPrefix("_").build();
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settings).getImplCode();
assertTrue(generatedCode.contains("private final List<? extends TestObject> _children;"));
assertTrue(generatedCode.contains("public ImmutableTestObject(final List<? extends TestObject> children) {"));
assertTrue(generatedCode.contains("this._children = Collections.unmodifiableList(new ArrayList<? extends TestObject>(children));"));
assertTrue(generatedCode.contains("public List<? extends TestObject> getChildren() {"));
}
@Test
public void renderingOf_withGeneric() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("interface TestObject {\n");
b.append("List<String> getNames();\n");
b.append("}");
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settingsBuilder.build()).getImplCode();
assertTrue(generatedCode.contains("private final List<String> names;"));
assertTrue(generatedCode.contains("public List<String> getNames() {"));
}
@Test
public void renderingOf_withInnerCompilationUnit() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("interface TestObject {\n");
b.append("interface InnerInterface {\n");
b.append("String getName();\n");
b.append("}\n");
b.append("InnerInterface getInnerInterface();\n");
b.append("}");
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settingsBuilder.build()).getImplCode();
assertTrue(generatedCode.contains("private final InnerInterface innerInterface;"));
assertTrue(generatedCode.contains("public InnerInterface getInnerInterface()"));
}
@Test
public void renderingOf_withReservedWord() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("package net.sf.qualitycheck.test;\n");
b.append("interface TestObject {\n");
b.append("Import getImport();\n");
b.append("}");
final String generatedCode = ImmutableObjectGenerator.generate(b.toString(), settingsBuilder.build()).getImplCode();
assertTrue(generatedCode.contains("private final Import import1;"));
assertTrue(generatedCode.contains("ImmutableTestObject(final Import import1)"));
assertTrue(generatedCode.contains("public Import getImport() {"));
}
@Test
public void testCarInterface() throws IOException {
final ImmutableSettings.Builder settings = new ImmutableSettings.Builder();
// global settings
settings.fieldPrefix("");
settings.jsr305Annotations(true);
settings.guava(false);
settings.qualityCheck(true);
// immutable settings
settings.copyMethods(true);
settings.hashCodePrecomputation(false);
settings.hashCodeAndEquals(true);
settings.serializable(false);
// builder settings
settings.builderCopyConstructor(true);
settings.builderFlatMutators(false);
settings.builderFluentMutators(true);
settings.builderName("Builder");
settings.builderImplementsInterface(true);
final String file = "Car.java";
assertEquals(readReferenceImmutable(file), readInterfaceAndGenerate(file, settings.build()));
}
@Test
public void testSettingsInterface() throws IOException {
final ImmutableSettings.Builder settings = new ImmutableSettings.Builder();
// global settings
settings.fieldPrefix("_");
settings.jsr305Annotations(true);
settings.guava(true);
settings.qualityCheck(true);
// immutable settings
settings.copyMethods(true);
settings.hashCodePrecomputation(true);
settings.hashCodeAndEquals(true);
settings.replacement(false);
settings.serializable(true);
settings.toString(true);
// builder settings
settings.builderCopyConstructor(true);
settings.builderFlatMutators(false);
settings.builderFluentMutators(true);
settings.builderName("Builder");
settings.builderImplementsInterface(false);
- final String file = "VirtualFilePermission.java";
+ final String file = "Settings.java";
LOG.info("\n" + readInterfaceAndGenerate(file, settings.build()));
}
@Test(expected = IllegalStateOfArgumentException.class)
public void throwsException_hasPossibleMutatingMethods_withGetterArguments() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("interface TestObject {\n");
b.append("String getName(int index);\n");
b.append("}");
ImmutableObjectGenerator.generate(b.toString(), settingsBuilder.build());
}
@Test(expected = IllegalStateOfArgumentException.class)
public void throwsException_hasPossibleMutatingMethods_withSetter() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("interface TestObject {\n");
b.append("void setName(String name);\n");
b.append("}");
ImmutableObjectGenerator.generate(b.toString(), settingsBuilder.build());
}
@Test(expected = IllegalStateOfArgumentException.class)
public void throwsException_moreThenOneCompilationUnit() throws IOException {
final StringBuilder b = new StringBuilder();
b.append("interface TestObject {\n");
b.append("String getName();\n");
b.append("}\n");
b.append("interface TestObject2 {\n");
b.append("String getName();\n");
b.append("}");
ImmutableObjectGenerator.generate(b.toString(), settingsBuilder.build());
}
}
| true | true | public void testSettingsInterface() throws IOException {
final ImmutableSettings.Builder settings = new ImmutableSettings.Builder();
// global settings
settings.fieldPrefix("_");
settings.jsr305Annotations(true);
settings.guava(true);
settings.qualityCheck(true);
// immutable settings
settings.copyMethods(true);
settings.hashCodePrecomputation(true);
settings.hashCodeAndEquals(true);
settings.replacement(false);
settings.serializable(true);
settings.toString(true);
// builder settings
settings.builderCopyConstructor(true);
settings.builderFlatMutators(false);
settings.builderFluentMutators(true);
settings.builderName("Builder");
settings.builderImplementsInterface(false);
final String file = "VirtualFilePermission.java";
LOG.info("\n" + readInterfaceAndGenerate(file, settings.build()));
}
| public void testSettingsInterface() throws IOException {
final ImmutableSettings.Builder settings = new ImmutableSettings.Builder();
// global settings
settings.fieldPrefix("_");
settings.jsr305Annotations(true);
settings.guava(true);
settings.qualityCheck(true);
// immutable settings
settings.copyMethods(true);
settings.hashCodePrecomputation(true);
settings.hashCodeAndEquals(true);
settings.replacement(false);
settings.serializable(true);
settings.toString(true);
// builder settings
settings.builderCopyConstructor(true);
settings.builderFlatMutators(false);
settings.builderFluentMutators(true);
settings.builderName("Builder");
settings.builderImplementsInterface(false);
final String file = "Settings.java";
LOG.info("\n" + readInterfaceAndGenerate(file, settings.build()));
}
|
diff --git a/src/main/java/com/prealpha/dcputil/compiler/lexer/Lexer.java b/src/main/java/com/prealpha/dcputil/compiler/lexer/Lexer.java
index c7805ef..5de90a1 100755
--- a/src/main/java/com/prealpha/dcputil/compiler/lexer/Lexer.java
+++ b/src/main/java/com/prealpha/dcputil/compiler/lexer/Lexer.java
@@ -1,60 +1,64 @@
package com.prealpha.dcputil.compiler.lexer;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* User: Ty
* Date: 7/12/12
* Time: 3:45 AM
*/
public class Lexer {
private String inputString = "";
public Lexer(){
}
public List<Expression> lex(String input){
this.inputString = input;
List<Expression> tokenList = new ArrayList<Expression>();
String[] lines = input.split("\n");
int ln = 1;
for(String line:lines){
tokenList.addAll(lexLine(line, ln));
ln++;
}
return tokenList;
}
private static final Pattern section = Pattern.compile("(:?\\[? *\\w+\\+?\\w* *\\]?)([;.*]?)");
public List<Expression> lexLine(String line, int linNum){
line = line.trim();
line = line.replace(","," ");
- line = line.split(";")[0];
+ if (line.equals(";")) {
+ line = "";
+ } else {
+ line = line.split(";")[0];
+ }
String[] segments = line.split("\\|");
List<Expression> expressions = new ArrayList<Expression>();
for(String s:segments){
List<Token> tokens = new ArrayList<Token>(3);
Matcher matcher = section.matcher(s);
int start = 0;
while(matcher.find(start)){
String token = matcher.group(1).trim();
start = matcher.end(1);
tokens.add(new Token(token,linNum));
}
if(tokens.size()>0){
expressions.add(new Expression(tokens.toArray(new Token[tokens.size()])));
}
}
return expressions;
}
}
| true | true | public List<Expression> lexLine(String line, int linNum){
line = line.trim();
line = line.replace(","," ");
line = line.split(";")[0];
String[] segments = line.split("\\|");
List<Expression> expressions = new ArrayList<Expression>();
for(String s:segments){
List<Token> tokens = new ArrayList<Token>(3);
Matcher matcher = section.matcher(s);
int start = 0;
while(matcher.find(start)){
String token = matcher.group(1).trim();
start = matcher.end(1);
tokens.add(new Token(token,linNum));
}
if(tokens.size()>0){
expressions.add(new Expression(tokens.toArray(new Token[tokens.size()])));
}
}
return expressions;
}
| public List<Expression> lexLine(String line, int linNum){
line = line.trim();
line = line.replace(","," ");
if (line.equals(";")) {
line = "";
} else {
line = line.split(";")[0];
}
String[] segments = line.split("\\|");
List<Expression> expressions = new ArrayList<Expression>();
for(String s:segments){
List<Token> tokens = new ArrayList<Token>(3);
Matcher matcher = section.matcher(s);
int start = 0;
while(matcher.find(start)){
String token = matcher.group(1).trim();
start = matcher.end(1);
tokens.add(new Token(token,linNum));
}
if(tokens.size()>0){
expressions.add(new Expression(tokens.toArray(new Token[tokens.size()])));
}
}
return expressions;
}
|
diff --git a/loci/visbio/data/DatasetPane.java b/loci/visbio/data/DatasetPane.java
index 4149ea4..d56ad68 100644
--- a/loci/visbio/data/DatasetPane.java
+++ b/loci/visbio/data/DatasetPane.java
@@ -1,639 +1,644 @@
//
// DatasetPane.java
//
/*
VisBio application for visualization of multidimensional
biological image data. Copyright (C) 2002-2005 Curtis Rueden.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.visbio.data;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import loci.ome.xml.OMENode;
import loci.ome.xml.DOMUtil;
import loci.visbio.VisBioFrame;
import loci.visbio.util.*;
import org.w3c.dom.Element;
import visad.VisADException;
import visad.util.Util;
/**
* DatasetPane provides a full-featured set of options
* for importing a multidimensional data series into VisBio.
*/
public class DatasetPane extends WizardPane implements DocumentListener {
// -- Constants --
/** Common dimensional types. */
private static final String[] DIM_TYPES = {
"Time", "Slice", "Channel", "Spectra", "Lifetime"
};
// -- GUI components, page 1 --
/** Choose file dialog box. */
private JFileChooser fileBox;
/** File group text field. */
private JTextField groupField;
// -- GUI components, page 2 --
/** Dataset name text field. */
private JTextField nameField;
/** Panel for dynamic second page components. */
private JPanel second;
/** Dimensional widgets. */
private BioComboBox[] widgets;
/** Combo box for selecting each file's dimensional content. */
private BioComboBox dimBox;
/** Checkbox for whether to use micron information. */
private JCheckBox useMicrons;
/** Text field for width in microns. */
private JTextField micronWidth;
/** Text field for height in microns. */
private JTextField micronHeight;
/** Text field for step size in microns. */
private JTextField micronStep;
/** Panel containing micron-related widgets. */
private JPanel micronPanel;
// -- Other fields --
/** Associate data manager. */
private DataManager dm;
/** File pattern. */
private FilePattern fp;
/** List of data files. */
private String[] ids;
/** Raw dataset created from import pane state. */
private Dataset data;
/** Next free id number for dataset naming scheme. */
private int nameId;
// -- Constructor --
/** Creates a file group import dialog. */
public DatasetPane(DataManager dm) {
this(dm, SwingUtil.getVisBioFileChooser());
}
/** Creates a file group import dialog with the given file chooser. */
public DatasetPane(DataManager dm, JFileChooser fileChooser) {
super("Import data");
this.dm = dm;
fileBox = fileChooser;
// -- Page 1 --
// file pattern field
groupField = new JTextField(25);
groupField.getDocument().addDocumentListener(this);
// select file button
JButton select = new JButton("Select file");
select.setMnemonic('s');
select.setActionCommand("select");
select.addActionListener(this);
// lay out first page
PanelBuilder builder = new PanelBuilder(new FormLayout(
"pref, 3dlu, pref:grow, 3dlu, pref", "pref, 3dlu, pref"));
CellConstraints cc = new CellConstraints();
builder.addLabel("File &pattern", cc.xy(1, 1)).setLabelFor(groupField);
builder.add(groupField, cc.xy(3, 1));
builder.add(select, cc.xy(5, 1));
JPanel first = builder.getPanel();
// -- Page 2 --
// dataset name field
nameField = new JTextField(4);
// combo box for dimensional range type within each file
dimBox = new BioComboBox(DIM_TYPES);
dimBox.setEditable(true);
// microns checkbox
useMicrons = new JCheckBox("Use microns instead of pixels");
if (!LAFUtil.isMacLookAndFeel()) useMicrons.setMnemonic('u');
useMicrons.setActionCommand("microns");
useMicrons.addActionListener(this);
// width in microns field
micronWidth = new JTextField(4);
micronWidth.setToolTipText("Width of each image in microns");
// height in microns field
micronHeight = new JTextField(4);
micronHeight.setToolTipText("Height of each image in microns");
// micron step size field
micronStep = new JTextField(4);
micronStep.setToolTipText("Distance between slices in microns");
// panel with micron-related widgets
micronPanel = FormsUtil.makeRow(new Object[]
{useMicrons, micronWidth, "x", micronHeight, "step", micronStep},
new boolean[] {false, true, false, true, false, true});
// lay out second page
second = new JPanel();
second.setLayout(new BorderLayout());
setPages(new JPanel[] {first, second});
next.setEnabled(false);
}
// -- DatasetPane API methods --
/** Examines the given file to determine if it is part of a file group. */
public void selectFile(File file) {
if (file == null || file.isDirectory()) {
groupField.setText("");
return;
}
String pattern = FilePattern.findPattern(file);
if (pattern == null) {
groupField.setText(file.getAbsolutePath());
return;
}
groupField.setText(pattern);
}
// -- ActionListener API methods --
/** Handles button press events. */
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("select")) {
// start file chooser in the directory specified in the file pattern
String groupText = groupField.getText();
if (groupText.startsWith("~")) {
String userHome = System.getProperty("user.home");
if (userHome != null) {
groupText = userHome + File.separator + groupText.substring(1);
}
}
File dir = new File(groupText);
if (dir.isDirectory()) {
fileBox.setCurrentDirectory(dir);
fileBox.setSelectedFile(null);
}
else {
File file = dir;
dir = dir = dir.getParentFile();
if (dir != null && dir.isDirectory()) fileBox.setCurrentDirectory(dir);
if (file.exists()) fileBox.setSelectedFile(file);
}
int returnVal = fileBox.showOpenDialog(this);
if (returnVal != JFileChooser.APPROVE_OPTION) return;
selectFile(fileBox.getSelectedFile());
}
else if (command.equals("microns")) {
toggleMicronPanel(useMicrons.isSelected());
}
else if (command.equals("next")) {
// lay out page 2 in a separate thread
SwingUtil.setWaitCursor(this, true);
disableButtons();
new Thread("VisBio-CheckDatasetThread") {
public void run() { buildPage(); }
}.start();
}
else if (command.equals("ok")) { // Finish
// check parameters
final String name = nameField.getText();
final String pattern = groupField.getText();
final int[] lengths = fp.getCount();
final String[] files = fp.getFiles();
int len = lengths.length;
boolean use = useMicrons.isSelected();
float width = Float.NaN, height = Float.NaN, step = Float.NaN;
try {
width = use ? Float.parseFloat(micronWidth.getText()) : Float.NaN;
height = use ? Float.parseFloat(micronHeight.getText()) : Float.NaN;
step = use ? Float.parseFloat(micronStep.getText()) : Float.NaN;
}
catch (NumberFormatException exc) { }
if (use) {
String msg = null;
if (width != width || width <= 0) {
msg = "Invalid physical image width.";
}
else if (height != height || height <= 0) {
msg = "Invalid physical image height.";
}
else if (step != step || step <= 0) {
msg = "Invalid physical slice distance.";
}
if (msg != null) {
JOptionPane.showMessageDialog(dialog,
msg, "VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
}
final float mw = width;
final float mh = height;
final float sd = step;
// compile information on dimensional types
boolean b = dimBox.isEnabled();
final String[] dims = new String[b ? len + 1 : len];
for (int i=0; i<len; i++) {
dims[i] = (String) widgets[i].getSelectedItem();
}
if (b) dims[len] = (String) dimBox.getSelectedItem();
// construct data object
super.actionPerformed(e);
new Thread("VisBio-FinishDatasetThread") {
public void run() {
dm.createDataset(name, pattern,
files, lengths, dims, mw, mh, sd, null);
}
}.start();
}
else super.actionPerformed(e);
}
// -- DocumentListener API methods --
/** Gives notification that an attribute or set of attributes changed. */
public void changedUpdate(DocumentEvent e) { checkText(); }
/** Gives notification that there was an insert into the document. */
public void insertUpdate(DocumentEvent e) { checkText(); }
/** Gives notification that a portion of the document has been removed. */
public void removeUpdate(DocumentEvent e) { checkText(); }
// -- Helper methods --
/** Helper method for DocumentListener methods. */
protected void checkText() {
next.setEnabled(!groupField.getText().trim().equals(""));
}
/** Builds the dataset pane's second page. */
protected void buildPage() {
// lay out page 2
String pattern = groupField.getText();
// parse file pattern
fp = new FilePattern(pattern);
if (!fp.isValid()) {
SwingUtil.setWaitCursor(dialog, false);
+ enableButtons();
JOptionPane.showMessageDialog(dialog, fp.getErrorMessage(),
"VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
int index = pattern.lastIndexOf(File.separator);
String path = index < 0 ? "" : pattern.substring(0, index);
pattern = pattern.substring(index + 1);
// guess at a good name for the dataset
String prefix = fp.getPrefix();
nameField.setText(prefix.equals("") ? "data" + ++nameId : prefix);
// check for matching files
BigInteger[] min = fp.getFirst();
BigInteger[] max = fp.getLast();
BigInteger[] step = fp.getStep();
ids = fp.getFiles();
if (ids.length < 1) {
SwingUtil.setWaitCursor(dialog, false);
+ enableButtons();
JOptionPane.showMessageDialog(dialog, "No files match the pattern.",
"VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
int blocks = min.length;
// check that pattern is not empty
if (ids[0].trim().equals("")) {
SwingUtil.setWaitCursor(dialog, false);
+ enableButtons();
JOptionPane.showMessageDialog(dialog, "Please enter a file pattern, " +
"or click \"Select file\" to choose a file.", "VisBio",
JOptionPane.INFORMATION_MESSAGE);
return;
}
// check that first file really exists
File file = new File(ids[0]);
String filename = "\"" + file.getName() + "\"";
if (!file.exists()) {
SwingUtil.setWaitCursor(dialog, false);
+ enableButtons();
JOptionPane.showMessageDialog(dialog, "File " + filename +
" does not exist.", "VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
// get number of images and OME-XML metadata from the first file
OMENode ome = null;
int numImages = 0;
ImageFamily loader = new ImageFamily();
try {
numImages = loader.getBlockCount(ids[0]);
ome = (OMENode) loader.getOMENode(ids[0]);
}
catch (IOException exc) {
if (VisBioFrame.DEBUG) exc.printStackTrace();
}
catch (VisADException exc) {
if (VisBioFrame.DEBUG) exc.printStackTrace();
}
if (numImages < 1) {
SwingUtil.setWaitCursor(dialog, false);
+ enableButtons();
JOptionPane.showMessageDialog(dialog,
"Cannot determine number of images per file.\n" + filename +
" may be corrupt or invalid.", "VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
// extract dimensional axis counts from OME-XML metadata
String dimOrder = null;
int sizeZ = 1, sizeT = 1, sizeC = 1;
if (ome != null) {
try {
Element pix = DOMUtil.findElement("Pixels", ome.getOMEDocument(true));
String z = DOMUtil.getAttribute("SizeZ", pix);
if (z != null && !z.equals("")) sizeZ = Integer.parseInt(z);
String t = DOMUtil.getAttribute("SizeT", pix);
if (t != null && !t.equals("")) sizeT = Integer.parseInt(t);
String c = DOMUtil.getAttribute("SizeC", pix);
if (c != null && !c.equals("")) sizeC = Integer.parseInt(c);
dimOrder = DOMUtil.getAttribute("DimensionOrder", pix);
}
catch (Exception exc) {
if (VisBioFrame.DEBUG) exc.printStackTrace();
}
}
// autodetect dimensional types
String[] kind = new String[blocks];
int other = 1;
boolean timeOk = true, sliceOk = true, channelOk = true, otherOk = true;
for (int i=0; i<blocks; i++) {
String p = fp.getPrefix(i).toLowerCase();
// look for labels indicating dimensional type
if (sliceOk && p.endsWith("focalplane")) {
kind[i] = "Slice";
sliceOk = false;
continue;
}
// strip off trailing non-letters
int q;
char[] c = p.toCharArray();
for (q=c.length; q>0; q--) if (c[q-1] >= 'a' && c[q-1] <= 'z') break;
p = p.substring(0, q);
// strip off leading letters
c = p.toCharArray();
for (q=c.length; q>0; q--) if (c[q-1] < 'a' || c[q-1] > 'z') break;
p = p.substring(q);
// look for short letter code indicating dimensional type
if (timeOk && (p.equals("t") || p.equals("tp") || p.equals("tl"))) {
kind[i] = "Time";
timeOk = false;
}
else if (sliceOk &&
(p.equals("z") || p.equals("zs") || p.equals("fp")))
{
kind[i] = "Slice";
sliceOk = false;
}
else if (channelOk && p.equals("c")) {
kind[i] = "Channel";
channelOk = false;
}
else if (timeOk) {
kind[i] = "Time";
timeOk = false;
}
else if (sliceOk) {
kind[i] = "Slice";
sliceOk = false;
}
else if (channelOk) {
kind[i] = "Channel";
channelOk = false;
}
else if (otherOk) {
kind[i] = "Other";
otherOk = false;
}
else kind[i] = "Other" + ++other;
}
if (timeOk) dimBox.setSelectedIndex(0);
else if (sliceOk) dimBox.setSelectedIndex(1);
else if (channelOk) dimBox.setSelectedIndex(2);
else if (otherOk) dimBox.setSelectedItem("Other");
else dimBox.setSelectedItem("Other" + ++other);
// construct dimensional widgets
widgets = new BioComboBox[blocks];
for (int i=0; i<blocks; i++) {
widgets[i] = new BioComboBox(DIM_TYPES);
widgets[i].setEditable(true);
widgets[i].setSelectedItem(kind[i]);
}
// HACK - ignore buggy dimensional axis counts
if (sizeZ * sizeT * sizeC != numImages) dimOrder = null;
// lay out dimensions panel
JPanel dimPanel = null;
boolean multiFiles = dimOrder != null &&
(sizeZ > 1 || sizeT > 1 || sizeC > 1);
if (multiFiles || numImages > 1 || blocks > 0) {
StringBuffer sb = new StringBuffer("pref");
if (multiFiles) {
if (sizeZ > 1) sb.append(", 3dlu, pref");
if (sizeT > 1) sb.append(", 3dlu, pref");
if (sizeC > 1) sb.append(", 3dlu, pref");
}
else if (numImages > 1) sb.append(", 3dlu, pref");
for (int i=0; i<blocks; i++) sb.append(", 3dlu, pref");
sb.append(", 9dlu");
PanelBuilder builder = new PanelBuilder(new FormLayout(
"pref, 12dlu, pref, 12dlu, pref:grow", sb.toString()));
CellConstraints cc = new CellConstraints();
builder.addSeparator("Dimensions", cc.xyw(1, 1, 5));
int count = 0;
if (multiFiles) {
StringBuffer dimCross = new StringBuffer();
for (int i=2; i<5; i++) {
char c = dimOrder.charAt(i);
switch (c) {
case 'Z':
if (sizeZ > 1) {
int y = 2 * count + 3;
builder.addLabel((count + 1) + ".",
cc.xy(1, y, "right, center"));
builder.addLabel("Slice", cc.xy(3, y, "left, center"));
builder.addLabel(sizeZ + " focal planes per file",
cc.xy(5, y, "left, center"));
if (dimCross.length() > 0) dimCross.append(" x ");
dimCross.append("Slice");
count++;
}
break;
case 'T':
if (sizeT > 1) {
int y = 2 * count + 3;
builder.addLabel((count + 1) + ".",
cc.xy(1, y, "right, center"));
builder.addLabel("Time", cc.xy(3, y, "left, center"));
builder.addLabel(sizeT + " time points per file",
cc.xy(5, y, "left, center"));
if (dimCross.length() > 0) dimCross.append(" x ");
dimCross.append("Time");
count++;
}
break;
case 'C':
if (sizeC > 1) {
int y = 2 * count + 3;
builder.addLabel((count + 1) + ".",
cc.xy(1, y, "right, center"));
builder.addLabel("Channel", cc.xy(3, y, "left, center"));
builder.addLabel(sizeC + " pixel channels per file",
cc.xy(5, y, "left, center"));
if (dimCross.length() > 0) dimCross.append(" x ");
dimCross.append("Channel");
count++;
}
break;
}
}
dimBox.setEnabled(true);
dimBox.setSelectedItem(dimCross.toString());
}
else if (numImages > 1) {
String num = (count + 1) + ".";
if (count < 9) num = "&" + num;
int y = 2 * count + 3;
builder.addLabel(num,
cc.xy(1, y, "right, center")).setLabelFor(dimBox);
dimBox.setEnabled(true);
builder.add(dimBox, cc.xy(3, y, "left, center"));
builder.addLabel(numImages + " images per file",
cc.xy(5, y, "left, center"));
count++;
}
else dimBox.setEnabled(false);
for (int i=0; i<blocks; i++) {
String num = (count + 1) + ".";
if (count < 9) num = "&" + num;
int y = 2 * count + 3;
builder.addLabel(num,
cc.xy(1, y, "right, center")).setLabelFor(widgets[i]);
builder.add(widgets[i], cc.xy(3, y, "left, center"));
builder.addLabel(fp.getBlock(i), cc.xy(5, y, "left, center"));
count++;
}
dimPanel = builder.getPanel();
}
// lay out widget panel
StringBuffer sb = new StringBuffer();
sb.append("pref, 3dlu, pref, 3dlu, pref, 3dlu, pref");
if (dimPanel != null) sb.append(", 9dlu, pref");
PanelBuilder builder = new PanelBuilder(new FormLayout(
"pref, 3dlu, pref:grow", sb.toString()));
CellConstraints cc = new CellConstraints();
JLabel pathLabel = new JLabel("File path");
pathLabel.setFont(pathLabel.getFont().deriveFont(Font.BOLD));
builder.add(pathLabel, cc.xy(1, 1, "right, center"));
builder.addLabel(path, cc.xy(3, 1, "left, center"));
JLabel patternLabel = new JLabel("File pattern");
patternLabel.setFont(patternLabel.getFont().deriveFont(Font.BOLD));
builder.add(patternLabel, cc.xy(1, 3, "right, center"));
builder.addLabel(pattern, cc.xy(3, 3, "left, center"));
JLabel nameLabel = new JLabel("Dataset name");
nameLabel.setFont(nameLabel.getFont().deriveFont(Font.BOLD));
nameLabel.setDisplayedMnemonic('n');
nameLabel.setLabelFor(nameField);
builder.add(nameLabel, cc.xy(1, 5, "right, center"));
builder.add(nameField, cc.xy(3, 5));
builder.add(micronPanel, cc.xyw(1, 7, 3));
if (dimPanel != null) builder.add(dimPanel, cc.xyw(1, 9, 3));
second.removeAll();
second.add(builder.getPanel());
// clear out micron information
micronWidth.setText("");
micronHeight.setText("");
micronStep.setText("");
useMicrons.setSelected(false);
toggleMicronPanel(false);
Util.invoke(false, new Runnable() {
public void run() {
setPage(1);
repack();
SwingUtil.setWaitCursor(dialog, false);
enableButtons();
}
});
}
/** Toggles availability of micron-related widgets. */
protected void toggleMicronPanel(boolean on) {
int count = micronPanel.getComponentCount();
for (int i=1; i<count; i++) micronPanel.getComponent(i).setEnabled(on);
}
}
| false | true | protected void buildPage() {
// lay out page 2
String pattern = groupField.getText();
// parse file pattern
fp = new FilePattern(pattern);
if (!fp.isValid()) {
SwingUtil.setWaitCursor(dialog, false);
JOptionPane.showMessageDialog(dialog, fp.getErrorMessage(),
"VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
int index = pattern.lastIndexOf(File.separator);
String path = index < 0 ? "" : pattern.substring(0, index);
pattern = pattern.substring(index + 1);
// guess at a good name for the dataset
String prefix = fp.getPrefix();
nameField.setText(prefix.equals("") ? "data" + ++nameId : prefix);
// check for matching files
BigInteger[] min = fp.getFirst();
BigInteger[] max = fp.getLast();
BigInteger[] step = fp.getStep();
ids = fp.getFiles();
if (ids.length < 1) {
SwingUtil.setWaitCursor(dialog, false);
JOptionPane.showMessageDialog(dialog, "No files match the pattern.",
"VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
int blocks = min.length;
// check that pattern is not empty
if (ids[0].trim().equals("")) {
SwingUtil.setWaitCursor(dialog, false);
JOptionPane.showMessageDialog(dialog, "Please enter a file pattern, " +
"or click \"Select file\" to choose a file.", "VisBio",
JOptionPane.INFORMATION_MESSAGE);
return;
}
// check that first file really exists
File file = new File(ids[0]);
String filename = "\"" + file.getName() + "\"";
if (!file.exists()) {
SwingUtil.setWaitCursor(dialog, false);
JOptionPane.showMessageDialog(dialog, "File " + filename +
" does not exist.", "VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
// get number of images and OME-XML metadata from the first file
OMENode ome = null;
int numImages = 0;
ImageFamily loader = new ImageFamily();
try {
numImages = loader.getBlockCount(ids[0]);
ome = (OMENode) loader.getOMENode(ids[0]);
}
catch (IOException exc) {
if (VisBioFrame.DEBUG) exc.printStackTrace();
}
catch (VisADException exc) {
if (VisBioFrame.DEBUG) exc.printStackTrace();
}
if (numImages < 1) {
SwingUtil.setWaitCursor(dialog, false);
JOptionPane.showMessageDialog(dialog,
"Cannot determine number of images per file.\n" + filename +
" may be corrupt or invalid.", "VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
// extract dimensional axis counts from OME-XML metadata
String dimOrder = null;
int sizeZ = 1, sizeT = 1, sizeC = 1;
if (ome != null) {
try {
Element pix = DOMUtil.findElement("Pixels", ome.getOMEDocument(true));
String z = DOMUtil.getAttribute("SizeZ", pix);
if (z != null && !z.equals("")) sizeZ = Integer.parseInt(z);
String t = DOMUtil.getAttribute("SizeT", pix);
if (t != null && !t.equals("")) sizeT = Integer.parseInt(t);
String c = DOMUtil.getAttribute("SizeC", pix);
if (c != null && !c.equals("")) sizeC = Integer.parseInt(c);
dimOrder = DOMUtil.getAttribute("DimensionOrder", pix);
}
catch (Exception exc) {
if (VisBioFrame.DEBUG) exc.printStackTrace();
}
}
// autodetect dimensional types
String[] kind = new String[blocks];
int other = 1;
boolean timeOk = true, sliceOk = true, channelOk = true, otherOk = true;
for (int i=0; i<blocks; i++) {
String p = fp.getPrefix(i).toLowerCase();
// look for labels indicating dimensional type
if (sliceOk && p.endsWith("focalplane")) {
kind[i] = "Slice";
sliceOk = false;
continue;
}
// strip off trailing non-letters
int q;
char[] c = p.toCharArray();
for (q=c.length; q>0; q--) if (c[q-1] >= 'a' && c[q-1] <= 'z') break;
p = p.substring(0, q);
// strip off leading letters
c = p.toCharArray();
for (q=c.length; q>0; q--) if (c[q-1] < 'a' || c[q-1] > 'z') break;
p = p.substring(q);
// look for short letter code indicating dimensional type
if (timeOk && (p.equals("t") || p.equals("tp") || p.equals("tl"))) {
kind[i] = "Time";
timeOk = false;
}
else if (sliceOk &&
(p.equals("z") || p.equals("zs") || p.equals("fp")))
{
kind[i] = "Slice";
sliceOk = false;
}
else if (channelOk && p.equals("c")) {
kind[i] = "Channel";
channelOk = false;
}
else if (timeOk) {
kind[i] = "Time";
timeOk = false;
}
else if (sliceOk) {
kind[i] = "Slice";
sliceOk = false;
}
else if (channelOk) {
kind[i] = "Channel";
channelOk = false;
}
else if (otherOk) {
kind[i] = "Other";
otherOk = false;
}
else kind[i] = "Other" + ++other;
}
if (timeOk) dimBox.setSelectedIndex(0);
else if (sliceOk) dimBox.setSelectedIndex(1);
else if (channelOk) dimBox.setSelectedIndex(2);
else if (otherOk) dimBox.setSelectedItem("Other");
else dimBox.setSelectedItem("Other" + ++other);
// construct dimensional widgets
widgets = new BioComboBox[blocks];
for (int i=0; i<blocks; i++) {
widgets[i] = new BioComboBox(DIM_TYPES);
widgets[i].setEditable(true);
widgets[i].setSelectedItem(kind[i]);
}
// HACK - ignore buggy dimensional axis counts
if (sizeZ * sizeT * sizeC != numImages) dimOrder = null;
// lay out dimensions panel
JPanel dimPanel = null;
boolean multiFiles = dimOrder != null &&
(sizeZ > 1 || sizeT > 1 || sizeC > 1);
if (multiFiles || numImages > 1 || blocks > 0) {
StringBuffer sb = new StringBuffer("pref");
if (multiFiles) {
if (sizeZ > 1) sb.append(", 3dlu, pref");
if (sizeT > 1) sb.append(", 3dlu, pref");
if (sizeC > 1) sb.append(", 3dlu, pref");
}
else if (numImages > 1) sb.append(", 3dlu, pref");
for (int i=0; i<blocks; i++) sb.append(", 3dlu, pref");
sb.append(", 9dlu");
PanelBuilder builder = new PanelBuilder(new FormLayout(
"pref, 12dlu, pref, 12dlu, pref:grow", sb.toString()));
CellConstraints cc = new CellConstraints();
builder.addSeparator("Dimensions", cc.xyw(1, 1, 5));
int count = 0;
if (multiFiles) {
StringBuffer dimCross = new StringBuffer();
for (int i=2; i<5; i++) {
char c = dimOrder.charAt(i);
switch (c) {
case 'Z':
if (sizeZ > 1) {
int y = 2 * count + 3;
builder.addLabel((count + 1) + ".",
cc.xy(1, y, "right, center"));
builder.addLabel("Slice", cc.xy(3, y, "left, center"));
builder.addLabel(sizeZ + " focal planes per file",
cc.xy(5, y, "left, center"));
if (dimCross.length() > 0) dimCross.append(" x ");
dimCross.append("Slice");
count++;
}
break;
case 'T':
if (sizeT > 1) {
int y = 2 * count + 3;
builder.addLabel((count + 1) + ".",
cc.xy(1, y, "right, center"));
builder.addLabel("Time", cc.xy(3, y, "left, center"));
builder.addLabel(sizeT + " time points per file",
cc.xy(5, y, "left, center"));
if (dimCross.length() > 0) dimCross.append(" x ");
dimCross.append("Time");
count++;
}
break;
case 'C':
if (sizeC > 1) {
int y = 2 * count + 3;
builder.addLabel((count + 1) + ".",
cc.xy(1, y, "right, center"));
builder.addLabel("Channel", cc.xy(3, y, "left, center"));
builder.addLabel(sizeC + " pixel channels per file",
cc.xy(5, y, "left, center"));
if (dimCross.length() > 0) dimCross.append(" x ");
dimCross.append("Channel");
count++;
}
break;
}
}
dimBox.setEnabled(true);
dimBox.setSelectedItem(dimCross.toString());
}
else if (numImages > 1) {
String num = (count + 1) + ".";
if (count < 9) num = "&" + num;
int y = 2 * count + 3;
builder.addLabel(num,
cc.xy(1, y, "right, center")).setLabelFor(dimBox);
dimBox.setEnabled(true);
builder.add(dimBox, cc.xy(3, y, "left, center"));
builder.addLabel(numImages + " images per file",
cc.xy(5, y, "left, center"));
count++;
}
else dimBox.setEnabled(false);
for (int i=0; i<blocks; i++) {
String num = (count + 1) + ".";
if (count < 9) num = "&" + num;
int y = 2 * count + 3;
builder.addLabel(num,
cc.xy(1, y, "right, center")).setLabelFor(widgets[i]);
builder.add(widgets[i], cc.xy(3, y, "left, center"));
builder.addLabel(fp.getBlock(i), cc.xy(5, y, "left, center"));
count++;
}
dimPanel = builder.getPanel();
}
// lay out widget panel
StringBuffer sb = new StringBuffer();
sb.append("pref, 3dlu, pref, 3dlu, pref, 3dlu, pref");
if (dimPanel != null) sb.append(", 9dlu, pref");
PanelBuilder builder = new PanelBuilder(new FormLayout(
"pref, 3dlu, pref:grow", sb.toString()));
CellConstraints cc = new CellConstraints();
JLabel pathLabel = new JLabel("File path");
pathLabel.setFont(pathLabel.getFont().deriveFont(Font.BOLD));
builder.add(pathLabel, cc.xy(1, 1, "right, center"));
builder.addLabel(path, cc.xy(3, 1, "left, center"));
JLabel patternLabel = new JLabel("File pattern");
patternLabel.setFont(patternLabel.getFont().deriveFont(Font.BOLD));
builder.add(patternLabel, cc.xy(1, 3, "right, center"));
builder.addLabel(pattern, cc.xy(3, 3, "left, center"));
JLabel nameLabel = new JLabel("Dataset name");
nameLabel.setFont(nameLabel.getFont().deriveFont(Font.BOLD));
nameLabel.setDisplayedMnemonic('n');
nameLabel.setLabelFor(nameField);
builder.add(nameLabel, cc.xy(1, 5, "right, center"));
builder.add(nameField, cc.xy(3, 5));
builder.add(micronPanel, cc.xyw(1, 7, 3));
if (dimPanel != null) builder.add(dimPanel, cc.xyw(1, 9, 3));
second.removeAll();
second.add(builder.getPanel());
// clear out micron information
micronWidth.setText("");
micronHeight.setText("");
micronStep.setText("");
useMicrons.setSelected(false);
toggleMicronPanel(false);
Util.invoke(false, new Runnable() {
public void run() {
setPage(1);
repack();
SwingUtil.setWaitCursor(dialog, false);
enableButtons();
}
});
}
| protected void buildPage() {
// lay out page 2
String pattern = groupField.getText();
// parse file pattern
fp = new FilePattern(pattern);
if (!fp.isValid()) {
SwingUtil.setWaitCursor(dialog, false);
enableButtons();
JOptionPane.showMessageDialog(dialog, fp.getErrorMessage(),
"VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
int index = pattern.lastIndexOf(File.separator);
String path = index < 0 ? "" : pattern.substring(0, index);
pattern = pattern.substring(index + 1);
// guess at a good name for the dataset
String prefix = fp.getPrefix();
nameField.setText(prefix.equals("") ? "data" + ++nameId : prefix);
// check for matching files
BigInteger[] min = fp.getFirst();
BigInteger[] max = fp.getLast();
BigInteger[] step = fp.getStep();
ids = fp.getFiles();
if (ids.length < 1) {
SwingUtil.setWaitCursor(dialog, false);
enableButtons();
JOptionPane.showMessageDialog(dialog, "No files match the pattern.",
"VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
int blocks = min.length;
// check that pattern is not empty
if (ids[0].trim().equals("")) {
SwingUtil.setWaitCursor(dialog, false);
enableButtons();
JOptionPane.showMessageDialog(dialog, "Please enter a file pattern, " +
"or click \"Select file\" to choose a file.", "VisBio",
JOptionPane.INFORMATION_MESSAGE);
return;
}
// check that first file really exists
File file = new File(ids[0]);
String filename = "\"" + file.getName() + "\"";
if (!file.exists()) {
SwingUtil.setWaitCursor(dialog, false);
enableButtons();
JOptionPane.showMessageDialog(dialog, "File " + filename +
" does not exist.", "VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
// get number of images and OME-XML metadata from the first file
OMENode ome = null;
int numImages = 0;
ImageFamily loader = new ImageFamily();
try {
numImages = loader.getBlockCount(ids[0]);
ome = (OMENode) loader.getOMENode(ids[0]);
}
catch (IOException exc) {
if (VisBioFrame.DEBUG) exc.printStackTrace();
}
catch (VisADException exc) {
if (VisBioFrame.DEBUG) exc.printStackTrace();
}
if (numImages < 1) {
SwingUtil.setWaitCursor(dialog, false);
enableButtons();
JOptionPane.showMessageDialog(dialog,
"Cannot determine number of images per file.\n" + filename +
" may be corrupt or invalid.", "VisBio", JOptionPane.ERROR_MESSAGE);
return;
}
// extract dimensional axis counts from OME-XML metadata
String dimOrder = null;
int sizeZ = 1, sizeT = 1, sizeC = 1;
if (ome != null) {
try {
Element pix = DOMUtil.findElement("Pixels", ome.getOMEDocument(true));
String z = DOMUtil.getAttribute("SizeZ", pix);
if (z != null && !z.equals("")) sizeZ = Integer.parseInt(z);
String t = DOMUtil.getAttribute("SizeT", pix);
if (t != null && !t.equals("")) sizeT = Integer.parseInt(t);
String c = DOMUtil.getAttribute("SizeC", pix);
if (c != null && !c.equals("")) sizeC = Integer.parseInt(c);
dimOrder = DOMUtil.getAttribute("DimensionOrder", pix);
}
catch (Exception exc) {
if (VisBioFrame.DEBUG) exc.printStackTrace();
}
}
// autodetect dimensional types
String[] kind = new String[blocks];
int other = 1;
boolean timeOk = true, sliceOk = true, channelOk = true, otherOk = true;
for (int i=0; i<blocks; i++) {
String p = fp.getPrefix(i).toLowerCase();
// look for labels indicating dimensional type
if (sliceOk && p.endsWith("focalplane")) {
kind[i] = "Slice";
sliceOk = false;
continue;
}
// strip off trailing non-letters
int q;
char[] c = p.toCharArray();
for (q=c.length; q>0; q--) if (c[q-1] >= 'a' && c[q-1] <= 'z') break;
p = p.substring(0, q);
// strip off leading letters
c = p.toCharArray();
for (q=c.length; q>0; q--) if (c[q-1] < 'a' || c[q-1] > 'z') break;
p = p.substring(q);
// look for short letter code indicating dimensional type
if (timeOk && (p.equals("t") || p.equals("tp") || p.equals("tl"))) {
kind[i] = "Time";
timeOk = false;
}
else if (sliceOk &&
(p.equals("z") || p.equals("zs") || p.equals("fp")))
{
kind[i] = "Slice";
sliceOk = false;
}
else if (channelOk && p.equals("c")) {
kind[i] = "Channel";
channelOk = false;
}
else if (timeOk) {
kind[i] = "Time";
timeOk = false;
}
else if (sliceOk) {
kind[i] = "Slice";
sliceOk = false;
}
else if (channelOk) {
kind[i] = "Channel";
channelOk = false;
}
else if (otherOk) {
kind[i] = "Other";
otherOk = false;
}
else kind[i] = "Other" + ++other;
}
if (timeOk) dimBox.setSelectedIndex(0);
else if (sliceOk) dimBox.setSelectedIndex(1);
else if (channelOk) dimBox.setSelectedIndex(2);
else if (otherOk) dimBox.setSelectedItem("Other");
else dimBox.setSelectedItem("Other" + ++other);
// construct dimensional widgets
widgets = new BioComboBox[blocks];
for (int i=0; i<blocks; i++) {
widgets[i] = new BioComboBox(DIM_TYPES);
widgets[i].setEditable(true);
widgets[i].setSelectedItem(kind[i]);
}
// HACK - ignore buggy dimensional axis counts
if (sizeZ * sizeT * sizeC != numImages) dimOrder = null;
// lay out dimensions panel
JPanel dimPanel = null;
boolean multiFiles = dimOrder != null &&
(sizeZ > 1 || sizeT > 1 || sizeC > 1);
if (multiFiles || numImages > 1 || blocks > 0) {
StringBuffer sb = new StringBuffer("pref");
if (multiFiles) {
if (sizeZ > 1) sb.append(", 3dlu, pref");
if (sizeT > 1) sb.append(", 3dlu, pref");
if (sizeC > 1) sb.append(", 3dlu, pref");
}
else if (numImages > 1) sb.append(", 3dlu, pref");
for (int i=0; i<blocks; i++) sb.append(", 3dlu, pref");
sb.append(", 9dlu");
PanelBuilder builder = new PanelBuilder(new FormLayout(
"pref, 12dlu, pref, 12dlu, pref:grow", sb.toString()));
CellConstraints cc = new CellConstraints();
builder.addSeparator("Dimensions", cc.xyw(1, 1, 5));
int count = 0;
if (multiFiles) {
StringBuffer dimCross = new StringBuffer();
for (int i=2; i<5; i++) {
char c = dimOrder.charAt(i);
switch (c) {
case 'Z':
if (sizeZ > 1) {
int y = 2 * count + 3;
builder.addLabel((count + 1) + ".",
cc.xy(1, y, "right, center"));
builder.addLabel("Slice", cc.xy(3, y, "left, center"));
builder.addLabel(sizeZ + " focal planes per file",
cc.xy(5, y, "left, center"));
if (dimCross.length() > 0) dimCross.append(" x ");
dimCross.append("Slice");
count++;
}
break;
case 'T':
if (sizeT > 1) {
int y = 2 * count + 3;
builder.addLabel((count + 1) + ".",
cc.xy(1, y, "right, center"));
builder.addLabel("Time", cc.xy(3, y, "left, center"));
builder.addLabel(sizeT + " time points per file",
cc.xy(5, y, "left, center"));
if (dimCross.length() > 0) dimCross.append(" x ");
dimCross.append("Time");
count++;
}
break;
case 'C':
if (sizeC > 1) {
int y = 2 * count + 3;
builder.addLabel((count + 1) + ".",
cc.xy(1, y, "right, center"));
builder.addLabel("Channel", cc.xy(3, y, "left, center"));
builder.addLabel(sizeC + " pixel channels per file",
cc.xy(5, y, "left, center"));
if (dimCross.length() > 0) dimCross.append(" x ");
dimCross.append("Channel");
count++;
}
break;
}
}
dimBox.setEnabled(true);
dimBox.setSelectedItem(dimCross.toString());
}
else if (numImages > 1) {
String num = (count + 1) + ".";
if (count < 9) num = "&" + num;
int y = 2 * count + 3;
builder.addLabel(num,
cc.xy(1, y, "right, center")).setLabelFor(dimBox);
dimBox.setEnabled(true);
builder.add(dimBox, cc.xy(3, y, "left, center"));
builder.addLabel(numImages + " images per file",
cc.xy(5, y, "left, center"));
count++;
}
else dimBox.setEnabled(false);
for (int i=0; i<blocks; i++) {
String num = (count + 1) + ".";
if (count < 9) num = "&" + num;
int y = 2 * count + 3;
builder.addLabel(num,
cc.xy(1, y, "right, center")).setLabelFor(widgets[i]);
builder.add(widgets[i], cc.xy(3, y, "left, center"));
builder.addLabel(fp.getBlock(i), cc.xy(5, y, "left, center"));
count++;
}
dimPanel = builder.getPanel();
}
// lay out widget panel
StringBuffer sb = new StringBuffer();
sb.append("pref, 3dlu, pref, 3dlu, pref, 3dlu, pref");
if (dimPanel != null) sb.append(", 9dlu, pref");
PanelBuilder builder = new PanelBuilder(new FormLayout(
"pref, 3dlu, pref:grow", sb.toString()));
CellConstraints cc = new CellConstraints();
JLabel pathLabel = new JLabel("File path");
pathLabel.setFont(pathLabel.getFont().deriveFont(Font.BOLD));
builder.add(pathLabel, cc.xy(1, 1, "right, center"));
builder.addLabel(path, cc.xy(3, 1, "left, center"));
JLabel patternLabel = new JLabel("File pattern");
patternLabel.setFont(patternLabel.getFont().deriveFont(Font.BOLD));
builder.add(patternLabel, cc.xy(1, 3, "right, center"));
builder.addLabel(pattern, cc.xy(3, 3, "left, center"));
JLabel nameLabel = new JLabel("Dataset name");
nameLabel.setFont(nameLabel.getFont().deriveFont(Font.BOLD));
nameLabel.setDisplayedMnemonic('n');
nameLabel.setLabelFor(nameField);
builder.add(nameLabel, cc.xy(1, 5, "right, center"));
builder.add(nameField, cc.xy(3, 5));
builder.add(micronPanel, cc.xyw(1, 7, 3));
if (dimPanel != null) builder.add(dimPanel, cc.xyw(1, 9, 3));
second.removeAll();
second.add(builder.getPanel());
// clear out micron information
micronWidth.setText("");
micronHeight.setText("");
micronStep.setText("");
useMicrons.setSelected(false);
toggleMicronPanel(false);
Util.invoke(false, new Runnable() {
public void run() {
setPage(1);
repack();
SwingUtil.setWaitCursor(dialog, false);
enableButtons();
}
});
}
|
diff --git a/src/main/java/ru/urbancamper/audiobookmarker/text/BookText.java b/src/main/java/ru/urbancamper/audiobookmarker/text/BookText.java
index 0cc67f4..44f3a8f 100644
--- a/src/main/java/ru/urbancamper/audiobookmarker/text/BookText.java
+++ b/src/main/java/ru/urbancamper/audiobookmarker/text/BookText.java
@@ -1,170 +1,171 @@
/*
*@autor pozpl
*/
package ru.urbancamper.audiobookmarker.text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeMap;
/**
*Class to hold book text, it's tokenized structure and
* perform operations to improve it with audiobook information.
* @author pozpl
*/
public class BookText {
/**
* the full text of Audiobook in plain text fomat
*/
private String fullText = "";
private String[] tokenizedBookText;
private Integer[] textInNumericForm;
private ArrayList<RecognizedTextOfSingleAudiofile> recognizedAudioFiles;
private LanguageModelBasedTextTokenizer textTokenizer;
private WordsToNumsMap wordsToNumMapper;
private LongestSubsequenceFinder longestSubsequenceFinder;
private HashMap<String, Integer> registredFileMapper;
private BitapSubtextFinding bitapSubtextFinder;
public BookText(LanguageModelBasedTextTokenizer textTokenizer,
WordsToNumsMap wordsToNumMapper,
LongestSubsequenceFinder subsequnceFinder,
BitapSubtextFinding bitapSubtextFinder
){
this.recognizedAudioFiles = new ArrayList<RecognizedTextOfSingleAudiofile>();
this.textTokenizer = textTokenizer;
this.wordsToNumMapper = wordsToNumMapper;
this.longestSubsequenceFinder = subsequnceFinder;
this.registredFileMapper = new HashMap<String, Integer>();
this.bitapSubtextFinder = bitapSubtextFinder;
}
public void setFullText(String fullText){
this.fullText = fullText;
this.tokenizedBookText = textTokenizer.tokenize(fullText);
this.textInNumericForm = this.wordsToNumMapper.getNumbersFromWords(tokenizedBookText);
}
public void registerRecognizedTextPiece(RecognizedTextOfSingleAudiofile recognizedFileText){
this.recognizedAudioFiles.add(recognizedFileText);
this.registredFileMapper.put(recognizedFileText.getAudioFileHash(), this.recognizedAudioFiles.size());
}
public RecognizedTextOfSingleAudiofile[] getListOfRegistredAudiofiles(){
return this.recognizedAudioFiles.toArray(
new RecognizedTextOfSingleAudiofile[this.recognizedAudioFiles.size()]);
}
/**
* Iterate through recognized text peaces and find mapping between words of
* this recognized peaces to full text words
* @return ArrayList of mappings of recognized text to full text
*/
private ArrayList<TreeMap<Integer, Integer>> getLongestSubsequenceMappingFromRecognizedTexts(){
ArrayList<TreeMap<Integer, Integer>> recognizedTextLongestSubsequences = new ArrayList<TreeMap<Integer, Integer>>();
for (Iterator<RecognizedTextOfSingleAudiofile> it = this.recognizedAudioFiles.iterator(); it.hasNext();) {
RecognizedTextOfSingleAudiofile recognizedText = it.next();
String[] recognizedTextAsTokens = recognizedText.getTokens();
Integer[] recognizedTextAsNumbers = this.wordsToNumMapper.getNumbersFromWords(recognizedTextAsTokens);
Integer maxErrors = recognizedTextAsNumbers.length / 3;
+ maxErrors = maxErrors > 4 ? maxErrors : 4;
List<Integer> foundIndexes = this.bitapSubtextFinder.find(
this.textInNumericForm, recognizedTextAsNumbers, maxErrors);
Integer recognizedTextBeginIndex = foundIndexes.size() > 0 ? foundIndexes.get(0)
: 0;
Integer[] fullTextSnippetToAlign = new Integer[recognizedTextAsNumbers.length];
- Integer endOfInterval = recognizedTextAsNumbers.length + recognizedTextBeginIndex;
+ Integer endOfInterval = recognizedTextAsNumbers.length + recognizedTextBeginIndex + maxErrors;
fullTextSnippetToAlign = Arrays.copyOfRange(this.textInNumericForm,
recognizedTextBeginIndex, endOfInterval);
TreeMap<Integer, Integer> recTextLongestSubsequence =
this.longestSubsequenceFinder.getLongestSubsequenceWithMinDistance(fullTextSnippetToAlign, recognizedTextAsNumbers);
recTextLongestSubsequence = this.shiftMappingOfSubText(recTextLongestSubsequence, recognizedTextBeginIndex);
recognizedTextLongestSubsequences.add(recTextLongestSubsequence);
}
return recognizedTextLongestSubsequences;
}
/**
* Shift mapping of sub text relatively of shift
* @param fullSubTextMap - tree map of equality between full text and sub text map
* @param shiftIndex - shift index of sub text in the full text recognized index
* @return return Tree map with shifted results
*/
private TreeMap<Integer, Integer> shiftMappingOfSubText(TreeMap<Integer, Integer> fullSubTextMap,
Integer shiftIndex){
TreeMap<Integer, Integer> shiftedTreeMap = new TreeMap<Integer, Integer>();
for(Integer fullTextWordIndex : fullSubTextMap.keySet()){
Integer shiftedFullTextWordIndex = fullTextWordIndex + shiftIndex;
shiftedTreeMap.put(shiftedFullTextWordIndex,
fullSubTextMap.get(fullTextWordIndex));
}
return shiftedTreeMap;
}
private String constructWordWithMarkInfo(String word, Integer fileIndex,Double startTime){
String fileIndexStr = fileIndex.toString();
String startTimeStr = startTime.toString();
String returnToken = "<" + fileIndexStr + ":" + startTimeStr + "/>" + word;
return returnToken;
}
@Deprecated
private String implodeTokensArray(String[] tokensArray){
String resultString = "";
for(Integer tokensCounter = 0;
tokensCounter < tokensArray.length; tokensCounter++){
String token = tokensArray[tokensCounter];
if(tokensCounter < tokensArray.length - 1){
resultString += token + " ";
}else{
resultString += token;
}
}
return resultString;
}
public String buildTextWithAudioMarks(){
ArrayList<TreeMap<Integer, Integer>> recognizedTextLongestSubsequences = this.getLongestSubsequenceMappingFromRecognizedTexts();
String markedText = "";
Integer subsequenceCounter = 0;
for(TreeMap<Integer, Integer> longestSubsequence: recognizedTextLongestSubsequences){
RecognizedTextOfSingleAudiofile recognizedFile = this.recognizedAudioFiles.get(subsequenceCounter);
Integer fileIndex = this.registredFileMapper.get(recognizedFile.getAudioFileHash());
for(Entry<Integer, Integer> fullTextToRecText: longestSubsequence.entrySet()){
Integer fullTextWordIndex = fullTextToRecText.getKey();
Integer recognizedTextWordIndex = fullTextToRecText.getValue();
Double beginTime = recognizedFile.getBeginTimeOfTokenAtPosition(recognizedTextWordIndex);
Double endTime = recognizedFile.getEndTimeOfTokenAtPosition(recognizedTextWordIndex);
String wordWithMarkerInfo = this.constructWordWithMarkInfo(
this.tokenizedBookText[fullTextWordIndex], fileIndex, beginTime);
this.tokenizedBookText[fullTextWordIndex] = wordWithMarkerInfo;
}
subsequenceCounter++;
}
return this.textTokenizer.deTokenize(tokenizedBookText);//this.implodeTokensArray(this.tokenizedBookText);
}
}
| false | true | private ArrayList<TreeMap<Integer, Integer>> getLongestSubsequenceMappingFromRecognizedTexts(){
ArrayList<TreeMap<Integer, Integer>> recognizedTextLongestSubsequences = new ArrayList<TreeMap<Integer, Integer>>();
for (Iterator<RecognizedTextOfSingleAudiofile> it = this.recognizedAudioFiles.iterator(); it.hasNext();) {
RecognizedTextOfSingleAudiofile recognizedText = it.next();
String[] recognizedTextAsTokens = recognizedText.getTokens();
Integer[] recognizedTextAsNumbers = this.wordsToNumMapper.getNumbersFromWords(recognizedTextAsTokens);
Integer maxErrors = recognizedTextAsNumbers.length / 3;
List<Integer> foundIndexes = this.bitapSubtextFinder.find(
this.textInNumericForm, recognizedTextAsNumbers, maxErrors);
Integer recognizedTextBeginIndex = foundIndexes.size() > 0 ? foundIndexes.get(0)
: 0;
Integer[] fullTextSnippetToAlign = new Integer[recognizedTextAsNumbers.length];
Integer endOfInterval = recognizedTextAsNumbers.length + recognizedTextBeginIndex;
fullTextSnippetToAlign = Arrays.copyOfRange(this.textInNumericForm,
recognizedTextBeginIndex, endOfInterval);
TreeMap<Integer, Integer> recTextLongestSubsequence =
this.longestSubsequenceFinder.getLongestSubsequenceWithMinDistance(fullTextSnippetToAlign, recognizedTextAsNumbers);
recTextLongestSubsequence = this.shiftMappingOfSubText(recTextLongestSubsequence, recognizedTextBeginIndex);
recognizedTextLongestSubsequences.add(recTextLongestSubsequence);
}
return recognizedTextLongestSubsequences;
}
| private ArrayList<TreeMap<Integer, Integer>> getLongestSubsequenceMappingFromRecognizedTexts(){
ArrayList<TreeMap<Integer, Integer>> recognizedTextLongestSubsequences = new ArrayList<TreeMap<Integer, Integer>>();
for (Iterator<RecognizedTextOfSingleAudiofile> it = this.recognizedAudioFiles.iterator(); it.hasNext();) {
RecognizedTextOfSingleAudiofile recognizedText = it.next();
String[] recognizedTextAsTokens = recognizedText.getTokens();
Integer[] recognizedTextAsNumbers = this.wordsToNumMapper.getNumbersFromWords(recognizedTextAsTokens);
Integer maxErrors = recognizedTextAsNumbers.length / 3;
maxErrors = maxErrors > 4 ? maxErrors : 4;
List<Integer> foundIndexes = this.bitapSubtextFinder.find(
this.textInNumericForm, recognizedTextAsNumbers, maxErrors);
Integer recognizedTextBeginIndex = foundIndexes.size() > 0 ? foundIndexes.get(0)
: 0;
Integer[] fullTextSnippetToAlign = new Integer[recognizedTextAsNumbers.length];
Integer endOfInterval = recognizedTextAsNumbers.length + recognizedTextBeginIndex + maxErrors;
fullTextSnippetToAlign = Arrays.copyOfRange(this.textInNumericForm,
recognizedTextBeginIndex, endOfInterval);
TreeMap<Integer, Integer> recTextLongestSubsequence =
this.longestSubsequenceFinder.getLongestSubsequenceWithMinDistance(fullTextSnippetToAlign, recognizedTextAsNumbers);
recTextLongestSubsequence = this.shiftMappingOfSubText(recTextLongestSubsequence, recognizedTextBeginIndex);
recognizedTextLongestSubsequences.add(recTextLongestSubsequence);
}
return recognizedTextLongestSubsequences;
}
|
diff --git a/src/models/Method.java b/src/models/Method.java
index 84cb5af..69da1db 100644
--- a/src/models/Method.java
+++ b/src/models/Method.java
@@ -1,191 +1,193 @@
package models;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.jdt.core.dom.MethodDeclaration;
public class Method {
private String name;
private Clazz clazz;
private int startChar;
private int endChar;
private String returnType;
private List<Method> methodCalls;
private List<Method> calledBy;
private List<Method> fuzzyCalls;
private List<Method> fuzzyCalledBy;
private List<String> unresolvedCalls;
private MethodDeclaration node;
public Method() {
methodCalls = new ArrayList<Method>();
calledBy = new ArrayList<Method>();
fuzzyCalls = new ArrayList<Method>();
fuzzyCalledBy = new ArrayList<Method>();
unresolvedCalls = new ArrayList<String>();
}
public Method(String name, Clazz clazz, ArrayList<Method> methodCalls) {
this.name = name;
this.clazz = clazz;
this.methodCalls = methodCalls;
this.calledBy = new ArrayList<Method>();
fuzzyCalls = new ArrayList<Method>();
fuzzyCalledBy = new ArrayList<Method>();
this.unresolvedCalls = new ArrayList<String>();
}
public Method(String name, Clazz clazz, int start, int end)
{
this.name = name;
this.clazz = clazz;
this.startChar = start;
this.endChar = end;
this.methodCalls = new ArrayList<Method>();
this.calledBy = new ArrayList<Method>();
fuzzyCalls = new ArrayList<Method>();
fuzzyCalledBy = new ArrayList<Method>();
this.unresolvedCalls = new ArrayList<String>();
}
public void addFuzzyCalledBy(Method m) {
if(!fuzzyCalledBy.contains(m))
this.fuzzyCalledBy.add(m);
}
public void addFuzzyCall(Method m) {
if(!fuzzyCalls.contains(m))
this.fuzzyCalls.add(m);
}
public void addCalledBy(Method m) {
if(!calledBy.contains(m))
this.calledBy.add(m);
}
public void addMethodCall(Method m) {
if(!methodCalls.contains(m))
this.methodCalls.add(m);
}
public void addUnresolvedCall(String method) {
if(!unresolvedCalls.contains(method))
this.unresolvedCalls.add(method);
}
public void print() {
System.out.println(" METHOD: " + name);
System.out.println(" Return Type: " + returnType);
+ System.out.println(" Start Character: " + this.startChar);
+ System.out.println(" End Character: " + this.endChar);
System.out.println(" Calls: ");
for(Method m: methodCalls)
System.out.println(" " + m.getName());
System.out.println(" Called By: ");
for(Method m: calledBy)
System.out.println(" " + m.getName());
System.out.println(" Fuzzy Calls: ");
for(Method m: fuzzyCalls)
System.out.println(" " + m.getName());
System.out.println(" Fuzzy Called By: ");
for(Method m: fuzzyCalledBy)
System.out.println(" " + m.getName());
System.out.println(" Unresolved Calls: (" + unresolvedCalls.size() + ")");
for(String m: unresolvedCalls)
System.out.println(" " + m);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
public List<Method> getMethodCalls() {
return methodCalls;
}
public void setMethodCalls(ArrayList<Method> methodCalls) {
this.methodCalls = methodCalls;
}
public List<Method> getCalledBy() {
return calledBy;
}
public void setCalledBy(List<Method> calledBy) {
this.calledBy = calledBy;
}
public int getstartChar() {
return startChar;
}
public void setstartChar(int startChar) {
this.startChar = startChar;
}
public int getendChar() {
return endChar;
}
public void setendChar(int endLine) {
this.endChar = endLine;
}
public String getReturnType() {
return returnType;
}
public void setReturnType(String returnType) {
this.returnType = returnType;
}
public MethodDeclaration getNode() {
return node;
}
public void setNode(MethodDeclaration node) {
this.node = node;
}
public List<String> getUnresolvedCalls() {
return unresolvedCalls;
}
public void setUnresolvedCalls(List<String> unresolvedCalls) {
this.unresolvedCalls = unresolvedCalls;
}
public List<Method> getFuzzyCalls() {
return fuzzyCalls;
}
public void setFuzzyCalls(List<Method> fuzzyCalls) {
this.fuzzyCalls = fuzzyCalls;
}
public List<Method> getFuzzyCalledBy() {
return fuzzyCalledBy;
}
public void setFuzzyCalledBy(List<Method> fuzzyCalledBy) {
this.fuzzyCalledBy = fuzzyCalledBy;
}
}
| true | true | public void print() {
System.out.println(" METHOD: " + name);
System.out.println(" Return Type: " + returnType);
System.out.println(" Calls: ");
for(Method m: methodCalls)
System.out.println(" " + m.getName());
System.out.println(" Called By: ");
for(Method m: calledBy)
System.out.println(" " + m.getName());
System.out.println(" Fuzzy Calls: ");
for(Method m: fuzzyCalls)
System.out.println(" " + m.getName());
System.out.println(" Fuzzy Called By: ");
for(Method m: fuzzyCalledBy)
System.out.println(" " + m.getName());
System.out.println(" Unresolved Calls: (" + unresolvedCalls.size() + ")");
for(String m: unresolvedCalls)
System.out.println(" " + m);
}
| public void print() {
System.out.println(" METHOD: " + name);
System.out.println(" Return Type: " + returnType);
System.out.println(" Start Character: " + this.startChar);
System.out.println(" End Character: " + this.endChar);
System.out.println(" Calls: ");
for(Method m: methodCalls)
System.out.println(" " + m.getName());
System.out.println(" Called By: ");
for(Method m: calledBy)
System.out.println(" " + m.getName());
System.out.println(" Fuzzy Calls: ");
for(Method m: fuzzyCalls)
System.out.println(" " + m.getName());
System.out.println(" Fuzzy Called By: ");
for(Method m: fuzzyCalledBy)
System.out.println(" " + m.getName());
System.out.println(" Unresolved Calls: (" + unresolvedCalls.size() + ")");
for(String m: unresolvedCalls)
System.out.println(" " + m);
}
|
diff --git a/src/mulan/transformations/multiclass/MultiClassTransformationBase.java b/src/mulan/transformations/multiclass/MultiClassTransformationBase.java
index f9a52a1..e8d88ed 100644
--- a/src/mulan/transformations/multiclass/MultiClassTransformationBase.java
+++ b/src/mulan/transformations/multiclass/MultiClassTransformationBase.java
@@ -1,53 +1,53 @@
package mulan.transformations.multiclass;
import java.util.List;
import mulan.transformations.*;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
/**
* The base class for multi-class transformation methods. It provides initial implementation
* of {@link MultiClassTransformation} interface. All implementations of transformation
* methods should reuse this base class.
*
* @author Stavros
*/
public abstract class MultiClassTransformationBase implements MultiClassTransformation {
protected int numOfLabels;
protected int numPredictors;
MultiClassTransformationBase(int numOfLabels) {
this.numOfLabels = numOfLabels;
}
public Instances transformInstances(Instances data) throws Exception {
numPredictors = data.numAttributes()-numOfLabels;
Instances transformed = new Instances(data, 0);
// delete all labels
RemoveAllLabels ral = new RemoveAllLabels();
- transformed = ral.transformInstances(data, numOfLabels);
+ transformed = ral.transformInstances(transformed, numOfLabels);
// add single label attribute
FastVector classValues = new FastVector(numOfLabels);
for(int x=0; x<numOfLabels; x++)
classValues.addElement("Class"+(x+1));
Attribute newClass = new Attribute("Class", classValues);
transformed.insertAttributeAt(newClass, transformed.numAttributes());
transformed.setClassIndex(transformed.numAttributes()-1);
for (int instanceIndex=0; instanceIndex<data.numInstances(); instanceIndex++) {
List<Instance> result = transformInstance(data.instance(instanceIndex));
for (Instance instance : result)
transformed.add(instance);
}
return transformed;
}
}
| true | true | public Instances transformInstances(Instances data) throws Exception {
numPredictors = data.numAttributes()-numOfLabels;
Instances transformed = new Instances(data, 0);
// delete all labels
RemoveAllLabels ral = new RemoveAllLabels();
transformed = ral.transformInstances(data, numOfLabels);
// add single label attribute
FastVector classValues = new FastVector(numOfLabels);
for(int x=0; x<numOfLabels; x++)
classValues.addElement("Class"+(x+1));
Attribute newClass = new Attribute("Class", classValues);
transformed.insertAttributeAt(newClass, transformed.numAttributes());
transformed.setClassIndex(transformed.numAttributes()-1);
for (int instanceIndex=0; instanceIndex<data.numInstances(); instanceIndex++) {
List<Instance> result = transformInstance(data.instance(instanceIndex));
for (Instance instance : result)
transformed.add(instance);
}
return transformed;
}
| public Instances transformInstances(Instances data) throws Exception {
numPredictors = data.numAttributes()-numOfLabels;
Instances transformed = new Instances(data, 0);
// delete all labels
RemoveAllLabels ral = new RemoveAllLabels();
transformed = ral.transformInstances(transformed, numOfLabels);
// add single label attribute
FastVector classValues = new FastVector(numOfLabels);
for(int x=0; x<numOfLabels; x++)
classValues.addElement("Class"+(x+1));
Attribute newClass = new Attribute("Class", classValues);
transformed.insertAttributeAt(newClass, transformed.numAttributes());
transformed.setClassIndex(transformed.numAttributes()-1);
for (int instanceIndex=0; instanceIndex<data.numInstances(); instanceIndex++) {
List<Instance> result = transformInstance(data.instance(instanceIndex));
for (Instance instance : result)
transformed.add(instance);
}
return transformed;
}
|
diff --git a/src/main/java/water/Model.java b/src/main/java/water/Model.java
index eb16ab129..c52e186f4 100644
--- a/src/main/java/water/Model.java
+++ b/src/main/java/water/Model.java
@@ -1,433 +1,433 @@
package water;
import hex.ConfusionMatrix;
import hex.VariableImportance;
import java.util.*;
import javassist.*;
import water.api.DocGen;
import water.api.Request.API;
import water.fvec.*;
import water.util.*;
import water.util.Log.Tag.Sys;
/**
* A Model models reality (hopefully).
* A model can be used to 'score' a row, or a collection of rows on any
* compatible dataset - meaning the row has all the columns with the same names
* as used to build the mode.
*/
public abstract class Model extends Iced {
static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
/** Key associated with this Model, if any. */
@API(help="Key associated with Model")
public final Key _selfKey;
/** Dataset key used to *build* the model, for models for which this makes
* sense, or null otherwise. Not all models are built from a dataset (eg
* artificial models), or are built from a single dataset (various ensemble
* models), so this key has no *mathematical* significance in the model but
* is handy during common model-building and for the historical record. */
@API(help="Datakey used to *build* the model")
public final Key _dataKey;
/** Columns used in the model and are used to match up with scoring data
* columns. The last name is the response column name. */
@API(help="Column names used to build the model")
public final String _names[];
/** Categorical/factor/enum mappings, per column. Null for non-enum cols.
* The last column holds the response col enums. */
@API(help="Column names used to build the model")
public final String _domains[][];
/** Full constructor from frame: Strips out the Vecs to just the names needed
* to match columns later for future datasets. */
public Model( Key selfKey, Key dataKey, Frame fr ) {
this(selfKey,dataKey,fr.names(),fr.domains());
}
/** Full constructor */
public Model( Key selfKey, Key dataKey, String names[], String domains[][] ) {
if( domains == null ) domains=new String[names.length+1][];
assert domains.length==names.length;
assert names.length > 1;
assert names[names.length-1] != null; // Have a valid response-column name?
_selfKey = selfKey;
_dataKey = dataKey;
_names = names;
_domains = domains;
}
/** Simple shallow copy constructor to a new Key */
public Model( Key selfKey, Model m ) { this(selfKey,m._dataKey,m._names,m._domains); }
/** Called when deleting this model, to cleanup any internal keys */
public void delete() { UKV.remove(_selfKey); }
public String responseName() { return _names[ _names.length-1]; }
public String[] classNames() { return _domains[_domains.length-1]; }
public boolean isClassifier() { return classNames() != null ; }
public int nclasses() {
String cns[] = classNames();
return cns==null ? 1 : cns.length;
}
/** For classifiers, confusion matrix on validation set. */
public ConfusionMatrix cm() { return null; }
/** Variable importance of individual variables measured by this model. */
public VariableImportance varimp() { return null; }
/** Bulk score the frame 'fr', producing a Frame result; the 1st Vec is the
* predicted class, the remaining Vecs are the probability distributions.
* For Regression (single-class) models, the 1st and only Vec is the
* prediction value. Also passed in a flag describing how hard we try to
* adapt the frame. */
public Frame score( Frame fr) {
int ridx = fr.find(_names[_names.length-1]);
if(ridx != -1){ // drop the response for scoring!
- fr = new Frame(fr._names,fr.vecs());
+ fr = new Frame(fr._names,fr.vecs().clone());
fr.remove(ridx);
}
// Adapt the Frame layout - returns adapted frame and frame containing only
// newly created vectors
Frame[] adaptFrms = adapt(fr,false);
// Adapted frame containing all columns - mix of original vectors from fr
// and newly created vectors serving as adaptors
Frame adaptFrm = adaptFrms[0];
// Contains only newly created vectors. The frame eases deletion of these vectors.
Frame onlyAdaptFrm = adaptFrms[1];
Vec v = adaptFrm.anyVec().makeZero();
// If the model produces a classification/enum, copy the domain into the
// result vector.
v._domain = _domains[_domains.length-1];
adaptFrm.add("predict",v);
if( nclasses() > 1 )
for( int c=0; c<nclasses(); c++ )
adaptFrm.add(classNames()[c],adaptFrm.anyVec().makeZero());
new MRTask2() {
@Override public void map( Chunk chks[] ) {
double tmp[] = new double[_names.length];
float preds[] = new float[nclasses()];
Chunk p = chks[_names.length-1];
for( int i=0; i<p._len; i++ ) {
float[] out = score0(chks,i,tmp,preds);
if( nclasses() > 1 ) {
if( Float.isNaN(out[0]) ) p.setNA0(i);
else p.set0(i, Utils.maxIndex(out));
for( int c=0; c<nclasses(); c++ )
chks[_names.length+c].set0(i,out[c]);
} else {
p.set0(i,out[0]);
}
}
}
}.doAll(adaptFrm);
// Return just the output columns
int x=_names.length-1, y=adaptFrm.numCols();
Frame output = adaptFrm.extractFrame(x, y);
// Delete manually only vectors which i created :-/
onlyAdaptFrm.remove();
return output;
}
/** Single row scoring, on a compatible Frame. */
public final float[] score( Frame fr, boolean exact, int row ) {
double tmp[] = new double[fr.numCols()];
for( int i=0; i<tmp.length; i++ )
tmp[i] = fr.vecs()[i].at(row);
return score(fr.names(),fr.domains(),exact,tmp);
}
/** Single row scoring, on a compatible set of data. Fairly expensive to adapt. */
public final float[] score( String names[], String domains[][], boolean exact, double row[] ) {
return score(adapt(names,domains,exact),row,new float[nclasses()]);
}
/** Single row scoring, on a compatible set of data, given an adaption vector */
public final float[] score( int map[][], double row[], float[] preds ) {
int[] colMap = map[map.length-1]; // Column mapping is the final array
assert colMap.length == _names.length-1 : " "+Arrays.toString(colMap)+" "+Arrays.toString(_names);
double tmp[] = new double[colMap.length]; // The adapted data
for( int i=0; i<colMap.length; i++ ) {
// Column mapping, or NaN for missing columns
double d = colMap[i]==-1 ? Double.NaN : row[colMap[i]];
if( map[i] != null ) { // Enum mapping
int e = (int)d;
if( e < 0 || e >= map[i].length ) d = Double.NaN; // User data is out of adapt range
else {
e = map[i][e];
d = e==-1 ? Double.NaN : (double)e;
}
}
tmp[i] = d;
}
return score0(tmp,preds); // The results.
}
/** Build an adaption array. The length is equal to the Model's vector
* length minus the response plus a column mapping. Each inner array is a
* domain map from data domains to model domains - or null for non-enum
* columns, or null for identity mappings. The extra final int[] is the
* column mapping itself, mapping from model columns to data columns. or -1
* if missing.
* If 'exact' is true, will throw if there are:
* any columns in the model but not in the input set;
* any enums in the data that the model does not understand
* any enums returned by the model that the data does not have a mapping for.
* If 'exact' is false, these situations will use or return NA's instead.
*/
private int[][] adapt( String names[], String domains[][], boolean exact) {
int maplen = names.length;
int map[][] = new int[maplen][];
// Make sure all are compatible
for( int c=0; c<names.length;++c) {
// Now do domain mapping
String ms[] = _domains[c]; // Model enum
String ds[] = domains[c]; // Data enum
if( ms == ds ) { // Domains trivially equal?
} else if( ms == null && ds != null ) {
throw new IllegalArgumentException("Incompatible column: '" + _names[c] + "', expected (trained on) numeric, was passed a categorical");
} else if( ms != null && ds == null ) {
if( exact )
throw new IllegalArgumentException("Incompatible column: '" + _names[c] + "', expected (trained on) categorical, was passed a numeric");
throw H2O.unimpl(); // Attempt an asEnum?
} else if( !Arrays.deepEquals(ms, ds) ) {
map[c] = getDomainMapping(_names[c], ms, ds, exact);
} // null mapping is equal to identity mapping
}
return map;
}
/** Build an adapted Frame from the given Frame. Useful for efficient bulk
* scoring of a new dataset to an existing model. Same adaption as above,
* but expressed as a Frame instead of as an int[][]. The returned Frame
* does not have a response column.
* It returns a <b>two element array</b> containing an adapted frame and a
* frame which contains only vectors which where adapted (the purpose of the
* second frame is to delete all adapted vectors with deletion of the
* frame). */
public Frame[] adapt( Frame fr, boolean exact) {
int ridx = fr.find(_names[_names.length-1]);
if(ridx != -1 && ridx != fr._names.length-1){ // put response to the end
String n =fr._names[ridx];
fr.add(n,fr.remove(ridx));
}
int n = ridx == -1?_names.length-1:_names.length;
String [] names = Arrays.copyOf(_names, n);
fr = fr.subframe(names);
Vec [] frvecs = fr.vecs();
if(!exact) for(int i = 0; i < n;++i)
if(_domains[i] != null && !frvecs[i].isEnum())
frvecs[i] = frvecs[i].toEnum();
int map[][] = adapt(names,fr.domains(),exact);
ArrayList<Vec> avecs = new ArrayList<Vec>();
ArrayList<String> anames = new ArrayList<String>();
for( int c=0; c<map.length; c++ ) // iterate over columns
if(map[c] != null){
avecs.add(frvecs[c] = frvecs[c].makeTransf(map[c]));
anames.add(names[c]);
}
return new Frame[] { new Frame(names,frvecs), new Frame(anames.toArray(new String[anames.size()]), avecs.toArray(new Vec[avecs.size()])) };
}
/** Returns a mapping between values domains for a given column. */
public static int[] getDomainMapping(String colName, String[] modelDom, String[] dom, boolean exact) {
int emap[] = new int[dom.length];
HashMap<String,Integer> md = new HashMap<String, Integer>();
for( int i = 0; i < modelDom.length; i++) md.put(modelDom[i], i);
for( int i = 0; i < dom.length; i++) {
Integer I = md.get(dom[i]);
if( I==null && exact )
Log.warn(Sys.SCORM, "Column "+colName+" was not trained with factor '"+dom[i]+"' which appears in the data");
emap[i] = I==null ? -1 : I;
}
for( int i = 0; i < dom.length; i++)
assert emap[i]==-1 || modelDom[emap[i]].equals(dom[i]);
return emap;
}
/** Bulk scoring API for one row. Chunks are all compatible with the model,
* and expect the last Chunks are for the final distribution & prediction.
* Default method is to just load the data into the tmp array, then call
* subclass scoring logic. */
protected float[] score0( Chunk chks[], int row_in_chunk, double[] tmp, float[] preds ) {
assert chks.length>=_names.length; // Last chunk is for the response
for( int i=0; i<_names.length; i++ )
tmp[i] = chks[i].at0(row_in_chunk);
return score0(tmp,preds);
}
/** Subclasses implement the scoring logic. The data is pre-loaded into a
* re-used temp array, in the order the model expects. The predictions are
* loaded into the re-used temp array, which is also returned. */
protected abstract float[] score0(double data[/*ncols*/], float preds[/*nclasses*/]);
// Version where the user has just ponied-up an array of data to be scored.
// Data must be in proper order. Handy for JUnit tests.
public double score(double [] data){ return Utils.maxIndex(score0(data,new float[nclasses()])); }
/** Return a String which is a valid Java program representing a class that
* implements the Model. The Java is of the form:
* <pre>
* class UUIDxxxxModel {
* public static final String NAMES[] = { ....column names... }
* public static final String DOMAINS[][] = { ....domain names... }
* // Pass in data in a double[], pre-aligned to the Model's requirements.
* // Jam predictions into the preds[] array; preds[0] is reserved for the
* // main prediction (class for classifiers or value for regression),
* // and remaining columns hold a probability distribution for classifiers.
* float[] predict( double data[], float preds[] );
* double[] map( HashMap<String,Double> row, double data[] );
* // Does the mapping lookup for every row, no allocation
* float[] predict( HashMap<String,Double> row, double data[], float preds[] );
* // Allocates a double[] for every row
* float[] predict( HashMap<String,Double> row, float preds[] );
* // Allocates a double[] and a float[] for every row
* float[] predict( HashMap<String,Double> row );
* }
* </pre>
*/
public String toJava() { return toJava(new SB()).toString(); }
public SB toJava( SB sb ) {
sb.p("\n");
String modelName = JCodeGen.toJavaId(_selfKey.toString());
sb.p("// Model for ").p(this.getClass().getSimpleName()).p(" with name ").p(modelName);
sb.p("\nclass ").p(modelName).p(" extends water.Model.GeneratedModel {\n");
toJavaNAMES(sb);
toJavaNCLASSES(sb);
toJavaInit(sb); sb.nl();
toJavaPredict(sb);
sb.p(TOJAVA_MAP);
sb.p(TOJAVA_PREDICT_MAP);
sb.p(TOJAVA_PREDICT_MAP_ALLOC1);
sb.p(TOJAVA_PREDICT_MAP_ALLOC2);
sb.p("}").nl();
return sb;
}
// Same thing as toJava, but as a Javassist CtClass
private CtClass makeCtClass() throws CannotCompileException {
CtClass clz = ClassPool.getDefault().makeClass(JCodeGen.toJavaId(_selfKey.toString()));
clz.addField(CtField.make(toJavaNAMES (new SB()).toString(),clz));
clz.addField(CtField.make(toJavaNCLASSES(new SB()).toString(),clz));
toJavaInit(clz); // Model-specific top-level goodness
clz.addMethod(CtMethod.make(toJavaPredict(new SB()).toString(),clz));
clz.addMethod(CtMethod.make(TOJAVA_MAP,clz));
clz.addMethod(CtMethod.make(TOJAVA_PREDICT_MAP,clz));
clz.addMethod(CtMethod.make(TOJAVA_PREDICT_MAP_ALLOC1,clz));
clz.addMethod(CtMethod.make(TOJAVA_PREDICT_MAP_ALLOC2,clz));
return clz;
}
private SB toJavaNAMES( SB sb ) {
return sb.p(" public static final String[] NAMES = new String[] ").toJavaStringInit(_names).p(";\n");
}
private SB toJavaNCLASSES( SB sb ) {
return sb.p(" public static final int NCLASSES = ").p(nclasses()).p(";\n");
}
// Override in subclasses to provide some top-level model-specific goodness
protected void toJavaInit(SB sb) { };
protected void toJavaInit(CtClass ct) { };
// Override in subclasses to provide some inside 'predict' call goodness
// Method returns code which should be appended into generated top level class after
// predit method.
protected void toJavaPredictBody(SB sb, SB afterSb) {
throw new IllegalArgumentException("This model type does not support conversion to Java");
}
// Wrapper around the main predict call, including the signature and return value
private SB toJavaPredict(SB sb) {
sb.p(" // Pass in data in a double[], pre-aligned to the Model's requirements.\n");
sb.p(" // Jam predictions into the preds[] array; preds[0] is reserved for the\n");
sb.p(" // main prediction (class for classifiers or value for regression),\n");
sb.p(" // and remaining columns hold a probability distribution for classifiers.\n");
sb.p(" @Override public final float[] predict( double[] data, float[] preds ) {\n");
SB afterCode = new SB().ii(1);
toJavaPredictBody(sb.ii(2), afterCode); sb.di(1);
sb.p(" return preds;\n");
sb.p(" }\n");
sb.p(afterCode);
return sb;
}
private static final String TOJAVA_MAP =
" // Takes a HashMap mapping column names to doubles. Looks up the column\n"+
" // names needed by the model, and places the doubles into the data array in\n"+
" // the order needed by the model. Missing columns use NaN.\n"+
" double[] map( java.util.HashMap row, double data[] ) {\n"+
" for( int i=0; i<NAMES.length-1; i++ ) {\n"+
" Double d = (Double)row.get(NAMES[i]);\n"+
" data[i] = d==null ? Double.NaN : d;\n"+
" }\n"+
" return data;\n"+
" }\n";
private static final String TOJAVA_PREDICT_MAP =
" // Does the mapping lookup for every row, no allocation\n"+
" float[] predict( java.util.HashMap row, double data[], float preds[] ) {\n"+
" return predict(map(row,data),preds);\n"+
" }\n";
private static final String TOJAVA_PREDICT_MAP_ALLOC1 =
" // Allocates a double[] for every row\n"+
" float[] predict( java.util.HashMap row, float preds[] ) {\n"+
" return predict(map(row,new double[NAMES.length]),preds);\n"+
" }\n";
private static final String TOJAVA_PREDICT_MAP_ALLOC2 =
" // Allocates a double[] and a float[] for every row\n"+
" float[] predict( java.util.HashMap row ) {\n"+
" return predict(map(row,new double[NAMES.length]),new float[NCLASSES+1]);\n"+
" }\n";
// Convenience method for testing: build Java, convert it to a class &
// execute it: compare the results of the new class's (JIT'd) scoring with
// the built-in (interpreted) scoring on this dataset. Throws if there
// is any error (typically an AssertionError).
public void testJavaScoring( Frame fr ) {
try {
//System.out.println(toJava());
Class clz = ClassPool.getDefault().toClass(makeCtClass());
Object modelo = clz.newInstance();
}
catch( CannotCompileException cce ) { throw new Error(cce); }
catch( InstantiationException cce ) { throw new Error(cce); }
catch( IllegalAccessException cce ) { throw new Error(cce); }
}
public abstract static class GeneratedModel {
// Predict a row
abstract public float[] predict( double data[], float preds[] );
// Run benchmark
public final void bench(long iters, double[][] data, float[] preds, int ntrees) {
int rows = data.length;
int cols = data[0].length;
int levels = preds.length-1;
int ntrees_internal = ntrees*levels;
System.out.println("# Iterations: " + iters);
System.out.println("# Rows : " + rows);
System.out.println("# Cols : " + cols);
System.out.println("# Levels : " + levels);
System.out.println("# Ntrees : " + ntrees);
System.out.println("# Ntrees internal : " + ntrees_internal);
System.out.println("iter,total_time,time_per_row,time_per_tree,time_per_row_tree,time_per_inter_tree,time_per_row_inter_tree");
StringBuilder sb = new StringBuilder(100);
for (int i=0; i<iters; i++) {
long startTime = System.nanoTime();
// Run dummy score
for (double[] row : data) predict(row, preds);
long ttime = System.nanoTime() - startTime;
sb.append(i).append(',');
sb.append(ttime).append(',');
sb.append(ttime/rows).append(',');
sb.append(ttime/ntrees).append(',');
sb.append(ttime/(ntrees*rows)).append(',');
sb.append(ttime/ntrees_internal).append(',');
sb.append(ttime/(ntrees_internal*rows)).append('\n');
System.out.print(sb.toString());
sb.setLength(0);
}
}
}
}
| true | true | public Frame score( Frame fr) {
int ridx = fr.find(_names[_names.length-1]);
if(ridx != -1){ // drop the response for scoring!
fr = new Frame(fr._names,fr.vecs());
fr.remove(ridx);
}
// Adapt the Frame layout - returns adapted frame and frame containing only
// newly created vectors
Frame[] adaptFrms = adapt(fr,false);
// Adapted frame containing all columns - mix of original vectors from fr
// and newly created vectors serving as adaptors
Frame adaptFrm = adaptFrms[0];
// Contains only newly created vectors. The frame eases deletion of these vectors.
Frame onlyAdaptFrm = adaptFrms[1];
Vec v = adaptFrm.anyVec().makeZero();
// If the model produces a classification/enum, copy the domain into the
// result vector.
v._domain = _domains[_domains.length-1];
adaptFrm.add("predict",v);
if( nclasses() > 1 )
for( int c=0; c<nclasses(); c++ )
adaptFrm.add(classNames()[c],adaptFrm.anyVec().makeZero());
new MRTask2() {
@Override public void map( Chunk chks[] ) {
double tmp[] = new double[_names.length];
float preds[] = new float[nclasses()];
Chunk p = chks[_names.length-1];
for( int i=0; i<p._len; i++ ) {
float[] out = score0(chks,i,tmp,preds);
if( nclasses() > 1 ) {
if( Float.isNaN(out[0]) ) p.setNA0(i);
else p.set0(i, Utils.maxIndex(out));
for( int c=0; c<nclasses(); c++ )
chks[_names.length+c].set0(i,out[c]);
} else {
p.set0(i,out[0]);
}
}
}
}.doAll(adaptFrm);
// Return just the output columns
int x=_names.length-1, y=adaptFrm.numCols();
Frame output = adaptFrm.extractFrame(x, y);
// Delete manually only vectors which i created :-/
onlyAdaptFrm.remove();
return output;
}
| public Frame score( Frame fr) {
int ridx = fr.find(_names[_names.length-1]);
if(ridx != -1){ // drop the response for scoring!
fr = new Frame(fr._names,fr.vecs().clone());
fr.remove(ridx);
}
// Adapt the Frame layout - returns adapted frame and frame containing only
// newly created vectors
Frame[] adaptFrms = adapt(fr,false);
// Adapted frame containing all columns - mix of original vectors from fr
// and newly created vectors serving as adaptors
Frame adaptFrm = adaptFrms[0];
// Contains only newly created vectors. The frame eases deletion of these vectors.
Frame onlyAdaptFrm = adaptFrms[1];
Vec v = adaptFrm.anyVec().makeZero();
// If the model produces a classification/enum, copy the domain into the
// result vector.
v._domain = _domains[_domains.length-1];
adaptFrm.add("predict",v);
if( nclasses() > 1 )
for( int c=0; c<nclasses(); c++ )
adaptFrm.add(classNames()[c],adaptFrm.anyVec().makeZero());
new MRTask2() {
@Override public void map( Chunk chks[] ) {
double tmp[] = new double[_names.length];
float preds[] = new float[nclasses()];
Chunk p = chks[_names.length-1];
for( int i=0; i<p._len; i++ ) {
float[] out = score0(chks,i,tmp,preds);
if( nclasses() > 1 ) {
if( Float.isNaN(out[0]) ) p.setNA0(i);
else p.set0(i, Utils.maxIndex(out));
for( int c=0; c<nclasses(); c++ )
chks[_names.length+c].set0(i,out[c]);
} else {
p.set0(i,out[0]);
}
}
}
}.doAll(adaptFrm);
// Return just the output columns
int x=_names.length-1, y=adaptFrm.numCols();
Frame output = adaptFrm.extractFrame(x, y);
// Delete manually only vectors which i created :-/
onlyAdaptFrm.remove();
return output;
}
|
diff --git a/src/java/org/rapidcontext/core/type/Role.java b/src/java/org/rapidcontext/core/type/Role.java
index d48b5ad..8e84c4b 100644
--- a/src/java/org/rapidcontext/core/type/Role.java
+++ b/src/java/org/rapidcontext/core/type/Role.java
@@ -1,278 +1,279 @@
/*
* RapidContext <http://www.rapidcontext.com/>
* Copyright (c) 2007-2013 Per Cederberg. All rights reserved.
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the BSD license.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the RapidContext LICENSE.txt file for more details.
*/
package org.rapidcontext.core.type;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.rapidcontext.core.data.Array;
import org.rapidcontext.core.data.Dict;
import org.rapidcontext.core.storage.Path;
import org.rapidcontext.core.storage.StorableObject;
import org.rapidcontext.core.storage.Storage;
/**
* A user access role. Each role may contain an access rule list for
* declaring which objects that the role provides access to.
*
* @author Per Cederberg
* @version 1.0
*/
public class Role extends StorableObject {
/**
* The class logger.
*/
private static final Logger LOG = Logger.getLogger(Role.class.getName());
/**
* The dictionary key for the role name.
*/
public static final String KEY_NAME = "name";
/**
* The dictionary key for the role description.
*/
public static final String KEY_DESCRIPTION = "description";
/**
* The dictionary key for automatic user match.
*/
public static final String KEY_AUTO = "auto";
/**
* The dictionary key for the role access array. The value stored
* is an array of access rules.
*/
public static final String KEY_ACCESS = "access";
/**
* The dictionary key for the path in the access dictionary. The
* value stored is an absolute path to an object, with optional
* glob characters ('*', '**' or '?').
*/
public static final String ACCESS_PATH = "path";
/**
* The dictionary key for the regex path in the access
* dictionary. The value stored is a regular expression matching
* an absolute path to an object (without leading '/' chars).
*/
public static final String ACCESS_REGEX = "regex";
/**
* The dictionary key for the permission list in the access
* dictionary. The value stored is a string with permissions
* separated by comma (',').
*
* @see #PERM_NONE
* @see #PERM_INTERNAL
* @see #PERM_READ
* @see #PERM_WRITE
* @see #PERM_ALL
*/
public static final String ACCESS_PERMISSION = "permission";
/**
* The permission key for no access.
*/
public static final String PERM_NONE = "none";
/**
* The permission key for internal access.
*/
public static final String PERM_INTERNAL = "internal";
/**
* The permission key for read access.
*/
public static final String PERM_READ = "read";
/**
* The permission key for write access.
*/
public static final String PERM_WRITE = "write";
/**
* The permission key for full access.
*/
public static final String PERM_ALL = "all";
/**
* The role object storage path.
*/
public static final Path PATH = new Path("/role/");
/**
* Searches for all roles in the storage.
*
* @param storage the storage to search in
*
* @return an array of all roles found
*/
public static Role[] findAll(Storage storage) {
Object[] objs = storage.loadAll(PATH);
ArrayList list = new ArrayList(objs.length);
for (int i = 0; i < objs.length; i++) {
if (objs[i] instanceof Role) {
list.add(objs[i]);
}
}
return (Role[]) list.toArray(new Role[list.size()]);
}
/**
* Creates a new role from a serialized representation.
*
* @param id the object identifier
* @param type the object type name
* @param dict the serialized representation
*/
public Role(String id, String type, Dict dict) {
super(id, type, dict);
dict.set(KEY_NAME, name());
dict.set(KEY_DESCRIPTION, description());
}
/**
* Returns the role name.
*
* @return the role name.
*/
public String name() {
return dict.getString(KEY_NAME, "");
}
/**
* Returns the role description.
*
* @return the role description.
*/
public String description() {
return dict.getString(KEY_DESCRIPTION, "");
}
/**
* Returns the automatic role attachment type. The values "all"
* and "auth" are the only ones with defined meaning.
*
* @return the automatic role attachment type
*/
public String auto() {
return dict.getString(KEY_AUTO, "none");
}
/**
* Checks if the specified user has this role. The user may be
* null, in which case only automatic roles for "all" will be
* considered a match.
*
* @param user the user to check, or null
*
* @return true if the user has this role, or
* false otherwise
*/
public boolean hasUser(User user) {
boolean matchAll = auto().equalsIgnoreCase("all");
boolean matchAuth = auto().equalsIgnoreCase("auth");
if (user == null) {
return matchAll;
} else {
return matchAll || matchAuth || user.hasRole(id());
}
}
/**
* Checks if the role has access permission for a storage path.
* The access list is processed from top to bottom to find a
* matching path entry. If a matching path with the PERM_NONE
* permission is encountered, false will be returned. Otherwise
* true will be returned only if the permission matches the
* requested one.
*
* @param path the object storage path
* @param permission the requested permission
*
* @return true if the role provides access, or
* false otherwise
*/
public boolean hasAccess(String path, String permission) {
Array arr = dict.getArray(KEY_ACCESS);
for (int i = 0; arr != null && i < arr.size(); i++) {
Dict dict = arr.getDict(i);
if (matchPath(dict, path)) {
String perms = dict.getString(ACCESS_PERMISSION, "").trim();
// BUG: string matching is not reliable for custom permissions!
if (perms.contains(permission)) {
return true;
} else if (PERM_NONE.equalsIgnoreCase(perms)) {
return false;
} else if (PERM_ALL.equalsIgnoreCase(perms)) {
return true;
}
}
}
return false;
}
/**
* Checks if the access data matches the specified values.
*
* @param dict the access data
* @param path the object storage path
*
* @return true if the access path matches, or
* false otherwise
*/
private boolean matchPath(Dict dict, String path) {
String glob = dict.getString(ACCESS_PATH, null);
String regex = dict.getString(ACCESS_REGEX, null);
Pattern m = (Pattern) dict.get("_" + ACCESS_REGEX);
if (m == null && glob != null) {
- glob = glob.replace(".", "\\.").replace("\\", "\\\\");
+ glob = glob.replace("\\", "\\\\").replace(".", "\\.");
glob = glob.replace("+", "\\+").replace("|", "\\|");
glob = glob.replace("^", "\\^").replace("$", "\\$");
glob = glob.replace("(", "\\(").replace(")", "\\)");
glob = glob.replace("[", "\\[").replace("]", "\\]");
glob = glob.replace("{", "\\{").replace("}", "\\}");
glob = glob.replace("**", ".+");
- glob = glob.replace("*", "[^/]+");
+ glob = glob.replace("*", "[^/]*");
+ glob = glob.replace(".+", ".*");
glob = glob.replace("?", ".");
try {
m = Pattern.compile("^" + glob + "$");
} catch (Exception e) {
LOG.log(Level.WARNING, "invalid pattern in role " + id(), e);
m = Pattern.compile("^invalid-glob-pattern$");
}
dict.set("_" + ACCESS_REGEX, m);
} else if (m == null && regex != null) {
regex = StringUtils.removeStart(regex, "^");
regex = StringUtils.removeStart(regex, "/");
regex = StringUtils.removeEnd(regex, "$");
try {
m = Pattern.compile("^" + regex + "$");
} catch (Exception e) {
LOG.log(Level.WARNING, "invalid pattern in role " + id(), e);
m = Pattern.compile("^invalid-regex-pattern$");
}
dict.set("_" + ACCESS_REGEX, m);
}
return m.matcher(path).matches();
}
}
| false | true | private boolean matchPath(Dict dict, String path) {
String glob = dict.getString(ACCESS_PATH, null);
String regex = dict.getString(ACCESS_REGEX, null);
Pattern m = (Pattern) dict.get("_" + ACCESS_REGEX);
if (m == null && glob != null) {
glob = glob.replace(".", "\\.").replace("\\", "\\\\");
glob = glob.replace("+", "\\+").replace("|", "\\|");
glob = glob.replace("^", "\\^").replace("$", "\\$");
glob = glob.replace("(", "\\(").replace(")", "\\)");
glob = glob.replace("[", "\\[").replace("]", "\\]");
glob = glob.replace("{", "\\{").replace("}", "\\}");
glob = glob.replace("**", ".+");
glob = glob.replace("*", "[^/]+");
glob = glob.replace("?", ".");
try {
m = Pattern.compile("^" + glob + "$");
} catch (Exception e) {
LOG.log(Level.WARNING, "invalid pattern in role " + id(), e);
m = Pattern.compile("^invalid-glob-pattern$");
}
dict.set("_" + ACCESS_REGEX, m);
} else if (m == null && regex != null) {
regex = StringUtils.removeStart(regex, "^");
regex = StringUtils.removeStart(regex, "/");
regex = StringUtils.removeEnd(regex, "$");
try {
m = Pattern.compile("^" + regex + "$");
} catch (Exception e) {
LOG.log(Level.WARNING, "invalid pattern in role " + id(), e);
m = Pattern.compile("^invalid-regex-pattern$");
}
dict.set("_" + ACCESS_REGEX, m);
}
return m.matcher(path).matches();
}
| private boolean matchPath(Dict dict, String path) {
String glob = dict.getString(ACCESS_PATH, null);
String regex = dict.getString(ACCESS_REGEX, null);
Pattern m = (Pattern) dict.get("_" + ACCESS_REGEX);
if (m == null && glob != null) {
glob = glob.replace("\\", "\\\\").replace(".", "\\.");
glob = glob.replace("+", "\\+").replace("|", "\\|");
glob = glob.replace("^", "\\^").replace("$", "\\$");
glob = glob.replace("(", "\\(").replace(")", "\\)");
glob = glob.replace("[", "\\[").replace("]", "\\]");
glob = glob.replace("{", "\\{").replace("}", "\\}");
glob = glob.replace("**", ".+");
glob = glob.replace("*", "[^/]*");
glob = glob.replace(".+", ".*");
glob = glob.replace("?", ".");
try {
m = Pattern.compile("^" + glob + "$");
} catch (Exception e) {
LOG.log(Level.WARNING, "invalid pattern in role " + id(), e);
m = Pattern.compile("^invalid-glob-pattern$");
}
dict.set("_" + ACCESS_REGEX, m);
} else if (m == null && regex != null) {
regex = StringUtils.removeStart(regex, "^");
regex = StringUtils.removeStart(regex, "/");
regex = StringUtils.removeEnd(regex, "$");
try {
m = Pattern.compile("^" + regex + "$");
} catch (Exception e) {
LOG.log(Level.WARNING, "invalid pattern in role " + id(), e);
m = Pattern.compile("^invalid-regex-pattern$");
}
dict.set("_" + ACCESS_REGEX, m);
}
return m.matcher(path).matches();
}
|
diff --git a/src/org/opensolaris/opengrok/configuration/Configuration.java b/src/org/opensolaris/opengrok/configuration/Configuration.java
index bda5ea3..68a7224 100644
--- a/src/org/opensolaris/opengrok/configuration/Configuration.java
+++ b/src/org/opensolaris/opengrok/configuration/Configuration.java
@@ -1,662 +1,662 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
*/
package org.opensolaris.opengrok.configuration;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.logging.Logger;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.opensolaris.opengrok.history.RepositoryInfo;
import org.opensolaris.opengrok.index.Filter;
import org.opensolaris.opengrok.index.IgnoredNames;
import org.opensolaris.opengrok.util.IOUtils;
/**
* Placeholder class for all configuration variables. Due to the multithreaded
* nature of the web application, each thread will use the same instance of the
* configuration object for each page request. Class and methods should have
* package scope, but that didn't work with the XMLDecoder/XMLEncoder.
*/
public final class Configuration {
private String ctags;
/** Should the history log be cached? */
private boolean historyCache;
/**
* The maximum time in milliseconds {@code HistoryCache.get()} can take
* before its result is cached.
*/
private int historyCacheTime;
/** Should the history cache be stored in a database? */
private boolean historyCacheInDB;
private List<Project> projects;
private String sourceRoot;
private String dataRoot;
private List<RepositoryInfo> repositories;
private String urlPrefix;
private boolean generateHtml;
/** Default project will be used, when no project is selected and no project is in cookie, so basically only the first time you open the first page, or when you clear your web cookies */
private Project defaultProject;
private int indexWordLimit;
private boolean verbose;
//if below is set, then we count how many files per project we need to process and print percentage of completion per project
private boolean printProgress;
private boolean allowLeadingWildcard;
private IgnoredNames ignoredNames;
private Filter includedNames;
private String userPage;
private String userPageSuffix;
private String bugPage;
private String bugPattern;
private String reviewPage;
private String reviewPattern;
private String webappLAF;
private boolean remoteScmSupported;
private boolean optimizeDatabase;
private boolean useLuceneLocking;
private boolean compressXref;
private boolean indexVersionedFilesOnly;
private int hitsPerPage;
private int cachePages;
private String databaseDriver;
private String databaseUrl;
private int scanningDepth;
private Set<String> allowedSymlinks;
private boolean obfuscatingEMailAddresses;
private boolean chattyStatusPage;
private final Map<String,String> cmds;
private int tabSize;
private static final Logger logger = Logger.getLogger("org.opensolaris.opengrok");
/**
* Get the default tab size (number of space characters per tab character)
* to use for each project. If {@code <= 0} tabs are read/write as is.
* @return current tab size set.
* @see Project#getTabSize()
* @see org.opensolaris.opengrok.analysis.ExpandTabsReader
*/
public int getTabSize() {
return tabSize;
}
/**
* Set the default tab size (number of space characters per tab character)
* to use for each project. If {@code <= 0} tabs are read/write as is.
* @param tabSize tabsize to set.
* @see Project#setTabSize(int)
* @see org.opensolaris.opengrok.analysis.ExpandTabsReader
*/
public void setTabSize(int tabSize) {
this.tabSize = tabSize;
}
public int getScanningDepth() {
return scanningDepth;
}
public void setScanningDepth(int scanningDepth) {
this.scanningDepth = scanningDepth;
}
/** Creates a new instance of Configuration */
public Configuration() {
//defaults for an opengrok instance configuration
setHistoryCache(true);
setHistoryCacheTime(30);
setHistoryCacheInDB(false);
setProjects(new ArrayList<Project>());
setRepositories(new ArrayList<RepositoryInfo>());
setUrlPrefix("/source/s?");
//setUrlPrefix("../s?"); // TODO generate relative search paths, get rid of -w <webapp> option to indexer !
setCtags(System.getProperty("org.opensolaris.opengrok.analysis.Ctags", "ctags"));
//below can cause an outofmemory error, since it is defaulting to NO LIMIT
setIndexWordLimit(Integer.MAX_VALUE);
setVerbose(false);
setPrintProgress(false);
setGenerateHtml(true);
setQuickContextScan(true);
setIgnoredNames(new IgnoredNames());
setIncludedNames(new Filter());
setUserPage("http://www.opensolaris.org/viewProfile.jspa?username=");
setBugPage("http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=");
setBugPattern("\\b([12456789][0-9]{6})\\b");
setReviewPage("http://arc.opensolaris.org/caselog/PSARC/");
setReviewPattern("\\b(\\d{4}/\\d{3})\\b"); // in form e.g. PSARC 2008/305
setWebappLAF("default");
setRemoteScmSupported(false);
setOptimizeDatabase(true);
setUsingLuceneLocking(false);
setCompressXref(true);
setIndexVersionedFilesOnly(false);
setHitsPerPage(25);
setCachePages(5);
setScanningDepth(3); // default depth of scanning for repositories
setAllowedSymlinks(new HashSet<String>());
- setTabSize(4);
+ //setTabSize(4);
cmds = new HashMap<String, String>();
}
public String getRepoCmd(String clazzName) {
return cmds.get(clazzName);
}
public String setRepoCmd(String clazzName, String cmd) {
if (clazzName == null) {
return null;
}
if (cmd == null || cmd.length() == 0) {
return cmds.remove(clazzName);
}
return cmds.put(clazzName, cmd);
}
// just to satisfy bean/de|encoder stuff
public Map<String, String> getCmds() {
return Collections.unmodifiableMap(cmds);
}
public void setCmds(Map<String, String> cmds) {
this.cmds.clear();
this.cmds.putAll(cmds);
}
public String getCtags() {
return ctags;
}
public void setCtags(String ctags) {
this.ctags = ctags;
}
public int getCachePages() {
return cachePages;
}
public void setCachePages(int cachePages) {
this.cachePages = cachePages;
}
public int getHitsPerPage() {
return hitsPerPage;
}
public void setHitsPerPage(int hitsPerPage) {
this.hitsPerPage = hitsPerPage;
}
/**
* Should the history log be cached?
* @return {@code true} if a {@code HistoryCache} implementation should
* be used, {@code false} otherwise
*/
public boolean isHistoryCache() {
return historyCache;
}
/**
* Set whether history should be cached.
* @param historyCache if {@code true} enable history cache
*/
public void setHistoryCache(boolean historyCache) {
this.historyCache = historyCache;
}
/**
* How long can a history request take before it's cached? If the time
* is exceeded, the result is cached. This setting only affects
* {@code FileHistoryCache}.
*
* @return the maximum time in milliseconds a history request can take
* before it's cached
*/
public int getHistoryCacheTime() {
return historyCacheTime;
}
/**
* Set the maximum time a history request can take before it's cached.
* This setting is only respected if {@code FileHistoryCache} is used.
*
* @param historyCacheTime maximum time in milliseconds
*/
public void setHistoryCacheTime(int historyCacheTime) {
this.historyCacheTime = historyCacheTime;
}
/**
* Should the history cache be stored in a database? If yes,
* {@code JDBCHistoryCache} will be used to cache the history; otherwise,
* {@code FileHistoryCache} is used.
*
* @return whether the history cache should be stored in a database
*/
public boolean isHistoryCacheInDB() {
return historyCacheInDB;
}
/**
* Set whether the history cache should be stored in a database, and
* {@code JDBCHistoryCache} should be used instead of {@code
* FileHistoryCache}.
*
* @param historyCacheInDB whether the history cached should be stored in
* a database
*/
public void setHistoryCacheInDB(boolean historyCacheInDB) {
this.historyCacheInDB = historyCacheInDB;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public String getSourceRoot() {
return sourceRoot;
}
public void setSourceRoot(String sourceRoot) {
this.sourceRoot = sourceRoot;
}
public String getDataRoot() {
return dataRoot;
}
public void setDataRoot(String dataRoot) {
this.dataRoot = dataRoot;
}
public List<RepositoryInfo> getRepositories() {
return repositories;
}
public void setRepositories(List<RepositoryInfo> repositories) {
this.repositories = repositories;
}
public String getUrlPrefix() {
return urlPrefix;
}
/**
* Set the URL prefix to be used by the {@link
* org.opensolaris.opengrok.analysis.executables.JavaClassAnalyzer} as well
* as lexers (see {@link org.opensolaris.opengrok.analysis.JFlexXref})
* when they create output with html links.
* @param urlPrefix prefix to use.
*/
public void setUrlPrefix(String urlPrefix) {
this.urlPrefix = urlPrefix;
}
public void setGenerateHtml(boolean generateHtml) {
this.generateHtml = generateHtml;
}
public boolean isGenerateHtml() {
return generateHtml;
}
public void setDefaultProject(Project defaultProject) {
this.defaultProject = defaultProject;
}
public Project getDefaultProject() {
return defaultProject;
}
public int getIndexWordLimit() {
return indexWordLimit;
}
public void setIndexWordLimit(int indexWordLimit) {
this.indexWordLimit = indexWordLimit;
}
public boolean isVerbose() {
return verbose;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public boolean isPrintProgress() {
return printProgress;
}
public void setPrintProgress(boolean printProgress) {
this.printProgress = printProgress;
}
public void setAllowLeadingWildcard(boolean allowLeadingWildcard) {
this.allowLeadingWildcard = allowLeadingWildcard;
}
public boolean isAllowLeadingWildcard() {
return allowLeadingWildcard;
}
private boolean quickContextScan;
public boolean isQuickContextScan() {
return quickContextScan;
}
public void setQuickContextScan(boolean quickContextScan) {
this.quickContextScan = quickContextScan;
}
public void setIgnoredNames(IgnoredNames ignoredNames) {
this.ignoredNames = ignoredNames;
}
public IgnoredNames getIgnoredNames() {
return ignoredNames;
}
public void setIncludedNames(Filter includedNames) {
this.includedNames = includedNames;
}
public Filter getIncludedNames() {
return includedNames;
}
public void setUserPage(String userPage) {
this.userPage = userPage;
}
public String getUserPage() {
return userPage;
}
public void setUserPageSuffix(String userPageSuffix) {
this.userPageSuffix = userPageSuffix;
}
public String getUserPageSuffix() {
return userPageSuffix;
}
public void setBugPage(String bugPage) {
this.bugPage = bugPage;
}
public String getBugPage() {
return bugPage;
}
public void setBugPattern(String bugPattern) {
this.bugPattern = bugPattern;
}
public String getBugPattern() {
return bugPattern;
}
public String getReviewPage() {
return reviewPage;
}
public void setReviewPage(String reviewPage) {
this.reviewPage = reviewPage;
}
public String getReviewPattern() {
return reviewPattern;
}
public void setReviewPattern(String reviewPattern) {
this.reviewPattern = reviewPattern;
}
public String getWebappLAF() {
return webappLAF;
}
public void setWebappLAF(String webappLAF) {
this.webappLAF = webappLAF;
}
public boolean isRemoteScmSupported() {
return remoteScmSupported;
}
public void setRemoteScmSupported(boolean remoteScmSupported) {
this.remoteScmSupported = remoteScmSupported;
}
public boolean isOptimizeDatabase() {
return optimizeDatabase;
}
public void setOptimizeDatabase(boolean optimizeDatabase) {
this.optimizeDatabase = optimizeDatabase;
}
public boolean isUsingLuceneLocking() {
return useLuceneLocking;
}
public void setUsingLuceneLocking(boolean useLuceneLocking) {
this.useLuceneLocking = useLuceneLocking;
}
public void setCompressXref(boolean compressXref) {
this.compressXref = compressXref;
}
public boolean isCompressXref() {
return compressXref;
}
public boolean isIndexVersionedFilesOnly() {
return indexVersionedFilesOnly;
}
public void setIndexVersionedFilesOnly(boolean indexVersionedFilesOnly) {
this.indexVersionedFilesOnly = indexVersionedFilesOnly;
}
public Date getDateForLastIndexRun() {
File timestamp = new File(getDataRoot(), "timestamp");
return new Date(timestamp.lastModified());
}
/**
* Return contents of a file or empty string if the file cannot be read.
*/
private String getFileContent(File file) {
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(file));
try {
String line = null;
while (( line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
catch (java.io.IOException e) {
logger.warning("failed to read header include file: " + e);
return "";
}
finally {
try {
input.close();
}
catch (java.io.IOException e) {
logger.info("failed to close header include file: " + e);
}
}
}
catch (java.io.FileNotFoundException e) {
return "";
}
return contents.toString();
}
/**
* Return string from the header include file so it can be embedded into
* page footer.
*/
public String getFooterIncludeFileContent() {
File hdrfile = new File(getDataRoot(), "footer_include");
return getFileContent(hdrfile);
}
/**
* Return string from the header include file so it can be embedded into
* page header.
*/
public String getHeaderIncludeFileContent() {
File hdrfile = new File(getDataRoot(), "header_include");
return getFileContent(hdrfile);
}
public String getDatabaseDriver() {
return databaseDriver;
}
public void setDatabaseDriver(String databaseDriver) {
this.databaseDriver = databaseDriver;
}
public String getDatabaseUrl() {
return databaseUrl;
}
public void setDatabaseUrl(String databaseUrl) {
this.databaseUrl = databaseUrl;
}
public Set<String> getAllowedSymlinks() {
return allowedSymlinks;
}
public void setAllowedSymlinks(Set<String> allowedSymlinks) {
this.allowedSymlinks = allowedSymlinks;
}
public boolean isObfuscatingEMailAddresses() {
return obfuscatingEMailAddresses;
}
public void setObfuscatingEMailAddresses(boolean obfuscate) {
this.obfuscatingEMailAddresses = obfuscate;
}
public boolean isChattyStatusPage() {
return chattyStatusPage;
}
public void setChattyStatusPage(boolean chattyStatusPage) {
this.chattyStatusPage = chattyStatusPage;
}
/**
* Write the current configuration to a file
* @param file the file to write the configuration into
* @throws IOException if an error occurs
*/
public void write(File file) throws IOException {
final FileOutputStream out = new FileOutputStream(file);
try {
this.encodeObject(out);
} finally {
IOUtils.close(out);
}
}
public String getXMLRepresentationAsString() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
this.encodeObject(bos);
return bos.toString();
}
private void encodeObject(OutputStream out) {
XMLEncoder e = new XMLEncoder(new BufferedOutputStream(out));
e.writeObject(this);
e.close();
}
public static Configuration read(File file) throws IOException {
final FileInputStream in = new FileInputStream(file);
try {
return decodeObject(in);
} finally {
IOUtils.close(in);
}
}
public static Configuration makeXMLStringAsConfiguration(String xmlconfig) throws IOException {
final Configuration ret;
final ByteArrayInputStream in = new ByteArrayInputStream(xmlconfig.getBytes());
ret = decodeObject(in);
return ret;
}
private static Configuration decodeObject(InputStream in) throws IOException {
XMLDecoder d = new XMLDecoder(new BufferedInputStream(in));
final Object ret = d.readObject();
d.close();
if (!(ret instanceof Configuration)) {
throw new IOException("Not a valid config file");
}
return (Configuration)ret;
}
}
| true | true | public Configuration() {
//defaults for an opengrok instance configuration
setHistoryCache(true);
setHistoryCacheTime(30);
setHistoryCacheInDB(false);
setProjects(new ArrayList<Project>());
setRepositories(new ArrayList<RepositoryInfo>());
setUrlPrefix("/source/s?");
//setUrlPrefix("../s?"); // TODO generate relative search paths, get rid of -w <webapp> option to indexer !
setCtags(System.getProperty("org.opensolaris.opengrok.analysis.Ctags", "ctags"));
//below can cause an outofmemory error, since it is defaulting to NO LIMIT
setIndexWordLimit(Integer.MAX_VALUE);
setVerbose(false);
setPrintProgress(false);
setGenerateHtml(true);
setQuickContextScan(true);
setIgnoredNames(new IgnoredNames());
setIncludedNames(new Filter());
setUserPage("http://www.opensolaris.org/viewProfile.jspa?username=");
setBugPage("http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=");
setBugPattern("\\b([12456789][0-9]{6})\\b");
setReviewPage("http://arc.opensolaris.org/caselog/PSARC/");
setReviewPattern("\\b(\\d{4}/\\d{3})\\b"); // in form e.g. PSARC 2008/305
setWebappLAF("default");
setRemoteScmSupported(false);
setOptimizeDatabase(true);
setUsingLuceneLocking(false);
setCompressXref(true);
setIndexVersionedFilesOnly(false);
setHitsPerPage(25);
setCachePages(5);
setScanningDepth(3); // default depth of scanning for repositories
setAllowedSymlinks(new HashSet<String>());
setTabSize(4);
cmds = new HashMap<String, String>();
}
| public Configuration() {
//defaults for an opengrok instance configuration
setHistoryCache(true);
setHistoryCacheTime(30);
setHistoryCacheInDB(false);
setProjects(new ArrayList<Project>());
setRepositories(new ArrayList<RepositoryInfo>());
setUrlPrefix("/source/s?");
//setUrlPrefix("../s?"); // TODO generate relative search paths, get rid of -w <webapp> option to indexer !
setCtags(System.getProperty("org.opensolaris.opengrok.analysis.Ctags", "ctags"));
//below can cause an outofmemory error, since it is defaulting to NO LIMIT
setIndexWordLimit(Integer.MAX_VALUE);
setVerbose(false);
setPrintProgress(false);
setGenerateHtml(true);
setQuickContextScan(true);
setIgnoredNames(new IgnoredNames());
setIncludedNames(new Filter());
setUserPage("http://www.opensolaris.org/viewProfile.jspa?username=");
setBugPage("http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=");
setBugPattern("\\b([12456789][0-9]{6})\\b");
setReviewPage("http://arc.opensolaris.org/caselog/PSARC/");
setReviewPattern("\\b(\\d{4}/\\d{3})\\b"); // in form e.g. PSARC 2008/305
setWebappLAF("default");
setRemoteScmSupported(false);
setOptimizeDatabase(true);
setUsingLuceneLocking(false);
setCompressXref(true);
setIndexVersionedFilesOnly(false);
setHitsPerPage(25);
setCachePages(5);
setScanningDepth(3); // default depth of scanning for repositories
setAllowedSymlinks(new HashSet<String>());
//setTabSize(4);
cmds = new HashMap<String, String>();
}
|
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/PaymentProcess.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/PaymentProcess.java
index 5e63b464..d2a7e551 100644
--- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/PaymentProcess.java
+++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/PaymentProcess.java
@@ -1,473 +1,474 @@
package pt.ist.expenditureTrackingSystem.domain.acquisitions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import module.mission.domain.MissionProcess;
import module.workflow.domain.ProcessFile;
import module.workflow.domain.WorkflowLog;
import module.workflow.domain.utils.WorkflowCommentCounter;
import module.workflow.util.HasPresentableProcessState;
import module.workflow.util.PresentableProcessState;
import module.workflow.widgets.UnreadCommentsWidget;
import myorg.domain.User;
import myorg.domain.VirtualHost;
import myorg.domain.exceptions.DomainException;
import myorg.domain.util.Money;
import myorg.util.BundleUtil;
import myorg.util.ClassNameBundle;
import org.joda.time.LocalDate;
import pt.ist.emailNotifier.domain.Email;
import pt.ist.expenditureTrackingSystem.domain.ExpenditureTrackingSystem;
import pt.ist.expenditureTrackingSystem.domain.ProcessState;
import pt.ist.expenditureTrackingSystem.domain.authorizations.Authorization;
import pt.ist.expenditureTrackingSystem.domain.organization.Person;
import pt.ist.expenditureTrackingSystem.domain.organization.Project;
import pt.ist.expenditureTrackingSystem.domain.organization.SubProject;
import pt.ist.expenditureTrackingSystem.domain.organization.Supplier;
import pt.ist.expenditureTrackingSystem.domain.organization.Unit;
@ClassNameBundle(bundle = "resources/ExpenditureResources")
public abstract class PaymentProcess extends PaymentProcess_Base implements HasPresentableProcessState {
public static Comparator<PaymentProcess> COMPARATOR_BY_YEAR_AND_ACQUISITION_PROCESS_NUMBER = new Comparator<PaymentProcess>() {
@Override
public int compare(PaymentProcess o1, PaymentProcess o2) {
int yearComp = COMPARATOR_BY_YEAR.compare(o1, o2);
return (yearComp != 0) ? yearComp : COMPARATOR_BY_ACQUISITION_PROCESS_NUMBER.compare(o1, o2);
}
};
public static Comparator<PaymentProcess> COMPARATOR_BY_YEAR = new Comparator<PaymentProcess>() {
@Override
public int compare(PaymentProcess o1, PaymentProcess o2) {
return o1.getPaymentProcessYear().getYear().compareTo(o2.getPaymentProcessYear().getYear());
}
};
public static Comparator<PaymentProcess> COMPARATOR_BY_ACQUISITION_PROCESS_NUMBER = new Comparator<PaymentProcess>() {
@Override
public int compare(PaymentProcess o1, PaymentProcess o2) {
return o1.getAcquisitionProcessNumber().compareTo(o2.getAcquisitionProcessNumber());
}
};
static {
UnreadCommentsWidget.register(new WorkflowCommentCounter(PaymentProcess.class));
}
public PaymentProcess() {
super();
final PaymentProcessYear acquisitionProcessYear = getPaymentProcessYearForConstruction();
setPaymentProcessYear(acquisitionProcessYear);
setAcquisitionProcessNumber(acquisitionProcessYear.nextAcquisitionProcessYearNumber());
}
private PaymentProcessYear getPaymentProcessYearForConstruction() {
return PaymentProcessYear.getPaymentProcessYearByYear(getYearForConstruction());
}
protected int getYearForConstruction() {
return new LocalDate().getYear();
}
public abstract <T extends RequestWithPayment> T getRequest();
public List<Unit> getPayingUnits() {
List<Unit> res = new ArrayList<Unit>();
for (Financer financer : getRequest().getFinancers()) {
res.add(financer.getUnit());
}
return res;
}
public boolean isRealValueEqualOrLessThanFundAllocation() {
Money allocatedMoney = this.getRequest().getTotalValue();
Money realMoney = this.getRequest().getRealTotalValue();
return realMoney.isLessThanOrEqual(allocatedMoney);
}
public boolean isResponsibleForAtLeastOnePayingUnit(Person person) {
for (Unit unit : getPayingUnits()) {
if (unit.isResponsible(person)) {
return true;
}
}
return false;
}
public Person getRequestor() {
return getRequest().getRequester();
}
public boolean isResponsibleForUnit(Person person) {
Set<Authorization> validAuthorizations = person.getValidAuthorizations();
for (Unit unit : getPayingUnits()) {
for (Authorization authorization : validAuthorizations) {
if (unit.isSubUnit(authorization.getUnit())) {
return true;
}
}
}
return false;
}
public boolean isResponsibleForUnit() {
final Person loggedPerson = getLoggedPerson();
return loggedPerson != null && isResponsibleForUnit(loggedPerson);
}
public boolean isProjectAccountingEmployee(final Person person) {
return getRequest().isProjectAccountingEmployee(person);
}
public boolean isTreasuryMember(final Person person) {
return getRequest().isTreasuryMember(person);
}
public boolean isProjectAccountingEmployee() {
final Person loggedPerson = getLoggedPerson();
return loggedPerson != null && isProjectAccountingEmployee(loggedPerson);
}
public boolean hasAllocatedFundsForAllProjectFinancers(final Person person) {
return getRequest().hasAllocatedFundsForAllProjectFinancers(person);
}
public boolean hasAllInvoicesAllocated() {
return getRequest().hasAllInvoicesAllocated();
}
public boolean hasAllInvoicesAllocatedInProject() {
return getRequest().hasAllInvoicesAllocatedInProject();
}
public boolean hasAnyFundAllocationId() {
return getRequest().hasAnyFundAllocationId();
}
public boolean hasAnyEffectiveFundAllocationId() {
return getRequest().hasAnyEffectiveFundAllocationId();
}
public boolean hasAnyNonProjectFundAllocationId() {
return getRequest().hasAnyNonProjectFundAllocationId();
}
public boolean isAccountingEmployee(final Person person) {
return getRequest().isAccountingEmployee(person);
}
public boolean isProjectAccountingEmployeeForOnePossibleUnit() {
final Person loggedPerson = getLoggedPerson();
return loggedPerson != null && isProjectAccountingEmployeeForOnePossibleUnit(loggedPerson);
}
public boolean isProjectAccountingEmployeeForOnePossibleUnit(final Person person) {
return getRequest().isProjectAccountingEmployeeForOnePossibleUnit(person);
}
public boolean isAccountingEmployee() {
final Person loggedPerson = getLoggedPerson();
return loggedPerson != null && isAccountingEmployee(loggedPerson);
}
public boolean isAccountingEmployeeForOnePossibleUnit() {
final Person loggedPerson = getLoggedPerson();
return loggedPerson != null && isAccountingEmployeeForOnePossibleUnit(loggedPerson);
}
public boolean isAccountingEmployeeForOnePossibleUnit(final Person person) {
return getRequest().isAccountingEmployeeForOnePossibleUnit(person);
}
public boolean hasAllocatedFundsForAllProjectFinancers() {
return getRequest().hasAllocatedFundsForAllProjectFinancers();
}
public boolean hasAnyAllocatedFunds() {
return getRequest().hasAnyAllocatedFunds();
}
public boolean hasAllFundAllocationId(Person person) {
return getRequest().hasAllFundAllocationId(person);
}
public Set<Financer> getFinancersWithFundsAllocated() {
return getRequest().getFinancersWithFundsAllocated();
}
public Set<Financer> getFinancersWithFundsInitiallyAllocated() {
return getRequest().getFinancersWithFundsInitiallyAllocated();
}
public Set<Financer> getFinancersWithFundsAllocated(Person person) {
return getRequest().getFinancersWithFundsAllocated(person);
}
public Set<ProjectFinancer> getProjectFinancersWithFundsAllocated() {
return getRequest().getProjectFinancersWithFundsAllocated();
}
public Set<ProjectFinancer> getProjectFinancersWithFundsAllocated(final Person person) {
return getRequest().getProjectFinancersWithFundsAllocated(person);
}
public abstract boolean isCanceled();
public abstract boolean isInGenesis();
public abstract boolean isPendingApproval();
public abstract boolean isInApprovedState();
public abstract boolean isPendingFundAllocation();
public abstract void allocateFundsToUnit();
public abstract void submitForApproval();
public abstract void submitForFundAllocation();
public abstract boolean isInAllocatedToUnitState();
public abstract boolean isInAuthorizedState();
protected abstract void authorize();
public boolean isResponsibleForUnit(final Person person, final Money amount) {
Set<Authorization> validAuthorizations = person.getValidAuthorizations();
for (Unit unit : getPayingUnits()) {
for (Authorization authorization : validAuthorizations) {
if (authorization.getMaxAmount().isGreaterThanOrEqual(amount) && unit.isSubUnit(authorization.getUnit())) {
final ExpenditureTrackingSystem instance = ExpenditureTrackingSystem.getInstance();
- if (!authorization.getUnit().hasParentUnit() ||
- (!isProcessessStartedWithInvoive() && (
+ if (!authorization.getUnit().hasParentUnit()
+ || !isProcessessStartedWithInvoive()
+ || (isProcessessStartedWithInvoive() && (
instance.getValueRequireingTopLevelAuthorization() == null ||
instance.getValueRequireingTopLevelAuthorization().isGreaterThan(amount)))) {
return true;
}
}
}
}
return false;
}
protected boolean isProcessessStartedWithInvoive() {
return false;
}
public void authorizeBy(final Person person) {
getRequest().authorizeBy(person);
if (getRequest().isAuthorizedByAllResponsibles()) {
authorize();
}
}
public boolean hasProjectsAsPayingUnits() {
for (Unit unit : getPayingUnits()) {
if (unit instanceof Project || unit instanceof SubProject) {
return true;
}
}
return false;
}
public boolean isRealValueFullyAttributedToUnits() {
return getRequest().isRealValueFullyAttributedToUnits();
}
public boolean isSimplifiedProcedureProcess() {
return false;
}
public boolean isInvoiceConfirmed() {
return false;
}
public boolean hasAllocatedFundsPermanentlyForAllProjectFinancers() {
final RequestWithPayment requestWithPayment = getRequest();
return requestWithPayment.hasAllocatedFundsPermanentlyForAllProjectFinancers();
}
public boolean hasAllocatedFundsPermanentlyForAnyProjectFinancers() {
final RequestWithPayment requestWithPayment = getRequest();
return requestWithPayment.hasAllocatedFundsPermanentlyForAnyProjectFinancer();
}
public void allocateFundsPermanently() {
}
public boolean isAllocatedPermanently() {
return false;
}
public void resetEffectiveFundAllocationId() {
}
public <T extends WorkflowLog> List<T> getExecutionLogsForState(String stateName) {
return (List<T>) getExecutionLogs();
}
public boolean isPayed() {
return false;
}
public boolean isAuthorized() {
return isInAuthorizedState();
}
public boolean isRefundProcess() {
return false;
}
public abstract String getAcquisitionProcessId();
private static final String EMPTY_STRING = new String();
public String getProcessStateDescription() {
return EMPTY_STRING;
}
public String getProcessStateName() {
return EMPTY_STRING;
}
public int getProcessStateOrder() {
return 0;
}
public abstract Collection<Supplier> getSuppliers();
public String getSuppliersDescription() {
Iterator<Supplier> iterator = getSuppliers().iterator();
StringBuilder builder = new StringBuilder();
while (iterator.hasNext()) {
builder.append(iterator.next().getName());
if (iterator.hasNext()) {
builder.append(" ,");
}
}
return builder.toString();
}
public String getTypeDescription() {
return BundleUtil.getStringFromResourceBundle("resources/ExpenditureResources", "label." + getClass().getSimpleName()
+ ".description");
}
public String getTypeShortDescription() {
return BundleUtil.getStringFromResourceBundle("resources/ExpenditureResources", "label." + getClass().getSimpleName()
+ ".shortDescription");
}
public abstract boolean isAppiableForYear(final int year);
public boolean isPriorityProcess() {
for (RequestItem item : getRequest().getRequestItems()) {
if (item.getCPVReference().isPriorityCode()) {
return true;
}
}
return false;
}
@Override
public void notifyUserDueToComment(User user, String comment) {
List<String> toAddress = new ArrayList<String>();
toAddress.clear();
final String email = user.getExpenditurePerson().getEmail();
if (email != null) {
toAddress.add(email);
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
new Email(virtualHost.getApplicationSubTitle().getContent(),
virtualHost.getSystemEmailAddress(), new String[] {}, toAddress, Collections.EMPTY_LIST,
Collections.EMPTY_LIST, BundleUtil.getFormattedStringFromResourceBundle("resources/AcquisitionResources",
"label.email.commentCreated.subject", getAcquisitionProcessId()),
BundleUtil.getFormattedStringFromResourceBundle("resources/AcquisitionResources",
"label.email.commentCreated.body", Person.getLoggedPerson().getName(), getAcquisitionProcessId(),
comment));
}
}
public boolean isCurrentUserObserver() {
return isObserver(Person.getLoggedPerson());
}
public boolean isObserver(Person person) {
if (getRequest().getRequestingUnit().hasObservers(person)) {
return true;
}
for (Unit unit : getPayingUnits()) {
if (unit.hasObservers(person)) {
return true;
}
}
return false;
}
@Override
public User getProcessCreator() {
return getRequest().getRequester().getUser();
}
public List<ProcessFile> getGenericFiles() {
return getFiles(ProcessFile.class);
}
public abstract void revertToState(ProcessState processState);
public abstract String getLocalizedName();
@Override
public void setMissionProcess(final MissionProcess missionProcess) {
if (missionProcess == null
// || (missionProcess.isExpenditureAuthorized() && missionProcess.areAllParticipantsAuthorized())
|| (!missionProcess.isUnderConstruction()
&& !missionProcess.getIsCanceled()
&& !missionProcess.isTerminated()
/*&& missionProcess.getMission().isPendingApproval()*/)) {
super.setMissionProcess(missionProcess);
} else {
// throw new DomainException("error.cannot.connect.acquisition.to.unauthorized.mission",
throw new DomainException("error.cannot.connect.acquisition.to.unsubmitted.for.approval.mission",
DomainException.getResourceFor("resources/AcquisitionResources"));
}
}
@Override
public PresentableProcessState getPresentableAcquisitionProcessState() {
return null;
}
@Override
public List<? extends PresentableProcessState> getAvailablePresentableStates() {
return Collections.emptyList();
}
public abstract Money getTotalValue();
public boolean isDirectResponsibleForUnit(final User user, final Money amount) {
final Person person = user.getExpenditurePerson();
for (final Unit unit : getPayingUnits()) {
if (unit.isDirectResponsible(person, amount)) {
return true;
}
}
return false;
}
public abstract Set<CPVReference> getCPVReferences();
public abstract void migrateProcessNumber();
}
| true | true | public boolean isResponsibleForUnit(final Person person, final Money amount) {
Set<Authorization> validAuthorizations = person.getValidAuthorizations();
for (Unit unit : getPayingUnits()) {
for (Authorization authorization : validAuthorizations) {
if (authorization.getMaxAmount().isGreaterThanOrEqual(amount) && unit.isSubUnit(authorization.getUnit())) {
final ExpenditureTrackingSystem instance = ExpenditureTrackingSystem.getInstance();
if (!authorization.getUnit().hasParentUnit() ||
(!isProcessessStartedWithInvoive() && (
instance.getValueRequireingTopLevelAuthorization() == null ||
instance.getValueRequireingTopLevelAuthorization().isGreaterThan(amount)))) {
return true;
}
}
}
}
return false;
}
| public boolean isResponsibleForUnit(final Person person, final Money amount) {
Set<Authorization> validAuthorizations = person.getValidAuthorizations();
for (Unit unit : getPayingUnits()) {
for (Authorization authorization : validAuthorizations) {
if (authorization.getMaxAmount().isGreaterThanOrEqual(amount) && unit.isSubUnit(authorization.getUnit())) {
final ExpenditureTrackingSystem instance = ExpenditureTrackingSystem.getInstance();
if (!authorization.getUnit().hasParentUnit()
|| !isProcessessStartedWithInvoive()
|| (isProcessessStartedWithInvoive() && (
instance.getValueRequireingTopLevelAuthorization() == null ||
instance.getValueRequireingTopLevelAuthorization().isGreaterThan(amount)))) {
return true;
}
}
}
}
return false;
}
|
diff --git a/bobblehead/src/com/bn/bobblehead/FaceSelectActivity.java b/bobblehead/src/com/bn/bobblehead/FaceSelectActivity.java
index f3acadd..6afdf24 100644
--- a/bobblehead/src/com/bn/bobblehead/FaceSelectActivity.java
+++ b/bobblehead/src/com/bn/bobblehead/FaceSelectActivity.java
@@ -1,299 +1,300 @@
package com.bn.bobblehead;
import java.io.FileOutputStream;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
@SuppressLint("NewApi")
public class FaceSelectActivity extends Activity {
private SelectView mSelectView;
private SensorManager mSensorManager;
private PowerManager mPowerManager;
private WindowManager mWindowManager;
private WakeLock mWakeLock;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get an instance of the SensorManager
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Get an instance of the PowerManager
mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
// Get an instance of the WindowManager
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.getDefaultDisplay();
// Create a bright wake lock
mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass()
.getName());
// instantiate our simulation view and set it as the activity's content
mSelectView = new SelectView(this);
setContentView(mSelectView);
}
@Override
protected void onResume() {
super.onResume();
mWakeLock.acquire();
setContentView(mSelectView);
}
@Override
protected void onPause() {
super.onPause();
// and release our wake-lock
mWakeLock.release();
}
class SelectView extends View implements OnClickListener {
private final Bitmap button;
private Sensor mAccelerometer;
private Bitmap backg;
public SelectView(Context context) {
super(context);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
//get go button and dimensions
Bitmap tmp = BitmapFactory.decodeResource(getResources(), R.drawable.go_button);
button=Bitmap.createScaledBitmap(tmp, 100, 100, false);
buttonR=new Rect(metrics.widthPixels-150,metrics.heightPixels-200,metrics.widthPixels,metrics.heightPixels);
//Get background
tmp=BitmapFactory.decodeFile(HomeScreen.backFil.toString());
backg=Bitmap.createScaledBitmap(tmp, metrics.widthPixels, metrics.heightPixels, false);
Options opts = new Options();
opts.inDither = true;
opts.inPreferredConfig = Bitmap.Config.RGB_565;
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
//Use to crop a bitmap to the specified rectangle using an oval cut
public Bitmap getCroppedBitmap(Bitmap bitmap,RectF r) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(r,new Paint());
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(1,1);
Bitmap resizedBitmap = Bitmap.createBitmap(output, (int)r.left, (int)r.top,
(int) r.width(), (int)r.height(), matrix, true);
System.out.println(canvas.getWidth()+":"+canvas.getHeight());
return resizedBitmap;
}
private Paint p=new Paint();
protected void onDraw(Canvas canvas) {
p.setStyle(Paint.Style.STROKE) ;
p.setStrokeWidth(4f);
p.setARGB(255, 0, 200, 0);
canvas.drawBitmap(backg, 0, 0, null);
if (selection != null){
canvas.drawOval(selection, p);
}
canvas.drawBitmap(button, null,buttonR, null);
// and make sure to redraw asap
invalidate();
}
private Rect buttonR;
private RectF selection;
private boolean rectDrawn=false;
private int ooX;//ovals originx
private int ooY;//avals origin y
int top=0;
int left=0;
int bottom=0;
int right=0;
public boolean onTouchEvent(MotionEvent e) {
// TODO Auto-generated method stub
int x = (int) e.getX();
int y = (int) e.getY();
//Check for button press
if (buttonR.contains(x, y)){
if (selection.width()>0 && selection.height() >0){
Intent i = new Intent(FaceSelectActivity.this,BobActivity.class);
Bitmap face=Bitmap.createBitmap(backg,(int)selection.left, (int)selection.top,(int)selection.width(),(int)selection.height());
face=getCroppedBitmap(backg,selection);
try {
if(!HomeScreen.faceFil.exists()){HomeScreen.faceFil.createNewFile();}
FileOutputStream out = new FileOutputStream(HomeScreen.faceFil);
face.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
RectF rec= new RectF(selection.left, selection.top,selection.left+selection.width(),selection.top+selection.height());
i.putExtra("rec", rec);
startActivity(i);
+ finish();
return true;
}
else {
showDialog(DIALOG_ALERT);
}
}
boolean backFlag=false;//true if the oval is being drawn towards the origin
//Check for oval drawings
switch (e.getAction()) {
//get an origin for the oval
case MotionEvent.ACTION_DOWN:
if (!rectDrawn){
top=(int) y;
left=(int) x;
ooX=(int) x;
ooY=(int) y;
}
//check x,y against the origin then save the rectangle
case MotionEvent.ACTION_MOVE:
if (x<ooX){
left=x;
right=ooX;
}else{
left=ooX;
right=x;
}
if (y<ooY){
top=y;
bottom=ooY;
}else{
top=ooY;
bottom=y;
}
}
//if no oval is drawn
if (top==0 && left==0 && right==0 && bottom==0){
selection=null;
}
selection=new RectF(left,top,right,bottom);
return true;
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
private static final int DIALOG_ALERT = 10;
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ALERT:
// Create out AlterDialog
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please Select a face.");
builder.setCancelable(true);
builder.setPositiveButton("Ok", new OkOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onCreateDialog(id);
}
private final class OkOnClickListener implements DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
//FaceSelectActivity.this.finish();
}
}
}
| true | true | public boolean onTouchEvent(MotionEvent e) {
// TODO Auto-generated method stub
int x = (int) e.getX();
int y = (int) e.getY();
//Check for button press
if (buttonR.contains(x, y)){
if (selection.width()>0 && selection.height() >0){
Intent i = new Intent(FaceSelectActivity.this,BobActivity.class);
Bitmap face=Bitmap.createBitmap(backg,(int)selection.left, (int)selection.top,(int)selection.width(),(int)selection.height());
face=getCroppedBitmap(backg,selection);
try {
if(!HomeScreen.faceFil.exists()){HomeScreen.faceFil.createNewFile();}
FileOutputStream out = new FileOutputStream(HomeScreen.faceFil);
face.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
RectF rec= new RectF(selection.left, selection.top,selection.left+selection.width(),selection.top+selection.height());
i.putExtra("rec", rec);
startActivity(i);
return true;
}
else {
showDialog(DIALOG_ALERT);
}
}
boolean backFlag=false;//true if the oval is being drawn towards the origin
//Check for oval drawings
switch (e.getAction()) {
//get an origin for the oval
case MotionEvent.ACTION_DOWN:
if (!rectDrawn){
top=(int) y;
left=(int) x;
ooX=(int) x;
ooY=(int) y;
}
//check x,y against the origin then save the rectangle
case MotionEvent.ACTION_MOVE:
if (x<ooX){
left=x;
right=ooX;
}else{
left=ooX;
right=x;
}
if (y<ooY){
top=y;
bottom=ooY;
}else{
top=ooY;
bottom=y;
}
}
//if no oval is drawn
if (top==0 && left==0 && right==0 && bottom==0){
selection=null;
}
selection=new RectF(left,top,right,bottom);
return true;
}
| public boolean onTouchEvent(MotionEvent e) {
// TODO Auto-generated method stub
int x = (int) e.getX();
int y = (int) e.getY();
//Check for button press
if (buttonR.contains(x, y)){
if (selection.width()>0 && selection.height() >0){
Intent i = new Intent(FaceSelectActivity.this,BobActivity.class);
Bitmap face=Bitmap.createBitmap(backg,(int)selection.left, (int)selection.top,(int)selection.width(),(int)selection.height());
face=getCroppedBitmap(backg,selection);
try {
if(!HomeScreen.faceFil.exists()){HomeScreen.faceFil.createNewFile();}
FileOutputStream out = new FileOutputStream(HomeScreen.faceFil);
face.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
RectF rec= new RectF(selection.left, selection.top,selection.left+selection.width(),selection.top+selection.height());
i.putExtra("rec", rec);
startActivity(i);
finish();
return true;
}
else {
showDialog(DIALOG_ALERT);
}
}
boolean backFlag=false;//true if the oval is being drawn towards the origin
//Check for oval drawings
switch (e.getAction()) {
//get an origin for the oval
case MotionEvent.ACTION_DOWN:
if (!rectDrawn){
top=(int) y;
left=(int) x;
ooX=(int) x;
ooY=(int) y;
}
//check x,y against the origin then save the rectangle
case MotionEvent.ACTION_MOVE:
if (x<ooX){
left=x;
right=ooX;
}else{
left=ooX;
right=x;
}
if (y<ooY){
top=y;
bottom=ooY;
}else{
top=ooY;
bottom=y;
}
}
//if no oval is drawn
if (top==0 && left==0 && right==0 && bottom==0){
selection=null;
}
selection=new RectF(left,top,right,bottom);
return true;
}
|
diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/tasklet/TaskletStep.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/tasklet/TaskletStep.java
index 15752c377..6a7c42117 100644
--- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/tasklet/TaskletStep.java
+++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/tasklet/TaskletStep.java
@@ -1,499 +1,497 @@
/*
* Copyright 2006-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core.step.tasklet;
import java.util.concurrent.Semaphore;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.ChunkListener;
import org.springframework.batch.core.JobInterruptedException;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.core.listener.CompositeChunkListener;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.scope.context.StepContextRepeatCallback;
import org.springframework.batch.core.step.AbstractStep;
import org.springframework.batch.core.step.FatalStepExecutionException;
import org.springframework.batch.core.step.StepInterruptionPolicy;
import org.springframework.batch.core.step.ThreadStepInterruptionPolicy;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.CompositeItemStream;
import org.springframework.batch.repeat.RepeatContext;
import org.springframework.batch.repeat.RepeatOperations;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.batch.repeat.support.RepeatTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;
/**
* Simple implementation of executing the step as a call to a {@link Tasklet},
* possibly repeated, and each call surrounded by a transaction. The structure
* is therefore that of a loop with transaction boundary inside the loop. The
* loop is controlled by the step operations (
* {@link #setStepOperations(RepeatOperations)}).<br/>
* <br/>
*
* Clients can use interceptors in the step operations to intercept or listen to
* the iteration on a step-wide basis, for instance to get a callback when the
* step is complete. Those that want callbacks at the level of an individual
* tasks, can specify interceptors for the chunk operations.
*
* @author Dave Syer
* @author Lucas Ward
* @author Ben Hale
* @author Robert Kasanicky
* @author Michael Minella
* @author Will Schipp
*/
@SuppressWarnings("serial")
public class TaskletStep extends AbstractStep {
private static final Log logger = LogFactory.getLog(TaskletStep.class);
private RepeatOperations stepOperations = new RepeatTemplate();
private CompositeChunkListener chunkListener = new CompositeChunkListener();
// default to checking current thread for interruption.
private StepInterruptionPolicy interruptionPolicy = new ThreadStepInterruptionPolicy();
private CompositeItemStream stream = new CompositeItemStream();
private PlatformTransactionManager transactionManager;
private TransactionAttribute transactionAttribute = new DefaultTransactionAttribute() {
@Override
public boolean rollbackOn(Throwable ex) {
return true;
}
};
private Tasklet tasklet;
/**
* Default constructor.
*/
public TaskletStep() {
this(null);
}
/**
* @param name
*/
public TaskletStep(String name) {
super(name);
}
/*
* (non-Javadoc)
*
* @see
* org.springframework.batch.core.step.AbstractStep#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
Assert.state(transactionManager != null, "A transaction manager must be provided");
}
/**
* Public setter for the {@link PlatformTransactionManager}.
*
* @param transactionManager the transaction manager to set
*/
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
/**
* Public setter for the {@link TransactionAttribute}.
*
* @param transactionAttribute the {@link TransactionAttribute} to set
*/
public void setTransactionAttribute(TransactionAttribute transactionAttribute) {
this.transactionAttribute = transactionAttribute;
}
/**
* Public setter for the {@link Tasklet}.
*
* @param tasklet the {@link Tasklet} to set
*/
public void setTasklet(Tasklet tasklet) {
this.tasklet = tasklet;
if (tasklet instanceof StepExecutionListener) {
registerStepExecutionListener((StepExecutionListener) tasklet);
}
}
/**
* Register a chunk listener for callbacks at the appropriate stages in a
* step execution.
*
* @param listener a {@link ChunkListener}
*/
public void registerChunkListener(ChunkListener listener) {
this.chunkListener.register(listener);
}
/**
* Register each of the objects as listeners.
*
* @param listeners an array of listener objects of known types.
*/
public void setChunkListeners(ChunkListener[] listeners) {
for (int i = 0; i < listeners.length; i++) {
registerChunkListener(listeners[i]);
}
}
/**
* Register each of the streams for callbacks at the appropriate time in the
* step. The {@link ItemReader} and {@link ItemWriter} are automatically
* registered, but it doesn't hurt to also register them here. Injected
* dependencies of the reader and writer are not automatically registered,
* so if you implement {@link ItemWriter} using delegation to another object
* which itself is a {@link ItemStream}, you need to register the delegate
* here.
*
* @param streams an array of {@link ItemStream} objects.
*/
public void setStreams(ItemStream[] streams) {
for (int i = 0; i < streams.length; i++) {
registerStream(streams[i]);
}
}
/**
* Register a single {@link ItemStream} for callbacks to the stream
* interface.
*
* @param stream
*/
public void registerStream(ItemStream stream) {
this.stream.register(stream);
}
/**
* The {@link RepeatOperations} to use for the outer loop of the batch
* processing. Should be set up by the caller through a factory. Defaults to
* a plain {@link RepeatTemplate}.
*
* @param stepOperations a {@link RepeatOperations} instance.
*/
public void setStepOperations(RepeatOperations stepOperations) {
this.stepOperations = stepOperations;
}
/**
* Setter for the {@link StepInterruptionPolicy}. The policy is used to
* check whether an external request has been made to interrupt the job
* execution.
*
* @param interruptionPolicy a {@link StepInterruptionPolicy}
*/
public void setInterruptionPolicy(StepInterruptionPolicy interruptionPolicy) {
this.interruptionPolicy = interruptionPolicy;
}
/**
* Process the step and update its context so that progress can be monitored
* by the caller. The step is broken down into chunks, each one executing in
* a transaction. The step and its execution and execution context are all
* given an up to date {@link BatchStatus}, and the {@link JobRepository} is
* used to store the result. Various reporting information are also added to
* the current context governing the step execution, which would normally be
* available to the caller through the step's {@link ExecutionContext}.<br/>
*
* @throws JobInterruptedException if the step or a chunk is interrupted
* @throws RuntimeException if there is an exception during a chunk
* execution
*
*/
@Override
@SuppressWarnings("unchecked")
protected void doExecute(StepExecution stepExecution) throws Exception {
stream.update(stepExecution.getExecutionContext());
getJobRepository().updateExecutionContext(stepExecution);
// Shared semaphore per step execution, so other step executions can run
// in parallel without needing the lock
final Semaphore semaphore = createSemaphore();
stepOperations.iterate(new StepContextRepeatCallback(stepExecution) {
@Override
public RepeatStatus doInChunkContext(RepeatContext repeatContext, ChunkContext chunkContext)
throws Exception {
StepExecution stepExecution = chunkContext.getStepContext().getStepExecution();
// Before starting a new transaction, check for
// interruption.
interruptionPolicy.checkInterrupted(stepExecution);
RepeatStatus result;
try {
result = (RepeatStatus) new TransactionTemplate(transactionManager, transactionAttribute)
.execute(new ChunkTransactionCallback(chunkContext, semaphore));
}
catch (UncheckedTransactionException e) {
// Allow checked exceptions to be thrown inside callback
throw (Exception) e.getCause();
}
chunkListener.afterChunk(chunkContext);
// Check for interruption after transaction as well, so that
// the interrupted exception is correctly propagated up to
// caller
interruptionPolicy.checkInterrupted(stepExecution);
return result;
}
});
}
/**
* Extension point mainly for test purposes so that the behaviour of the
* lock can be manipulated to simulate various pathologies.
*
* @return a semaphore for locking access to the JobRepository
*/
protected Semaphore createSemaphore() {
return new Semaphore(1);
}
@Override
protected void close(ExecutionContext ctx) throws Exception {
stream.close();
}
@Override
protected void open(ExecutionContext ctx) throws Exception {
stream.open(ctx);
}
/**
* retrieve the tasklet - helper method for JobOperator
* @return the {@link Tasklet} instance being executed within this step
*/
public Tasklet getTasklet() {
return tasklet;
}
/**
* A callback for the transactional work inside a chunk. Also detects
* failures in the transaction commit and rollback, only panicking if the
* transaction status is unknown (i.e. if a commit failure leads to a clean
* rollback then we assume the state is consistent).
*
* @author Dave Syer
*
*/
@SuppressWarnings("rawtypes")
private class ChunkTransactionCallback extends TransactionSynchronizationAdapter implements TransactionCallback {
private final StepExecution stepExecution;
private final ChunkContext chunkContext;
private boolean rolledBack = false;
private boolean stepExecutionUpdated = false;
private StepExecution oldVersion;
private boolean locked = false;
private final Semaphore semaphore;
public ChunkTransactionCallback(ChunkContext chunkContext, Semaphore semaphore) {
this.chunkContext = chunkContext;
this.stepExecution = chunkContext.getStepContext().getStepExecution();
this.semaphore = semaphore;
}
@Override
public void afterCompletion(int status) {
try {
if (status != TransactionSynchronization.STATUS_COMMITTED) {
if (stepExecutionUpdated) {
// Wah! the commit failed. We need to rescue the step
// execution data.
logger.info("Commit failed while step execution data was already updated. "
+ "Reverting to old version.");
copy(oldVersion, stepExecution);
if (status == TransactionSynchronization.STATUS_ROLLED_BACK) {
rollback(stepExecution);
}
}
chunkListener.afterChunkError(chunkContext);
}
if (status == TransactionSynchronization.STATUS_UNKNOWN) {
logger.error("Rolling back with transaction in unknown state");
rollback(stepExecution);
stepExecution.upgradeStatus(BatchStatus.UNKNOWN);
stepExecution.setTerminateOnly();
}
}
finally {
// Only release the lock if we acquired it, and release as late
// as possible
if (locked) {
semaphore.release();
}
locked = false;
}
}
@Override
public Object doInTransaction(TransactionStatus status) {
TransactionSynchronizationManager.registerSynchronization(this);
RepeatStatus result = RepeatStatus.CONTINUABLE;
StepContribution contribution = stepExecution.createStepContribution();
chunkListener.beforeChunk(chunkContext);
// In case we need to push it back to its old value
// after a commit fails...
oldVersion = new StepExecution(stepExecution.getStepName(), stepExecution.getJobExecution());
copy(stepExecution, oldVersion);
try {
try {
try {
result = tasklet.execute(contribution, chunkContext);
if (result == null) {
result = RepeatStatus.FINISHED;
}
}
catch (Exception e) {
if (transactionAttribute.rollbackOn(e)) {
chunkContext.setAttribute(ChunkListener.ROLLBACK_EXCEPTION_KEY, e);
throw e;
}
}
}
finally {
// If the step operations are asynchronous then we need
// to synchronize changes to the step execution (at a
// minimum). Take the lock *before* changing the step
// execution.
try {
semaphore.acquire();
locked = true;
}
catch (InterruptedException e) {
logger.error("Thread interrupted while locking for repository update");
stepExecution.setStatus(BatchStatus.STOPPED);
stepExecution.setTerminateOnly();
Thread.currentThread().interrupt();
}
// Apply the contribution to the step
// even if unsuccessful
logger.debug("Applying contribution: " + contribution);
stepExecution.apply(contribution);
}
stepExecutionUpdated = true;
stream.update(stepExecution.getExecutionContext());
try {
// Going to attempt a commit. If it fails this flag will
// stay false and we can use that later.
getJobRepository().updateExecutionContext(stepExecution);
stepExecution.incrementCommitCount();
logger.debug("Saving step execution before commit: " + stepExecution);
getJobRepository().update(stepExecution);
}
catch (Exception e) {
// If we get to here there was a problem saving the step
// execution and we have to fail.
- String msg = "JobRepository failure forcing exit with unknown status";
+ String msg = "JobRepository failure forcing rollback";
logger.error(msg, e);
- stepExecution.upgradeStatus(BatchStatus.UNKNOWN);
- stepExecution.setTerminateOnly();
throw new FatalStepExecutionException(msg, e);
}
}
catch (Error e) {
logger.debug("Rollback for Error: " + e.getClass().getName() + ": " + e.getMessage());
rollback(stepExecution);
throw e;
}
catch (RuntimeException e) {
logger.debug("Rollback for RuntimeException: " + e.getClass().getName() + ": " + e.getMessage());
rollback(stepExecution);
throw e;
}
catch (Exception e) {
logger.debug("Rollback for Exception: " + e.getClass().getName() + ": " + e.getMessage());
rollback(stepExecution);
// Allow checked exceptions
throw new UncheckedTransactionException(e);
}
return result;
}
private void rollback(StepExecution stepExecution) {
if (!rolledBack) {
stepExecution.incrementRollbackCount();
rolledBack = true;
}
}
private void copy(final StepExecution source, final StepExecution target) {
target.setVersion(source.getVersion());
target.setWriteCount(source.getWriteCount());
target.setFilterCount(source.getFilterCount());
target.setCommitCount(source.getCommitCount());
target.setExecutionContext(new ExecutionContext(source.getExecutionContext()));
}
}
}
| false | true | public Object doInTransaction(TransactionStatus status) {
TransactionSynchronizationManager.registerSynchronization(this);
RepeatStatus result = RepeatStatus.CONTINUABLE;
StepContribution contribution = stepExecution.createStepContribution();
chunkListener.beforeChunk(chunkContext);
// In case we need to push it back to its old value
// after a commit fails...
oldVersion = new StepExecution(stepExecution.getStepName(), stepExecution.getJobExecution());
copy(stepExecution, oldVersion);
try {
try {
try {
result = tasklet.execute(contribution, chunkContext);
if (result == null) {
result = RepeatStatus.FINISHED;
}
}
catch (Exception e) {
if (transactionAttribute.rollbackOn(e)) {
chunkContext.setAttribute(ChunkListener.ROLLBACK_EXCEPTION_KEY, e);
throw e;
}
}
}
finally {
// If the step operations are asynchronous then we need
// to synchronize changes to the step execution (at a
// minimum). Take the lock *before* changing the step
// execution.
try {
semaphore.acquire();
locked = true;
}
catch (InterruptedException e) {
logger.error("Thread interrupted while locking for repository update");
stepExecution.setStatus(BatchStatus.STOPPED);
stepExecution.setTerminateOnly();
Thread.currentThread().interrupt();
}
// Apply the contribution to the step
// even if unsuccessful
logger.debug("Applying contribution: " + contribution);
stepExecution.apply(contribution);
}
stepExecutionUpdated = true;
stream.update(stepExecution.getExecutionContext());
try {
// Going to attempt a commit. If it fails this flag will
// stay false and we can use that later.
getJobRepository().updateExecutionContext(stepExecution);
stepExecution.incrementCommitCount();
logger.debug("Saving step execution before commit: " + stepExecution);
getJobRepository().update(stepExecution);
}
catch (Exception e) {
// If we get to here there was a problem saving the step
// execution and we have to fail.
String msg = "JobRepository failure forcing exit with unknown status";
logger.error(msg, e);
stepExecution.upgradeStatus(BatchStatus.UNKNOWN);
stepExecution.setTerminateOnly();
throw new FatalStepExecutionException(msg, e);
}
}
catch (Error e) {
logger.debug("Rollback for Error: " + e.getClass().getName() + ": " + e.getMessage());
rollback(stepExecution);
throw e;
}
catch (RuntimeException e) {
logger.debug("Rollback for RuntimeException: " + e.getClass().getName() + ": " + e.getMessage());
rollback(stepExecution);
throw e;
}
catch (Exception e) {
logger.debug("Rollback for Exception: " + e.getClass().getName() + ": " + e.getMessage());
rollback(stepExecution);
// Allow checked exceptions
throw new UncheckedTransactionException(e);
}
return result;
}
| public Object doInTransaction(TransactionStatus status) {
TransactionSynchronizationManager.registerSynchronization(this);
RepeatStatus result = RepeatStatus.CONTINUABLE;
StepContribution contribution = stepExecution.createStepContribution();
chunkListener.beforeChunk(chunkContext);
// In case we need to push it back to its old value
// after a commit fails...
oldVersion = new StepExecution(stepExecution.getStepName(), stepExecution.getJobExecution());
copy(stepExecution, oldVersion);
try {
try {
try {
result = tasklet.execute(contribution, chunkContext);
if (result == null) {
result = RepeatStatus.FINISHED;
}
}
catch (Exception e) {
if (transactionAttribute.rollbackOn(e)) {
chunkContext.setAttribute(ChunkListener.ROLLBACK_EXCEPTION_KEY, e);
throw e;
}
}
}
finally {
// If the step operations are asynchronous then we need
// to synchronize changes to the step execution (at a
// minimum). Take the lock *before* changing the step
// execution.
try {
semaphore.acquire();
locked = true;
}
catch (InterruptedException e) {
logger.error("Thread interrupted while locking for repository update");
stepExecution.setStatus(BatchStatus.STOPPED);
stepExecution.setTerminateOnly();
Thread.currentThread().interrupt();
}
// Apply the contribution to the step
// even if unsuccessful
logger.debug("Applying contribution: " + contribution);
stepExecution.apply(contribution);
}
stepExecutionUpdated = true;
stream.update(stepExecution.getExecutionContext());
try {
// Going to attempt a commit. If it fails this flag will
// stay false and we can use that later.
getJobRepository().updateExecutionContext(stepExecution);
stepExecution.incrementCommitCount();
logger.debug("Saving step execution before commit: " + stepExecution);
getJobRepository().update(stepExecution);
}
catch (Exception e) {
// If we get to here there was a problem saving the step
// execution and we have to fail.
String msg = "JobRepository failure forcing rollback";
logger.error(msg, e);
throw new FatalStepExecutionException(msg, e);
}
}
catch (Error e) {
logger.debug("Rollback for Error: " + e.getClass().getName() + ": " + e.getMessage());
rollback(stepExecution);
throw e;
}
catch (RuntimeException e) {
logger.debug("Rollback for RuntimeException: " + e.getClass().getName() + ": " + e.getMessage());
rollback(stepExecution);
throw e;
}
catch (Exception e) {
logger.debug("Rollback for Exception: " + e.getClass().getName() + ": " + e.getMessage());
rollback(stepExecution);
// Allow checked exceptions
throw new UncheckedTransactionException(e);
}
return result;
}
|
diff --git a/server/src/org/oryxeditor/server/MultiDownloader.java b/server/src/org/oryxeditor/server/MultiDownloader.java
index 63e83fff..cfabed5b 100644
--- a/server/src/org/oryxeditor/server/MultiDownloader.java
+++ b/server/src/org/oryxeditor/server/MultiDownloader.java
@@ -1,202 +1,202 @@
package org.oryxeditor.server;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* Copyright (c) 2007 Martin Czuchra.
*
* 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.
*/
/**
* This is a rewrite of the original download.php for usage in plugins that need
* to run in the Java environment.
*
* There is no distinction between GET and POST requests, since code relying on
* download.php behaviour would perform a POST to just request the download of
* one or more files from the server.
*
* @author Martin Czuchra
*/
public class MultiDownloader extends HttpServlet {
private static final long serialVersionUID = 544537395679618334L;
/**
* The GET request forwards to the performDownload method.
*/
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
this.performDownload(req, res);
}
/**
* The POST request forwards to the performDownload method.
*/
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
this.performDownload(req, res);
}
private void prepareHeaders(HttpServletResponse res, String mimetype,
String name) {
res.setHeader("Pragma", "public");
res.setHeader("Expires", "0");
res.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
res.addHeader("Cache-Control", "private");
res.setHeader("Content-Transfer-Encoding", "binary");
res.setHeader("Content-Type", mimetype);
res.setHeader("Content-Disposition", "attachment; filename=\"" + name
+ "\"");
}
/**
* Creates a zipfile consisting of filenames and contents provided in
* filenames and contents parameters, respectively. The resulting zip file
* is written into the whereTo stream.
*
* This method requires that the length of the filenames and contents array
* is equal and performs an assertion on this.
*
* @param filenames
* the array of filenames to be written into the zip file.
* @param contents
* the array of file contents to be written into the zipfile
* for the file that is at the same array position in the
* filenames array.
* @param whereTo
* the stream the zipfile should be written to.
* @throws IOException
* when something goes wrong.
*/
private void zip(String[] filenames, String[] contents, OutputStream whereTo)
throws IOException {
assert (filenames.length == contents.length);
// enclose the whereTo stream into a ZipOutputStream.
ZipOutputStream out = new ZipOutputStream(whereTo);
// iterate over all filenames.
for (int i = 0; i < filenames.length; i++) {
// add a new entry for the current filename, write the current
// content and close the entry again.
out.putNextEntry(new ZipEntry(filenames[i]));
out.write(contents[i].getBytes());
out.closeEntry();
}
// Complete the ZIP file
out.close();
}
/**
* Performs the actual download independently of the original HTTP method of
* the request. See in-method comments for details.
*
* @param req
* The original HttpServletRequest object.
* @param res
* The original HttpServletResponse object.
* @throws IOException
*/
private void performDownload(HttpServletRequest req, HttpServletResponse res)
throws IOException {
// if there is a parameter named "download_0", then, by convention,
// there are more than one files to be downloaded in a zip file.
if (req.getParameter("download_0") != null) {
// traverse all files that should be downloaded and that are
// embedded in the request. the content of each file is stored in
// content, the filename in name.
int i = 0;
String content, name;
Vector<String> contents = new Vector<String>(), names = new Vector<String>();
while ((content = req.getParameter("download_" + i)) != null) {
// get current name and increment file counter.
name = req.getParameter("file_" + i++);
// while collecting, write all current names and contents into
// the appropriate Vector objects.
contents.add(content);
names.add(name);
}
// init two arrays the vectors will be cast into.
String[] contentsArray = new String[contents.size()];
String[] namesArray = new String[names.size()];
// prepare the response headers and send the requested file to the
// client. mimetype and filename originally were hardcoded into
// download.php, so they are here, since code may rely on this.
this.prepareHeaders(res, "application/zip", "result.zip");
this.zip(names.toArray(namesArray),
contents.toArray(contentsArray), res.getOutputStream());
} else if (req.getParameter("download") != null) {
// branch for fetching of one file exactly. get the name and content
// of the file into the appropriate string variables.
String name = req.getParameter("file");
- String content = req.getParameter("content");
+ String content = req.getParameter("download");
// prepare headers, with empty mimetype (as download.php does), and
// send the content of the file back to the user.
this.prepareHeaders(res, "", name);
res.getWriter().write(content);
} else {
// when none of the above rules applies, inform the user that
// nothing remains to be done.
// TODO Find appropriate HTTP message here, no code relies on this.
res.getWriter().println("There is nothing to be downloaded.");
}
}
}
| true | true | private void performDownload(HttpServletRequest req, HttpServletResponse res)
throws IOException {
// if there is a parameter named "download_0", then, by convention,
// there are more than one files to be downloaded in a zip file.
if (req.getParameter("download_0") != null) {
// traverse all files that should be downloaded and that are
// embedded in the request. the content of each file is stored in
// content, the filename in name.
int i = 0;
String content, name;
Vector<String> contents = new Vector<String>(), names = new Vector<String>();
while ((content = req.getParameter("download_" + i)) != null) {
// get current name and increment file counter.
name = req.getParameter("file_" + i++);
// while collecting, write all current names and contents into
// the appropriate Vector objects.
contents.add(content);
names.add(name);
}
// init two arrays the vectors will be cast into.
String[] contentsArray = new String[contents.size()];
String[] namesArray = new String[names.size()];
// prepare the response headers and send the requested file to the
// client. mimetype and filename originally were hardcoded into
// download.php, so they are here, since code may rely on this.
this.prepareHeaders(res, "application/zip", "result.zip");
this.zip(names.toArray(namesArray),
contents.toArray(contentsArray), res.getOutputStream());
} else if (req.getParameter("download") != null) {
// branch for fetching of one file exactly. get the name and content
// of the file into the appropriate string variables.
String name = req.getParameter("file");
String content = req.getParameter("content");
// prepare headers, with empty mimetype (as download.php does), and
// send the content of the file back to the user.
this.prepareHeaders(res, "", name);
res.getWriter().write(content);
} else {
// when none of the above rules applies, inform the user that
// nothing remains to be done.
// TODO Find appropriate HTTP message here, no code relies on this.
res.getWriter().println("There is nothing to be downloaded.");
}
}
| private void performDownload(HttpServletRequest req, HttpServletResponse res)
throws IOException {
// if there is a parameter named "download_0", then, by convention,
// there are more than one files to be downloaded in a zip file.
if (req.getParameter("download_0") != null) {
// traverse all files that should be downloaded and that are
// embedded in the request. the content of each file is stored in
// content, the filename in name.
int i = 0;
String content, name;
Vector<String> contents = new Vector<String>(), names = new Vector<String>();
while ((content = req.getParameter("download_" + i)) != null) {
// get current name and increment file counter.
name = req.getParameter("file_" + i++);
// while collecting, write all current names and contents into
// the appropriate Vector objects.
contents.add(content);
names.add(name);
}
// init two arrays the vectors will be cast into.
String[] contentsArray = new String[contents.size()];
String[] namesArray = new String[names.size()];
// prepare the response headers and send the requested file to the
// client. mimetype and filename originally were hardcoded into
// download.php, so they are here, since code may rely on this.
this.prepareHeaders(res, "application/zip", "result.zip");
this.zip(names.toArray(namesArray),
contents.toArray(contentsArray), res.getOutputStream());
} else if (req.getParameter("download") != null) {
// branch for fetching of one file exactly. get the name and content
// of the file into the appropriate string variables.
String name = req.getParameter("file");
String content = req.getParameter("download");
// prepare headers, with empty mimetype (as download.php does), and
// send the content of the file back to the user.
this.prepareHeaders(res, "", name);
res.getWriter().write(content);
} else {
// when none of the above rules applies, inform the user that
// nothing remains to be done.
// TODO Find appropriate HTTP message here, no code relies on this.
res.getWriter().println("There is nothing to be downloaded.");
}
}
|
diff --git a/src/rajawali/renderer/RajawaliRenderer.java b/src/rajawali/renderer/RajawaliRenderer.java
index e441fd53..8abfbfdf 100644
--- a/src/rajawali/renderer/RajawaliRenderer.java
+++ b/src/rajawali/renderer/RajawaliRenderer.java
@@ -1,1324 +1,1324 @@
package rajawali.renderer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.opengles.GL10;
import rajawali.BaseObject3D;
import rajawali.Camera;
import rajawali.Capabilities;
import rajawali.animation.Animation3D;
import rajawali.effects.APass;
import rajawali.effects.EffectComposer;
import rajawali.materials.AMaterial;
import rajawali.materials.MaterialManager;
import rajawali.materials.textures.ATexture;
import rajawali.materials.textures.TextureManager;
import rajawali.math.vector.Vector3;
import rajawali.renderer.plugins.Plugin;
import rajawali.scene.RajawaliScene;
import rajawali.util.FPSUpdateListener;
import rajawali.util.ObjectColorPicker;
import rajawali.util.RajLog;
import rajawali.visitors.INode;
import rajawali.visitors.INodeVisitor;
import android.content.Context;
import android.content.SharedPreferences;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.Matrix;
import android.os.SystemClock;
import android.service.wallpaper.WallpaperService;
import android.view.MotionEvent;
import android.view.WindowManager;
public class RajawaliRenderer implements GLSurfaceView.Renderer, INode {
protected final int GL_COVERAGE_BUFFER_BIT_NV = 0x8000;
protected Context mContext; //Context the renderer is running in
protected SharedPreferences preferences; //Shared preferences for this app
protected int mViewportWidth, mViewportHeight; //Height and width of GL viewport
protected WallpaperService.Engine mWallpaperEngine; //Concrete wallpaper instance
protected GLSurfaceView mSurfaceView; //The rendering surface
protected TextureManager mTextureManager; //Texture manager for ALL textures across ALL scenes.
protected MaterialManager mMaterialManager; //Material manager for ALL materials across ALL scenes.
protected ScheduledExecutorService mTimer; //Timer used to schedule drawing
protected float mFrameRate; //Target frame rate to render at
protected int mFrameCount; //Used for determining FPS
private long mStartTime = System.nanoTime(); //Used for determining FPS
protected double mLastMeasuredFPS; //Last measured FPS value
protected FPSUpdateListener mFPSUpdateListener; //Listener to notify of new FPS values.
private long mLastRender; //Time of last rendering. Used for animation delta time
protected float[] mVMatrix = new float[16]; //The OpenGL view matrix
protected float[] mPMatrix = new float[16]; //The OpenGL projection matrix
protected boolean mEnableDepthBuffer = true; //Do we use the depth buffer?
protected static boolean mFogEnabled; //Is camera fog enabled?
protected static int mMaxLights = 1; //How many lights max?
protected int mLastReportedGLError = 0; // Keep track of the last reported OpenGL error
//In case we cannot parse the version number, assume OpenGL ES 2.0
protected int mGLES_Major_Version = 2; //The GL ES major version of the surface
protected int mGLES_Minor_Version = 0; //The GL ES minor version of the surface
/**
* Scene caching stores all textures and relevant OpenGL-specific
* data. This is used when the OpenGL context needs to be restored.
* The context typically needs to be restored when the application
* is re-activated or when a live wallpaper is rotated.
*/
private boolean mSceneCachingEnabled; //This applies to all scenes
protected boolean mSceneInitialized; //This applies to all scenes
public static boolean supportsUIntBuffers = false;
/**
* Frame task queue. Adding, removing or replacing scenes is prohibited
* outside the use of this queue. The render thread will automatically
* handle the necessary operations at an appropriate time, ensuring
* thread safety and general correct operation.
*
* Guarded by {@link #mSceneQueue}
*/
private LinkedList<AFrameTask> mSceneQueue;
private List<RajawaliScene> mScenes; //List of all scenes this renderer is aware of.
/**
* The scene currently being displayed.
*
* Guarded by {@link #mNextSceneLock}
*/
private RajawaliScene mCurrentScene;
private RajawaliScene mNextScene; //The scene which the renderer should switch to on the next frame.
private final Object mNextSceneLock = new Object(); //Scene switching lock
/**
* Effect composer for post processing. If the effect composer is empty,
* RajawaliRenderer will render the scene normally to screen. If there are
* {@link APass} instances in the composer list, it will skip rendering the
* current scene and call render on the effect composer instead which will
* handle scene render passes of its own.
*/
protected EffectComposer mEffectComposer;
public RajawaliRenderer(Context context) {
RajLog.i("Rajawali | Anchor Steam | Dev Branch");
RajLog.i("THIS IS A DEV BRANCH CONTAINING SIGNIFICANT CHANGES. PLEASE REFER TO CHANGELOG.md FOR MORE INFORMATION.");
AMaterial.setLoaderContext(context);
mContext = context;
mFrameRate = getRefreshRate();
mScenes = Collections.synchronizedList(new CopyOnWriteArrayList<RajawaliScene>());
mSceneQueue = new LinkedList<AFrameTask>();
mSceneCachingEnabled = true;
mSceneInitialized = false;
RajawaliScene defaultScene = new RajawaliScene(this);
mScenes.add(defaultScene);
mCurrentScene = defaultScene;
}
/**
* Switches the {@link RajawaliScene} currently being displayed.
*
* @param scene {@link RajawaliScene} object to display.
*/
public void switchScene(RajawaliScene scene) {
synchronized (mNextSceneLock) {
mNextScene = scene;
}
}
/**
* Switches the {@link RajawaliScene} currently being displayed.
*
* @param scene Index of the {@link RajawaliScene} to use.
*/
public void switchScene(int scene) {
switchScene(mScenes.get(scene));
}
/**
* Fetches the {@link RajawaliScene} currently being being displayed.
* Note that the scene is not thread safe so this should be used
* with extreme caution.
*
* @return {@link RajawaliScene} object currently used for the scene.
* @see {@link RajawaliRenderer#mCurrentScene}
*/
public RajawaliScene getCurrentScene() {
return mCurrentScene;
}
/**
* Fetches the specified scene.
*
* @param scene Index of the {@link RajawaliScene} to fetch.
* @return {@link RajawaliScene} which was retrieved.
*/
public RajawaliScene getScene(int scene) {
return mScenes.get(scene);
}
/**
* Replaces a {@link RajawaliScene} in the renderer at the specified location
* in the list. This does not validate the index, so if it is not
* contained in the list already, an exception will be thrown.
*
* If the {@link RajawaliScene} being replaced is
* the one in current use, the replacement will be selected on the next
* frame.
*
* @param scene {@link RajawaliScene} object to add.
* @param location Integer index of the {@link RajawaliScene} to replace.
* @return boolean True if the replace task was successfully queued.
*/
public boolean replaceScene(RajawaliScene scene, int location) {
return queueReplaceTask(location, scene);
}
/**
* Replaces the specified {@link RajawaliScene} in the renderer with the
* new one. If the {@link RajawaliScene} being replaced is
* the one in current use, the replacement will be selected on the next
* frame.
*
* @param oldScene {@link RajawaliScene} object to be replaced.
* @param newScene {@link RajawaliScene} which will replace the old.
* @return boolean True if the replace task was successfully queued.
*/
public boolean replaceScene(RajawaliScene oldScene, RajawaliScene newScene) {
return queueReplaceTask(oldScene, newScene);
}
/**
* Adds a {@link RajawaliScene} to the renderer.
*
* @param scene {@link RajawaliScene} object to add.
* @return boolean True if this addition was successfully queued.
*/
public boolean addScene(RajawaliScene scene) {
return queueAddTask(scene);
}
/**
* Adds a {@link Collection} of scenes to the renderer.
*
* @param scenes {@link Collection} of scenes to be added.
* @return boolean True if the addition was successfully queued.
*/
public boolean addScenes(Collection<RajawaliScene> scenes) {
ArrayList<AFrameTask> tasks = new ArrayList<AFrameTask>(scenes);
return queueAddAllTask(tasks);
}
/**
* Removes a {@link RajawaliScene} from the renderer. If the {@link RajawaliScene}
* being removed is the one in current use, the 0 index {@link RajawaliScene}
* will be selected on the next frame.
*
* @param scene {@link RajawaliScene} object to be removed.
* @return boolean True if the removal was successfully queued.
*/
public boolean removeScene(RajawaliScene scene) {
return queueRemoveTask(scene);
}
/**
* Clears all scenes from the renderer. This should be used with
* extreme care as it will also clear the current scene. If this
* is done while still rendering, bad things will happen.
*/
protected void clearScenes() {
queueClearTask(AFrameTask.TYPE.SCENE);
}
/**
* Adds a {@link RajawaliScene}, switching to it immediately
*
* @param scene The {@link RajawaliScene} to add.
* @return boolean True if the addition task was successfully queued.
*/
public boolean addAndSwitchScene(RajawaliScene scene) {
boolean success = addScene(scene);
switchScene(scene);
return success;
}
/**
* Replaces a {@link RajawaliScene} at the specified index, switching to the
* replacement immediately on the next frame. This does not validate the index.
*
* @param scene The {@link RajawaliScene} to add.
* @param location The index of the scene to replace.
* @return boolean True if the replace task was successfully queued.
*/
public boolean replaceAndSwitchScene(RajawaliScene scene, int location) {
boolean success = replaceScene(scene, location);
switchScene(scene);
return success;
}
/**
* Replaces the specified {@link RajawaliScene} in the renderer with the
* new one, switching to it immediately on the next frame. If the scene to
* replace does not exist, nothing will happen.
*
* @param oldScene {@link RajawaliScene} object to be replaced.
* @param newScene {@link RajawaliScene} which will replace the old.
* @return boolean True if the replace task was successfully queued.
*/
public boolean replaceAndSwitchScene(RajawaliScene oldScene, RajawaliScene newScene) {
boolean success = queueReplaceTask(oldScene, newScene);
switchScene(newScene);
return success;
}
/**
* Register an animation to be managed by the current scene. This is optional
* leaving open the possibility to manage updates on Animations in your own implementation.
*
* @param anim {@link Animation3D} to be registered.
* @return boolean True if the registration was queued successfully.
*/
public boolean registerAnimation(Animation3D anim) {
return mCurrentScene.registerAnimation(anim);
}
/**
* Remove a managed animation. If the animation is not a member of the current scene,
* nothing will happen.
*
* @param anim {@link Animation3D} to be unregistered.
* @return boolean True if the unregister was queued successfully.
*/
public boolean unregisterAnimation(Animation3D anim) {
return mCurrentScene.unregisterAnimation(anim);
}
/**
* Retrieve the current {@link Camera} in use. This is the camera being
* used by the current scene.
*
* @return {@link Camera} currently in use.
*/
public Camera getCurrentCamera() {
return mCurrentScene.getCamera();
}
/**
* Adds a {@link Camera} to the current scene.
*
* @param camera {@link Camera} to add.
* @return boolean True if the addition was queued successfully.
*/
public boolean addCamera(Camera camera) {
return mCurrentScene.addCamera(camera);
}
/**
* Replace a {@link Camera} in the current scene with a new one, switching immediately.
*
* @param oldCamera {@link Camera} the old camera.
* @param newCamera {@link Camera} the new camera.
* @return boolean True if the replacement was queued successfully.
*/
public boolean replaceAndSwitchCamera(Camera oldCamera, Camera newCamera) {
return mCurrentScene.replaceAndSwitchCamera(oldCamera, newCamera);
}
/**
* Replace a {@link Camera} at the specified index in the current scene with a new one,
* switching immediately.
*
* @param camera {@link Camera} the new camera.
* @param index The integer index of the camera to replace.
* @return boolean True if the replacement was queued successfully.
*/
public boolean replaceAndSwitchCamera(Camera camera, int index) {
return mCurrentScene.replaceAndSwitchCamera(camera, index);
}
/**
* Adds a {@link Camera} to the current scene switching
* to it immediately.
*
* @param camera {@link Camera} to add.
* @return boolean True if the addition was queued successfully.
*/
public boolean addAndSwitchCamera(Camera camera) {
return mCurrentScene.addAndSwitchCamera(camera);
}
/**
* Removes a {@link Camera} from the current scene.
* If the camera is not a member of the scene, nothing will happen.
*
* @param camera {@link Camera} to remove.
* @return boolean True if the removal was queued successfully.
*/
public boolean removeCamera(Camera camera) {
return mCurrentScene.removeCamera(camera);
}
/**
* Adds a {@link BaseObject3D} child to the current scene.
*
* @param child {@link BaseObject3D} object to be added.
* @return boolean True if the addition was successfully queued.
*/
public boolean addChild(BaseObject3D child) {
return mCurrentScene.addChild(child);
}
/**
* Removes a {@link BaseObject3D} child from the current scene.
* If the child is not a member of the scene, nothing will happen.
*
* @param child {@link BaseObject3D} object to be removed.
* @return boolean True if the removal was successfully queued.
*/
public boolean removeChild(BaseObject3D child) {
return mCurrentScene.removeChild(child);
}
/**
* Adds a {@link Plugin} plugin to the current scene.
*
* @param plugin {@link Plugin} object to be added.
* @return boolean True if the addition was successfully queued.
*/
public boolean addPlugin(Plugin plugin) {
return mCurrentScene.addPlugin(plugin);
}
/**
* Removes a {@link Plugin} child from the current scene.
* If the plugin is not a member of the scene, nothing will happen.
*
* @param plugin {@link Plugin} object to be removed.
* @return boolean True if the removal was successfully queued.
*/
public boolean removePlugin(Plugin plugin) {
return mCurrentScene.removePlugin(plugin);
}
/*
* (non-Javadoc)
* @see android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition.khronos.opengles.GL10)
*/
public void onDrawFrame(GL10 glUnused) {
performFrameTasks(); //Execute any pending frame tasks
synchronized (mNextSceneLock) {
//Check if we need to switch the scene, and if so, do it.
if (mNextScene != null) {
mCurrentScene = mNextScene;
mCurrentScene.resetGLState(); //Ensure that the GL state is what this scene expects
mNextScene = null;
mCurrentScene.getCamera().setProjectionMatrix(mViewportWidth, mViewportHeight);
}
}
render(); //Render the frame
++mFrameCount;
if (mFrameCount % 50 == 0) {
long now = System.nanoTime();
double elapsedS = (now - mStartTime) / 1.0e9;
double msPerFrame = (1000 * elapsedS / mFrameCount);
mLastMeasuredFPS = 1000 / msPerFrame;
mFrameCount = 0;
mStartTime = now;
if(mFPSUpdateListener != null)
mFPSUpdateListener.onFPSUpdate(mLastMeasuredFPS); //Update the FPS listener
}
int error = glUnused.glGetError();
if(error > 0)
{
if(error != mLastReportedGLError)
{
RajLog.e("OpenGL Error: " + GLU.gluErrorString(error) + " " + this.hashCode());
mLastReportedGLError = error;
}
} else {
mLastReportedGLError = 0;
}
}
/**
* Called by {@link #onDrawFrame(GL10)} to render the next frame.
*/
private void render() {
final double deltaTime = (SystemClock.elapsedRealtime() - mLastRender) / 1000d;
mLastRender = SystemClock.elapsedRealtime();
mCurrentScene.render(deltaTime, null);
}
public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset) {
}
public void onTouchEvent(MotionEvent event) {
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
mViewportWidth = width;
mViewportHeight = height;
mCurrentScene.updateProjectionMatrix(width, height);
GLES20.glViewport(0, 0, width, height);
}
/* Called when the OpenGL context is created or re-created. Don't set up your scene here,
* use initScene() for that.
*
* @see rajawali.renderer.RajawaliRenderer#initScene
* @see android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition.khronos.opengles.GL10, javax.microedition.khronos.egl.EGLConfig)
*
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
RajLog.setGL10(gl);
Capabilities.getInstance();
String[] versionString = (gl.glGetString(GL10.GL_VERSION)).split(" ");
if (versionString.length >= 3) {
- String[] versionParts = versionString[2].split(".");
- if (versionParts.length == 2) {
+ String[] versionParts = versionString[2].split("\\.");
+ if (versionParts.length >= 2) {
mGLES_Major_Version = Integer.parseInt(versionParts[0]);
mGLES_Minor_Version = Integer.parseInt(versionParts[1]);
}
}
supportsUIntBuffers = gl.glGetString(GL10.GL_EXTENSIONS).indexOf("GL_OES_element_index_uint") > -1;
//GLES20.glFrontFace(GLES20.GL_CCW);
//GLES20.glCullFace(GLES20.GL_BACK);
if (!mSceneInitialized) {
mEffectComposer = new EffectComposer(this);
mTextureManager = TextureManager.getInstance();
mTextureManager.setContext(this.getContext());
mTextureManager.registerRenderer(this);
mMaterialManager = MaterialManager.getInstance();
mMaterialManager.setContext(this.getContext());
mMaterialManager.registerRenderer(this);
getCurrentScene().resetGLState();
initScene();
}
if (!mSceneCachingEnabled) {
mTextureManager.reset();
mMaterialManager.reset();
clearScenes();
} else if(mSceneCachingEnabled && mSceneInitialized) {
mTextureManager.taskReload();
mMaterialManager.taskReload();
reloadScenes();
}
mSceneInitialized = true;
startRendering();
}
/**
* Called to reload the scenes.
*/
protected void reloadScenes() {
synchronized (mScenes) {
for (int i = 0, j = mScenes.size(); i < j; ++i) {
mScenes.get(i).reload();
}
}
}
/**
* Scene construction should happen here, not in onSurfaceCreated()
*/
protected void initScene() {
}
public void startRendering() {
if(!mSceneInitialized) return;
mLastRender = SystemClock.elapsedRealtime();
if (mTimer != null) {return;}
mTimer = Executors.newScheduledThreadPool(1);
mTimer.scheduleAtFixedRate(new RequestRenderTask(), 0, (long) (1000 / mFrameRate), TimeUnit.MILLISECONDS);
}
/**
* Stop rendering the scene.
*
* @return true if rendering was stopped, false if rendering was already
* stopped (no action taken)
*/
protected boolean stopRendering() {
if (mTimer != null) {
mTimer.shutdownNow();
mTimer = null;
return true;
}
return false;
}
public void onVisibilityChanged(boolean visible) {
if (!visible) {
stopRendering();
} else
getCurrentScene().resetGLState();
startRendering();
}
public void onSurfaceDestroyed() {
synchronized (mScenes) {
mTextureManager.unregisterRenderer(this);
mMaterialManager.unregisterRenderer(this);
if (mTextureManager != null)
mTextureManager.taskReset(this);
if (mMaterialManager != null)
mMaterialManager.taskReset(this);
for (int i = 0, j = mScenes.size(); i < j; ++i)
mScenes.get(i).destroyScene();
}
stopRendering();
}
public void setSharedPreferences(SharedPreferences preferences) {
this.preferences = preferences;
}
private class RequestRenderTask implements Runnable {
public void run() {
if (mSurfaceView != null) {
mSurfaceView.requestRender();
}
}
}
public Vector3 unProject(float x, float y, float z) {
x = mViewportWidth - x;
y = mViewportHeight - y;
float[] m = new float[16], mvpmatrix = new float[16],
in = new float[4],
out = new float[4];
Matrix.multiplyMM(mvpmatrix, 0, mPMatrix, 0, mVMatrix, 0);
Matrix.invertM(m, 0, mvpmatrix, 0);
in[0] = (x / (float)mViewportWidth) * 2 - 1;
in[1] = (y / (float)mViewportHeight) * 2 - 1;
in[2] = 2 * z - 1;
in[3] = 1;
Matrix.multiplyMV(out, 0, m, 0, in, 0);
if (out[3]==0)
return null;
out[3] = 1/out[3];
return new Vector3(out[0] * out[3], out[1] * out[3], out[2] * out[3]);
}
public float getFrameRate() {
return mFrameRate;
}
public void setFrameRate(int frameRate) {
setFrameRate((float)frameRate);
}
public void setFrameRate(float frameRate) {
this.mFrameRate = frameRate;
if (stopRendering()) {
// Restart timer with new frequency
startRendering();
}
}
public float getRefreshRate() {
return ((WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay()
.getRefreshRate();
}
public WallpaperService.Engine getEngine() {
return mWallpaperEngine;
}
public void setEngine(WallpaperService.Engine engine) {
this.mWallpaperEngine = engine;
}
public GLSurfaceView getSurfaceView() {
return mSurfaceView;
}
public void setSurfaceView(GLSurfaceView surfaceView) {
this.mSurfaceView = surfaceView;
}
public Context getContext() {
return mContext;
}
public TextureManager getTextureManager() {
return mTextureManager;
}
/**
* Adds a task to the frame task queue.
*
* @param task AFrameTask to be added.
* @return boolean True on successful addition to queue.
*/
private boolean addTaskToQueue(AFrameTask task) {
synchronized (mSceneQueue) {
return mSceneQueue.offer(task);
}
}
/**
* Internal method for performing frame tasks. Should be called at the
* start of onDrawFrame() prior to render().
*/
private void performFrameTasks() {
synchronized (mSceneQueue) {
//Fetch the first task
AFrameTask taskObject = mSceneQueue.poll();
while (taskObject != null) {
AFrameTask.TASK task = taskObject.getTask();
switch (task) {
case NONE:
//DO NOTHING
return;
case ADD:
handleAddTask(taskObject);
break;
case ADD_ALL:
handleAddAllTask(taskObject);
break;
case REMOVE:
handleRemoveTask(taskObject);
break;
case REMOVE_ALL:
handleRemoveAllTask(taskObject);
break;
case REPLACE:
handleReplaceTask(taskObject);
break;
case RELOAD:
handleReloadTask(taskObject);
break;
case RESET:
handleResetTask(taskObject);
break;
case INITIALIZE:
handleInitializeTask(taskObject);
break;
}
//Retrieve the next task
taskObject = mSceneQueue.poll();
}
}
}
/**
* Internal method for handling replacement tasks.
*
* @param task {@link AFrameTask} object to process.
*/
private void handleReplaceTask(AFrameTask task) {
AFrameTask.TYPE type = task.getFrameTaskType();
switch (type) {
case SCENE:
internalReplaceScene(task, (RajawaliScene) task.getNewObject(), task.getIndex());
break;
case TEXTURE:
internalReplaceTexture((ATexture)task, task.getIndex());
default:
break;
}
}
/**
* Internal method for handling addition tasks.
*
* @param task {@link AFrameTask} object to process.
*/
private void handleAddTask(AFrameTask task) {
AFrameTask.TYPE type = task.getFrameTaskType();
switch (type) {
case SCENE:
internalAddScene((RajawaliScene) task, task.getIndex());
break;
case TEXTURE:
internalAddTexture((ATexture) task, task.getIndex());
break;
case MATERIAL:
internalAddMaterial((AMaterial) task, task.getIndex());
default:
break;
}
}
/**
* Internal method for handling removal tasks.
*
* @param task {@link AFrameTask} object to process.
*/
private void handleRemoveTask(AFrameTask task) {
AFrameTask.TYPE type = task.getFrameTaskType();
switch (type) {
case SCENE:
internalRemoveScene((RajawaliScene) task, task.getIndex());
break;
case TEXTURE:
internalRemoveTexture((ATexture) task, task.getIndex());
break;
case MATERIAL:
internalRemoveMaterial((AMaterial) task, task.getIndex());
break;
default:
break;
}
}
/**
* Internal method for handling add all tasks.
*
* @param task {@link AFrameTask} object to process.
*/
private void handleAddAllTask(AFrameTask task) {
GroupTask group = (GroupTask) task;
AFrameTask[] tasks = (AFrameTask[]) group.getCollection().toArray();
AFrameTask.TYPE type = tasks[0].getFrameTaskType();
int i = 0;
int j = tasks.length;
switch (type) {
case SCENE:
for (i = 0; i < j; ++i) {
internalAddScene((RajawaliScene) tasks[i], AFrameTask.UNUSED_INDEX);
}
break;
default:
break;
}
}
/**
* Internal method for handling add remove all tasks.
*
* @param task {@link AFrameTask} object to process.
*/
private void handleRemoveAllTask(AFrameTask task) {
GroupTask group = (GroupTask) task;
AFrameTask.TYPE type = group.getFrameTaskType();
boolean clear = false;
AFrameTask[] tasks = null;
int i = 0, j = 0;
if (type == null) {
clear = true;
} else {
tasks = (AFrameTask[]) group.getCollection().toArray();
type = tasks[0].getFrameTaskType();
j = tasks.length;
}
switch (type) {
case SCENE:
if (clear) {
internalClearScenes();
} else {
for (i = 0; i < j; ++i) {
internalRemoveScene((RajawaliScene) tasks[i], AFrameTask.UNUSED_INDEX);
}
}
break;
default:
break;
}
}
/**
* Internal method for handling reload tasks.
*
* @param task {@link AFrameTask} object to process.
*/
private void handleReloadTask(AFrameTask task) {
AFrameTask.TYPE type = task.getFrameTaskType();
switch (type) {
case TEXTURE_MANAGER:
internalReloadTextureManager();
case MATERIAL_MANAGER:
internalReloadMaterialManager();
default:
break;
}
}
/**
* Internal method for handling reset tasks.
*
* @param task {@link AFrameTask} object to process.
*/
private void handleResetTask(AFrameTask task) {
AFrameTask.TYPE type = task.getFrameTaskType();
switch (type) {
case TEXTURE_MANAGER:
internalResetTextureManager();
case MATERIAL_MANAGER:
internalResetMaterialManager();
default:
break;
}
}
/**
* Internal method for handling reset tasks.
*
* @param task {@link AFrameTask} object to process.
*/
private void handleInitializeTask(AFrameTask task) {
AFrameTask.TYPE type = task.getFrameTaskType();
switch (type) {
case COLOR_PICKER:
((ObjectColorPicker)task).initialize();
default:
break;
}
}
/**
* Internal method for replacing a {@link RajawaliScene} object. If index is
* {@link AFrameTask.UNUSED_INDEX} then it will be used, otherwise the replace
* object is used. Should only be called through {@link #handleAddTask(AFrameTask)}
*
* @param scene {@link AFrameTask} The old scene.
* @param replace {@link RajawaliScene} The scene replacing the old scene.
* @param index integer index to effect. Set to {@link AFrameTask.UNUSED_INDEX} if not used.
*/
private void internalReplaceScene(AFrameTask scene, RajawaliScene replace, int index) {
if (index != AFrameTask.UNUSED_INDEX) {
mScenes.set(index, replace);
} else {
mScenes.set(mScenes.indexOf(scene), replace);
}
}
/**
* Internal method for replacing a {@link ATexture} object. Should only be
* called through {@link #handleAddTask(AFrameTask)}
*
* @param texture {@link ATexture} The texture to be replaced.
* @param index integer index to effect. Set to {@link AFrameTask.UNUSED_INDEX} if not used.
*/
private void internalReplaceTexture(ATexture textureConfig, int index) {
mTextureManager.taskReplace(textureConfig);
}
/**
* Internal method for adding {@link RajawaliScene} objects.
* Should only be called through {@link #handleAddTask(AFrameTask)}
*
* This takes an index for the addition, but it is pretty
* meaningless.
*
* @param scene {@link RajawaliScene} to add.
* @param int index to add the animation at.
*/
private void internalAddScene(RajawaliScene scene, int index) {
if (index == AFrameTask.UNUSED_INDEX) {
mScenes.add(scene);
} else {
mScenes.add(index, scene);
}
}
/**
* Internal method for adding {@link ATexture} objects.
* Should only be called through {@link #handleAddTask(AFrameTask)}
*
* This takes an index for the addition, but it is pretty
* meaningless.
*
* @param texture {@link ATexture} to add.
* @param int index to add the animation at.
*/
private void internalAddTexture(ATexture textureConfig, int index) {
mTextureManager.taskAdd(textureConfig);
}
/**
* Internal method for adding {@link AMaterial} objects.
* Should only be called through {@link #handleAddTask(AFrameTask)}
*
* This takes an index for the addition, but it is pretty
* meaningless.
*
* @param material {@link AMaterial} to add.
* @param int index to add the animation at.
*/
private void internalAddMaterial(AMaterial material, int index) {
mMaterialManager.taskAdd(material);
}
/**
* Internal method for removing {@link RajawaliScene} objects.
* Should only be called through {@link #handleRemoveTask(AFrameTask)}
*
* This takes an index for the removal.
*
* @param anim {@link RajawaliScene} to remove. If index is used, this is ignored.
* @param index integer index to remove the child at.
*/
private void internalRemoveScene(RajawaliScene scene, int index) {
RajawaliScene removal = scene;
if (index == AFrameTask.UNUSED_INDEX) {
mScenes.remove(scene);
} else {
removal = mScenes.remove(index);
}
if (mCurrentScene.equals(removal)) {
//If the current camera is the one being removed,
//switch to the new 0 index camera.
mCurrentScene = mScenes.get(0);
}
}
private void internalRemoveTexture(ATexture texture, int index)
{
mTextureManager.taskRemove(texture);
}
private void internalRemoveMaterial(AMaterial material, int index)
{
mMaterialManager.taskRemove(material);
}
/**
* Internal method for removing all {@link RajawaliScene} objects.
* Should only be called through {@link #handleRemoveAllTask(AFrameTask)}
*/
private void internalClearScenes() {
mScenes.clear();
mCurrentScene = null;
}
/**
* Internal method for reloading the {@link TextureManager#reload()} texture manager.
* Should only be called through {@link #handleReloadTask(AFrameTask)}
*/
private void internalReloadTextureManager() {
mTextureManager.taskReload();
}
/**
* Internal method for reloading the {@link MaterialManager#reload()} material manager.
* Should only be called through {@link #handleReloadTask(AFrameTask)}
*/
private void internalReloadMaterialManager() {
mMaterialManager.taskReload();
}
/**
* Internal method for resetting the {@link TextureManager#reset()} texture manager.
* Should only be called through {@link #handleReloadTask(AFrameTask)}
*/
private void internalResetTextureManager() {
mTextureManager.taskReset();
}
/**
* Internal method for resetting the {@link MaterialManager#reset()} material manager.
* Should only be called through {@link #handleReloadTask(AFrameTask)}
*/
private void internalResetMaterialManager() {
mMaterialManager.taskReset();
}
/**
* Queue an addition task. The added object will be placed
* at the end of the renderer's list.
*
* @param task {@link AFrameTask} to be added.
* @return boolean True if the task was successfully queued.
*/
public boolean queueAddTask(AFrameTask task) {
task.setTask(AFrameTask.TASK.ADD);
task.setIndex(AFrameTask.UNUSED_INDEX);
return addTaskToQueue(task);
}
/**
* Queue an addition task. The added object will be placed
* at the specified index in the renderer's list, or the end
* if out of range.
*
* @param task {@link AFrameTask} to be added.
* @param index Integer index to place the object at.
* @return boolean True if the task was successfully queued.
*/
public boolean queueAddTask(AFrameTask task, int index) {
task.setTask(AFrameTask.TASK.ADD);
task.setIndex(index);
return addTaskToQueue(task);
}
/**
* Queue a removal task. The removal will occur at the specified
* index, or at the end of the list if out of range.
*
* @param type {@link AFrameTask.TYPE} Which list to remove from.
* @param index Integer index to remove the object at.
* @return boolean True if the task was successfully queued.
*/
public boolean queueRemoveTask(AFrameTask.TYPE type, int index) {
EmptyTask task = new EmptyTask(type);
task.setTask(AFrameTask.TASK.REMOVE);
task.setIndex(index);
return addTaskToQueue(task);
}
/**
* Queue a removal task to remove the specified object.
*
* @param task {@link AFrameTask} to be removed.
* @return boolean True if the task was successfully queued.
*/
public boolean queueRemoveTask(AFrameTask task) {
task.setTask(AFrameTask.TASK.REMOVE);
task.setIndex(AFrameTask.UNUSED_INDEX);
return addTaskToQueue(task);
}
/**
* Queue a replacement task to replace the object at the
* specified index with a new one. Replaces the object at
* the end of the list if index is out of range.
*
* @param index Integer index of the object to replace.
* @param replacement {@link AFrameTask} the object replacing the old.
* @return boolean True if the task was successfully queued.
*/
public boolean queueReplaceTask(int index, AFrameTask replacement) {
EmptyTask task = new EmptyTask(replacement.getFrameTaskType());
task.setTask(AFrameTask.TASK.REPLACE);
task.setIndex(index);
task.setNewObject(replacement);
return addTaskToQueue(task);
}
/**
* Queue a replacement task to replace the specified object with the new one.
*
* @param task {@link AFrameTask} the object to replace.
* @param replacement {@link AFrameTask} the object replacing the old.
* @return boolean True if the task was successfully queued.
*/
public boolean queueReplaceTask(AFrameTask task, AFrameTask replacement) {
task.setTask(AFrameTask.TASK.REPLACE);
task.setIndex(AFrameTask.UNUSED_INDEX);
task.setNewObject(replacement);
return addTaskToQueue(task);
}
/**
* Queue an add all task to add all objects from the given collection.
*
* @param collection {@link Collection} containing all the objects to add.
* @return boolean True if the task was successfully queued.
*/
public boolean queueAddAllTask(Collection<AFrameTask> collection) {
GroupTask task = new GroupTask(collection);
task.setTask(AFrameTask.TASK.ADD_ALL);
task.setIndex(AFrameTask.UNUSED_INDEX);
return addTaskToQueue(task);
}
/**
* Queue a remove all task which will clear the related list.
*
* @param type {@link AFrameTask.TYPE} Which object list to clear (Cameras, BaseObject3D, etc)
* @return boolean True if the task was successfully queued.
*/
public boolean queueClearTask(AFrameTask.TYPE type) {
GroupTask task = new GroupTask(type);
task.setTask(AFrameTask.TASK.REMOVE_ALL);
task.setIndex(AFrameTask.UNUSED_INDEX);
return addTaskToQueue(task);
}
/**
* Queue a reload task. The added object will be reloaded.
*
* @param task {@link AFrameTask} to be reloaded.
* @return boolean True if the task was successfully queued.
*/
public boolean queueReloadTask(AFrameTask task) {
task.setTask(AFrameTask.TASK.RELOAD);
task.setIndex(AFrameTask.UNUSED_INDEX);
return addTaskToQueue(task);
}
/**
* Queue a reset task. The added object will be reset.
*
* @param task {@link AFrameTask} to be reset.
* @return boolean True if the task was successfully queued.
*/
public boolean queueResetTask(AFrameTask task) {
task.setTask(AFrameTask.TASK.RELOAD);
task.setIndex(AFrameTask.UNUSED_INDEX);
return addTaskToQueue(task);
}
/**
* Queue an initialization task. The added object will be initialized.
*
* @param task {@link AFrameTask} to be added.
* @return boolean True if the task was successfully queued.
*/
public boolean queueInitializeTask(AFrameTask task) {
task.setTask(AFrameTask.TASK.INITIALIZE);
task.setIndex(AFrameTask.UNUSED_INDEX);
return addTaskToQueue(task);
}
public void accept(INodeVisitor visitor) { //TODO: Handle
visitor.apply(this);
//for (int i = 0; i < mChildren.size(); i++)
// mChildren.get(i).accept(visitor);
}
public int getViewportWidth() {
return mViewportWidth;
}
public int getViewportHeight() {
return mViewportHeight;
}
public static boolean isFogEnabled() {
return mFogEnabled;
}
public void setFogEnabled(boolean enabled) {
mFogEnabled = enabled;
synchronized (mScenes) {
for (int i = 0, j = mScenes.size(); i < j; ++i) {
List<Camera> cams = mScenes.get(i).getCamerasCopy();
for (int n = 0, k = cams.size(); n < k; ++n) {
cams.get(n).setFogEnabled(enabled);
}
}
}
}
public boolean getSceneInitialized() {
return mSceneInitialized;
}
public void setSceneCachingEnabled(boolean enabled) {
mSceneCachingEnabled = enabled;
}
public boolean getSceneCachingEnabled() {
return mSceneCachingEnabled;
}
public static int getMaxLights() {
return mMaxLights;
}
public static void setMaxLights(int maxLights) {
RajawaliRenderer.mMaxLights = maxLights;
}
public void setFPSUpdateListener(FPSUpdateListener listener) {
mFPSUpdateListener = listener;
}
public static int checkGLError(String message) {
int error = GLES20.glGetError();
if(error != GLES20.GL_NO_ERROR)
{
StringBuffer sb = new StringBuffer();
if(message != null)
sb.append("[").append(message).append("] ");
sb.append("GLES20 Error: ");
sb.append(GLU.gluErrorString(error));
RajLog.e(sb.toString());
}
return error;
}
/**
* Indicates whether the OpenGL context is still alive or not.
*
* @return
*/
public static boolean hasGLContext()
{
EGL10 egl = (EGL10)EGLContext.getEGL();
EGLContext eglContext = egl.eglGetCurrentContext();
return eglContext != EGL10.EGL_NO_CONTEXT;
}
/**
* Fetches the Open GL ES major version of the EGL surface.
*
* @return int containing the major version number.
*/
public int getGLMajorVersion() {
return mGLES_Major_Version;
}
/**
* Fetches the Open GL ES minor version of the EGL surface.
*
* @return int containing the minor version number.
*/
public int getGLMinorVersion() {
return mGLES_Minor_Version;
}
public void setUsesCoverageAa(boolean usesCoverageAa) {
mCurrentScene.setUsesCoverageAa(usesCoverageAa);
}
public void setUsesCoverageAaAll(boolean usesCoverageAa) {
synchronized (mScenes) {
for (int i = 0, j = mScenes.size(); i < j; ++i) {
mScenes.get(i).setUsesCoverageAa(usesCoverageAa);
}
}
}
}
| true | true | public void onSurfaceCreated(GL10 gl, EGLConfig config) {
RajLog.setGL10(gl);
Capabilities.getInstance();
String[] versionString = (gl.glGetString(GL10.GL_VERSION)).split(" ");
if (versionString.length >= 3) {
String[] versionParts = versionString[2].split(".");
if (versionParts.length == 2) {
mGLES_Major_Version = Integer.parseInt(versionParts[0]);
mGLES_Minor_Version = Integer.parseInt(versionParts[1]);
}
}
supportsUIntBuffers = gl.glGetString(GL10.GL_EXTENSIONS).indexOf("GL_OES_element_index_uint") > -1;
//GLES20.glFrontFace(GLES20.GL_CCW);
//GLES20.glCullFace(GLES20.GL_BACK);
if (!mSceneInitialized) {
mEffectComposer = new EffectComposer(this);
mTextureManager = TextureManager.getInstance();
mTextureManager.setContext(this.getContext());
mTextureManager.registerRenderer(this);
mMaterialManager = MaterialManager.getInstance();
mMaterialManager.setContext(this.getContext());
mMaterialManager.registerRenderer(this);
getCurrentScene().resetGLState();
initScene();
}
if (!mSceneCachingEnabled) {
mTextureManager.reset();
mMaterialManager.reset();
clearScenes();
} else if(mSceneCachingEnabled && mSceneInitialized) {
mTextureManager.taskReload();
mMaterialManager.taskReload();
reloadScenes();
}
mSceneInitialized = true;
startRendering();
}
| public void onSurfaceCreated(GL10 gl, EGLConfig config) {
RajLog.setGL10(gl);
Capabilities.getInstance();
String[] versionString = (gl.glGetString(GL10.GL_VERSION)).split(" ");
if (versionString.length >= 3) {
String[] versionParts = versionString[2].split("\\.");
if (versionParts.length >= 2) {
mGLES_Major_Version = Integer.parseInt(versionParts[0]);
mGLES_Minor_Version = Integer.parseInt(versionParts[1]);
}
}
supportsUIntBuffers = gl.glGetString(GL10.GL_EXTENSIONS).indexOf("GL_OES_element_index_uint") > -1;
//GLES20.glFrontFace(GLES20.GL_CCW);
//GLES20.glCullFace(GLES20.GL_BACK);
if (!mSceneInitialized) {
mEffectComposer = new EffectComposer(this);
mTextureManager = TextureManager.getInstance();
mTextureManager.setContext(this.getContext());
mTextureManager.registerRenderer(this);
mMaterialManager = MaterialManager.getInstance();
mMaterialManager.setContext(this.getContext());
mMaterialManager.registerRenderer(this);
getCurrentScene().resetGLState();
initScene();
}
if (!mSceneCachingEnabled) {
mTextureManager.reset();
mMaterialManager.reset();
clearScenes();
} else if(mSceneCachingEnabled && mSceneInitialized) {
mTextureManager.taskReload();
mMaterialManager.taskReload();
reloadScenes();
}
mSceneInitialized = true;
startRendering();
}
|
diff --git a/src/android/org/pgsqlite/SQLitePlugin.java b/src/android/org/pgsqlite/SQLitePlugin.java
index ce3db48..ea7da32 100755
--- a/src/android/org/pgsqlite/SQLitePlugin.java
+++ b/src/android/org/pgsqlite/SQLitePlugin.java
@@ -1,547 +1,543 @@
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010, IBM Corporation
*/
package org.pgsqlite;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.lang.Number;
import java.util.HashMap;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.CallbackContext;
import org.sqlg.SQLiteGlue;
import android.util.Base64;
import android.util.Log;
public class SQLitePlugin extends CordovaPlugin
{
/**
* Multiple database map (static).
*/
static HashMap<String, Long> dbmap = new HashMap<String, Long>();
static {
System.loadLibrary("sqlg");
}
/**
* Get a SQLiteGlue database reference from the db map (public static accessor).
*
* @param dbname
* The name of the database.
*
*/
public static long getSQLiteGlueDatabase(String dbname)
{
return dbmap.get(dbname);
}
/**
* NOTE: Using default constructor, explicit constructor no longer required.
*/
/**
* Executes the request and returns PluginResult.
*
* @param action
* The action to execute.
*
* @param args
* JSONArry of arguments for the plugin.
*
* @param cbc
* Callback context from Cordova API
*
*/
@Override
public boolean execute(String action, JSONArray args, CallbackContext cbc)
{
try {
if (action.equals("open")) {
JSONObject o = args.getJSONObject(0);
String dbname = o.getString("name");
return this.openDatabase(dbname, null);
}
else if (action.equals("close")) {
this.closeDatabase(args.getString(0));
}
/**
else if (action.equals("executePragmaStatement"))
{
String dbName = args.getString(0);
String query = args.getString(1);
JSONArray jparams = (args.length() < 3) ? null : args.getJSONArray(2);
String[] params = null;
if (jparams != null) {
params = new String[jparams.length()];
for (int j = 0; j < jparams.length(); j++) {
if (jparams.isNull(j))
params[j] = "";
else
params[j] = jparams.getString(j);
}
}
Cursor myCursor = this.getDatabase(dbName).rawQuery(query, params);
String result = this.getRowsResultFromQuery(myCursor).getJSONArray("rows").toString();
this.sendJavascriptCB("window.SQLitePluginCallback.p1('" + id + "', " + result + ");");
}
**/
else if (action.equals("executeSqlBatch") || action.equals("executeBatchTransaction") || action.equals("backgroundExecuteSqlBatch"))
{
String[] queries = null;
String[] queryIDs = null;
JSONArray jsonArr = null;
int paramLen = 0;
JSONArray[] jsonparams = null;
JSONObject allargs = args.getJSONObject(0);
JSONObject dbargs = allargs.getJSONObject("dbargs");
String dbName = dbargs.getString("dbname");
JSONArray txargs = allargs.getJSONArray("executes");
if (txargs.isNull(0)) {
queries = new String[0];
} else {
int len = txargs.length();
queries = new String[len];
queryIDs = new String[len];
jsonparams = new JSONArray[len];
for (int i = 0; i < len; i++)
{
JSONObject a = txargs.getJSONObject(i);
queries[i] = a.getString("sql");
queryIDs[i] = a.getString("qid");
jsonArr = a.getJSONArray("params");
paramLen = jsonArr.length();
jsonparams[i] = jsonArr;
}
}
boolean ex = action.equals("executeBatchTransaction");
if (action.equals("backgroundExecuteSqlBatch"))
this.executeSqlBatchInBackground(dbName, queries, jsonparams, queryIDs, cbc);
else
this.executeSqlBatch(dbName, queries, jsonparams, queryIDs, cbc);
}
return true;
} catch (JSONException e) {
// TODO: signal JSON problem to JS
return false;
}
}
/**
*
* Clean up and close all open databases.
*
*/
@Override
public void onDestroy() {
while (!dbmap.isEmpty()) {
String dbname = dbmap.keySet().iterator().next();
this.closeDatabase(dbname);
dbmap.remove(dbname);
}
}
// --------------------------------------------------------------------------
// LOCAL METHODS
// --------------------------------------------------------------------------
/**
* Open a database.
*
* @param dbname
* The name of the database-NOT including its extension.
*
* @param password
* The database password or null.
*
*/
private boolean openDatabase(String dbname, String password) //throws SQLiteException
{
if (this.getDatabase(dbname) != null) this.closeDatabase(dbname);
String dbfilepath = this.cordova.getActivity().getDatabasePath(dbname + ".db").getAbsolutePath();
Log.v("info", "Open dbfilepath: " + dbfilepath);
long mydb = SQLiteGlue.sqlg_db_open(dbfilepath, SQLiteGlue.SQLG_OPEN_READWRITE | SQLiteGlue.SQLG_OPEN_CREATE);
if (mydb < 0) return false;
dbmap.put(dbname, mydb);
return true;
}
/**
* Close a database.
*
* @param dbName
* The name of the database-NOT including its extension.
*
*/
private void closeDatabase(String dbName)
{
Long mydb = this.getDatabase(dbName);
if (mydb != null)
{
SQLiteGlue.sqlg_db_close(mydb.longValue());
dbmap.remove(dbName);
}
}
/**
* Get a database from the db map.
*
* @param dbname
* The name of the database.
*
*/
private Long getDatabase(String dbname)
{
return dbmap.get(dbname);
}
/**
* Executes a batch request IN BACKGROUND THREAD and sends the results via sendJavascriptCB().
*
* @param dbName
* The name of the database.
*
* @param queryarr
* Array of query strings
*
* @param jsonparams
* Array of JSON query parameters
*
* @param queryIDs
* Array of query ids
*
* @param cbc
* Callback context from Cordova API
*
*/
private void executeSqlBatchInBackground(final String dbName,
final String[] queryarr, final JSONArray[] jsonparams, final String[] queryIDs, final CallbackContext cbc)
{
final SQLitePlugin myself = this;
this.cordova.getThreadPool().execute(new Runnable() {
public void run() {
synchronized(myself) {
myself.executeSqlBatch(dbName, queryarr, jsonparams, queryIDs, cbc);
}
}
});
}
/**
* Executes a batch request and sends the results via sendJavascriptCB().
*
* @param dbname
* The name of the database.
*
* @param queryarr
* Array of query strings
*
* @param jsonparams
* Array of JSON query parameters
*
* @param queryIDs
* Array of query ids
*
* @param cbc
* Callback context from Cordova API
*
*/
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs, CallbackContext cbc)
{
Long db = this.getDatabase(dbname);
if (db == null) return;
long mydb = db.longValue();
String query = "";
String query_id = "";
int len = queryarr.length;
JSONArray batchResults = new JSONArray();
for (int i = 0; i < len; i++) {
query_id = queryIDs[i];
JSONObject queryResult = null;
String errorMessage = null;
int errorCode = 0;
try {
query = queryarr[i];
int step_return = 0;
// XXX TODO bindings for UPDATE & rowsAffected for UPDATE/DELETE/INSERT
/**
// /* OPTIONAL changes for new Android SDK from HERE:
if (android.os.Build.VERSION.SDK_INT >= 11 &&
(query.toLowerCase().startsWith("update") ||
query.toLowerCase().startsWith("delete")))
{
//SQLiteStatement myStatement = mydb.compileStatement(query);
SQLiteStatement myStatement = mydb.prepare(query);
if (jsonparams != null) {
for (int j = 0; j < jsonparams[i].length(); j++) {
if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double ) {
myStatement.bind(j + 1, jsonparams[i].getDouble(j));
} else if (jsonparams[i].get(j) instanceof Number) {
myStatement.bind(j + 1, jsonparams[i].getLong(j));
} else if (jsonparams[i].isNull(j)) {
myStatement.bindNull(j + 1);
} else {
myStatement.bind(j + 1, jsonparams[i].getString(j));
}
}
}
int rowsAffected = myStatement.executeUpdateDelete();
queryResult = new JSONObject();
queryResult.put("rowsAffected", rowsAffected);
} else // to HERE. */
if (query.toLowerCase().startsWith("insert") && jsonparams != null) {
/* prepare/compile statement: */
long st = SQLiteGlue.sqlg_db_prepare_st(mydb, query);
for (int j = 0; j < jsonparams[i].length(); j++) {
if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double ) {
SQLiteGlue.sqlg_st_bind_double(st, j + 1, jsonparams[i].getDouble(j));
} else if (jsonparams[i].get(j) instanceof Number) {
SQLiteGlue.sqlg_st_bind_int64(st, j + 1, jsonparams[i].getLong(j));
// XXX TODO bind null:
//} else if (jsonparams[i].isNull(j)) {
// myStatement.bindNull(j + 1);
} else {
SQLiteGlue.sqlg_st_bind_text(st, j + 1, jsonparams[i].getString(j));
}
}
step_return = SQLiteGlue.sqlg_st_step(st);
// XXX TODO get insertId
SQLiteGlue.sqlg_st_finish(st);
queryResult = new JSONObject();
// XXX TODO [insertId]:
//queryResult.put("insertId", insertId);
// XXX TODO [fix rowsAffected]:
queryResult.put("rowsAffected", 1);
} else {
long st = SQLiteGlue.sqlg_db_prepare_st(mydb, query);
if (jsonparams != null) {
for (int j = 0; j < jsonparams[i].length(); j++) {
//if (jsonparams[i].isNull(j))
//params[j] = "";
//myStatement.bindNull(j + 1);
//else
//params[j] = jsonparams[i].getString(j);
//myStatement.bind(j + 1, jsonparams[i].getString(j));
SQLiteGlue.sqlg_st_bind_text(st, j + 1, jsonparams[i].getString(j));
}
}
step_return = SQLiteGlue.sqlg_st_step(st);
if ((step_return == 100) && query_id.length() > 0)
{
queryResult = this.getRowsResultFromQuery(st);
}
else if (query_id.length() > 0) {
queryResult = new JSONObject();
}
//SQLiteGlue.sqlg_st_finish(st);
}
// XXX TBD ?? cleanup:
if (step_return != 0 && step_return < 100) {
queryResult = null;
errorMessage = "query failure";
+ // XXX TBD add mapping:
+ errorCode = 0; /* UNKNOWN_ERR */
}
- } catch (SQLiteConstraintException ex) {
- ex.printStackTrace();
- errorMessage = ex.getMessage();
- errorCode = 6; /* CONSTRAINT_ERR */
- Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage);
- // XXX TBD other SQLite exceptions to map...
} catch (Exception ex) {
ex.printStackTrace();
errorMessage = ex.getMessage();
errorCode = 0; /* UNKNOWN_ERR */
Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage);
}
try {
if (queryResult != null) {
JSONObject r = new JSONObject();
r.put("qid", query_id);
r.put("result", queryResult);
batchResults.put(r);
} else if (errorMessage != null) {
JSONObject r = new JSONObject();
r.put("qid", query_id);
JSONObject e = new JSONObject();
e.put("message", errorMessage);
e.put("code", errorCode);
r.put("error", e);
batchResults.put(r);
}
} catch (JSONException ex) {
ex.printStackTrace();
Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + ex.getMessage());
// TODO what to do?
}
}
cbc.success(batchResults);
}
/**
* Get rows results from query [TBD XXX].
*
* @param cur
* [TBD XXX] Cursor into query results
*
* @return results in [TBD XXX] form
*
*/
private JSONObject getRowsResultFromQuery(long st)
{
JSONObject rowsResult = new JSONObject();
// If query result has rows
//if (cur.moveToFirst())
{
JSONArray rowsArrayResult = new JSONArray();
String key = "";
int colCount = SQLiteGlue.sqlg_st_column_count(st);
// Build up JSON result object for each row
do {
JSONObject row = new JSONObject();
try {
for (int i = 0; i < colCount; ++i) {
key = SQLiteGlue.sqlg_st_column_name(st, i);
/* // for old Android SDK remove lines from HERE:
if(android.os.Build.VERSION.SDK_INT >= 11)
{
switch(cur.getType (i))
{
case Cursor.FIELD_TYPE_NULL:
row.put(key, JSONObject.NULL);
break;
case Cursor.FIELD_TYPE_INTEGER:
row.put(key, cur.getInt(i));
break;
case Cursor.FIELD_TYPE_FLOAT:
row.put(key, cur.getFloat(i));
break;
case Cursor.FIELD_TYPE_STRING:
row.put(key, cur.getString(i));
break;
case Cursor.FIELD_TYPE_BLOB:
row.put(key, new String(Base64.encode(cur.getBlob(i), Base64.DEFAULT)));
break;
}
}
else // to HERE.*/
{
row.put(key, SQLiteGlue.sqlg_st_column_text(st, i));
}
}
rowsArrayResult.put(row);
} catch (JSONException e) {
e.printStackTrace();
}
} while (SQLiteGlue.sqlg_st_step(st) == 100); /* SQLITE_ROW */
try {
rowsResult.put("rows", rowsArrayResult);
} catch (JSONException e) {
e.printStackTrace();
}
}
return rowsResult;
}
/**
* Send Javascript callback.
*
* @param cb
* Javascript callback command to send
*
*/
private void sendJavascriptCB(String cb)
{
this.webView.sendJavascript(cb);
}
/**
* Send Javascript callback on GUI thread.
*
* @param cb
* Javascript callback command to send
*
*/
private void sendJavascriptToGuiThread(final String cb)
{
final SQLitePlugin myself = this;
this.cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
myself.webView.sendJavascript(cb);
}
});
}
}
| false | true | private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs, CallbackContext cbc)
{
Long db = this.getDatabase(dbname);
if (db == null) return;
long mydb = db.longValue();
String query = "";
String query_id = "";
int len = queryarr.length;
JSONArray batchResults = new JSONArray();
for (int i = 0; i < len; i++) {
query_id = queryIDs[i];
JSONObject queryResult = null;
String errorMessage = null;
int errorCode = 0;
try {
query = queryarr[i];
int step_return = 0;
// XXX TODO bindings for UPDATE & rowsAffected for UPDATE/DELETE/INSERT
/**
// /* OPTIONAL changes for new Android SDK from HERE:
if (android.os.Build.VERSION.SDK_INT >= 11 &&
(query.toLowerCase().startsWith("update") ||
query.toLowerCase().startsWith("delete")))
{
//SQLiteStatement myStatement = mydb.compileStatement(query);
SQLiteStatement myStatement = mydb.prepare(query);
if (jsonparams != null) {
for (int j = 0; j < jsonparams[i].length(); j++) {
if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double ) {
myStatement.bind(j + 1, jsonparams[i].getDouble(j));
} else if (jsonparams[i].get(j) instanceof Number) {
myStatement.bind(j + 1, jsonparams[i].getLong(j));
} else if (jsonparams[i].isNull(j)) {
myStatement.bindNull(j + 1);
} else {
myStatement.bind(j + 1, jsonparams[i].getString(j));
}
}
}
int rowsAffected = myStatement.executeUpdateDelete();
queryResult = new JSONObject();
queryResult.put("rowsAffected", rowsAffected);
} else // to HERE. */
if (query.toLowerCase().startsWith("insert") && jsonparams != null) {
/* prepare/compile statement: */
long st = SQLiteGlue.sqlg_db_prepare_st(mydb, query);
for (int j = 0; j < jsonparams[i].length(); j++) {
if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double ) {
SQLiteGlue.sqlg_st_bind_double(st, j + 1, jsonparams[i].getDouble(j));
} else if (jsonparams[i].get(j) instanceof Number) {
SQLiteGlue.sqlg_st_bind_int64(st, j + 1, jsonparams[i].getLong(j));
// XXX TODO bind null:
//} else if (jsonparams[i].isNull(j)) {
// myStatement.bindNull(j + 1);
} else {
SQLiteGlue.sqlg_st_bind_text(st, j + 1, jsonparams[i].getString(j));
}
}
step_return = SQLiteGlue.sqlg_st_step(st);
// XXX TODO get insertId
SQLiteGlue.sqlg_st_finish(st);
queryResult = new JSONObject();
// XXX TODO [insertId]:
//queryResult.put("insertId", insertId);
// XXX TODO [fix rowsAffected]:
queryResult.put("rowsAffected", 1);
} else {
long st = SQLiteGlue.sqlg_db_prepare_st(mydb, query);
if (jsonparams != null) {
for (int j = 0; j < jsonparams[i].length(); j++) {
//if (jsonparams[i].isNull(j))
//params[j] = "";
//myStatement.bindNull(j + 1);
//else
//params[j] = jsonparams[i].getString(j);
//myStatement.bind(j + 1, jsonparams[i].getString(j));
SQLiteGlue.sqlg_st_bind_text(st, j + 1, jsonparams[i].getString(j));
}
}
step_return = SQLiteGlue.sqlg_st_step(st);
if ((step_return == 100) && query_id.length() > 0)
{
queryResult = this.getRowsResultFromQuery(st);
}
else if (query_id.length() > 0) {
queryResult = new JSONObject();
}
//SQLiteGlue.sqlg_st_finish(st);
}
// XXX TBD ?? cleanup:
if (step_return != 0 && step_return < 100) {
queryResult = null;
errorMessage = "query failure";
}
} catch (SQLiteConstraintException ex) {
ex.printStackTrace();
errorMessage = ex.getMessage();
errorCode = 6; /* CONSTRAINT_ERR */
Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage);
// XXX TBD other SQLite exceptions to map...
} catch (Exception ex) {
ex.printStackTrace();
errorMessage = ex.getMessage();
errorCode = 0; /* UNKNOWN_ERR */
Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage);
}
try {
if (queryResult != null) {
JSONObject r = new JSONObject();
r.put("qid", query_id);
r.put("result", queryResult);
batchResults.put(r);
} else if (errorMessage != null) {
JSONObject r = new JSONObject();
r.put("qid", query_id);
JSONObject e = new JSONObject();
e.put("message", errorMessage);
e.put("code", errorCode);
r.put("error", e);
batchResults.put(r);
}
} catch (JSONException ex) {
ex.printStackTrace();
Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + ex.getMessage());
// TODO what to do?
}
}
cbc.success(batchResults);
}
| private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs, CallbackContext cbc)
{
Long db = this.getDatabase(dbname);
if (db == null) return;
long mydb = db.longValue();
String query = "";
String query_id = "";
int len = queryarr.length;
JSONArray batchResults = new JSONArray();
for (int i = 0; i < len; i++) {
query_id = queryIDs[i];
JSONObject queryResult = null;
String errorMessage = null;
int errorCode = 0;
try {
query = queryarr[i];
int step_return = 0;
// XXX TODO bindings for UPDATE & rowsAffected for UPDATE/DELETE/INSERT
/**
// /* OPTIONAL changes for new Android SDK from HERE:
if (android.os.Build.VERSION.SDK_INT >= 11 &&
(query.toLowerCase().startsWith("update") ||
query.toLowerCase().startsWith("delete")))
{
//SQLiteStatement myStatement = mydb.compileStatement(query);
SQLiteStatement myStatement = mydb.prepare(query);
if (jsonparams != null) {
for (int j = 0; j < jsonparams[i].length(); j++) {
if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double ) {
myStatement.bind(j + 1, jsonparams[i].getDouble(j));
} else if (jsonparams[i].get(j) instanceof Number) {
myStatement.bind(j + 1, jsonparams[i].getLong(j));
} else if (jsonparams[i].isNull(j)) {
myStatement.bindNull(j + 1);
} else {
myStatement.bind(j + 1, jsonparams[i].getString(j));
}
}
}
int rowsAffected = myStatement.executeUpdateDelete();
queryResult = new JSONObject();
queryResult.put("rowsAffected", rowsAffected);
} else // to HERE. */
if (query.toLowerCase().startsWith("insert") && jsonparams != null) {
/* prepare/compile statement: */
long st = SQLiteGlue.sqlg_db_prepare_st(mydb, query);
for (int j = 0; j < jsonparams[i].length(); j++) {
if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double ) {
SQLiteGlue.sqlg_st_bind_double(st, j + 1, jsonparams[i].getDouble(j));
} else if (jsonparams[i].get(j) instanceof Number) {
SQLiteGlue.sqlg_st_bind_int64(st, j + 1, jsonparams[i].getLong(j));
// XXX TODO bind null:
//} else if (jsonparams[i].isNull(j)) {
// myStatement.bindNull(j + 1);
} else {
SQLiteGlue.sqlg_st_bind_text(st, j + 1, jsonparams[i].getString(j));
}
}
step_return = SQLiteGlue.sqlg_st_step(st);
// XXX TODO get insertId
SQLiteGlue.sqlg_st_finish(st);
queryResult = new JSONObject();
// XXX TODO [insertId]:
//queryResult.put("insertId", insertId);
// XXX TODO [fix rowsAffected]:
queryResult.put("rowsAffected", 1);
} else {
long st = SQLiteGlue.sqlg_db_prepare_st(mydb, query);
if (jsonparams != null) {
for (int j = 0; j < jsonparams[i].length(); j++) {
//if (jsonparams[i].isNull(j))
//params[j] = "";
//myStatement.bindNull(j + 1);
//else
//params[j] = jsonparams[i].getString(j);
//myStatement.bind(j + 1, jsonparams[i].getString(j));
SQLiteGlue.sqlg_st_bind_text(st, j + 1, jsonparams[i].getString(j));
}
}
step_return = SQLiteGlue.sqlg_st_step(st);
if ((step_return == 100) && query_id.length() > 0)
{
queryResult = this.getRowsResultFromQuery(st);
}
else if (query_id.length() > 0) {
queryResult = new JSONObject();
}
//SQLiteGlue.sqlg_st_finish(st);
}
// XXX TBD ?? cleanup:
if (step_return != 0 && step_return < 100) {
queryResult = null;
errorMessage = "query failure";
// XXX TBD add mapping:
errorCode = 0; /* UNKNOWN_ERR */
}
} catch (Exception ex) {
ex.printStackTrace();
errorMessage = ex.getMessage();
errorCode = 0; /* UNKNOWN_ERR */
Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage);
}
try {
if (queryResult != null) {
JSONObject r = new JSONObject();
r.put("qid", query_id);
r.put("result", queryResult);
batchResults.put(r);
} else if (errorMessage != null) {
JSONObject r = new JSONObject();
r.put("qid", query_id);
JSONObject e = new JSONObject();
e.put("message", errorMessage);
e.put("code", errorCode);
r.put("error", e);
batchResults.put(r);
}
} catch (JSONException ex) {
ex.printStackTrace();
Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + ex.getMessage());
// TODO what to do?
}
}
cbc.success(batchResults);
}
|
diff --git a/proxy/src/main/java/org/candlepin/controller/Entitler.java b/proxy/src/main/java/org/candlepin/controller/Entitler.java
index f4b07f16c..98a6690fd 100644
--- a/proxy/src/main/java/org/candlepin/controller/Entitler.java
+++ b/proxy/src/main/java/org/candlepin/controller/Entitler.java
@@ -1,241 +1,241 @@
/**
* Copyright (c) 2009 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.candlepin.controller;
import com.google.inject.Inject;
import org.apache.log4j.Logger;
import org.candlepin.audit.Event;
import org.candlepin.audit.EventFactory;
import org.candlepin.audit.EventSink;
import org.candlepin.exceptions.BadRequestException;
import org.candlepin.exceptions.ForbiddenException;
import org.candlepin.model.Consumer;
import org.candlepin.model.ConsumerCurator;
import org.candlepin.model.Entitlement;
import org.candlepin.model.Owner;
import org.candlepin.model.Pool;
import org.candlepin.model.PoolQuantity;
import org.candlepin.policy.EntitlementRefusedException;
import org.xnap.commons.i18n.I18n;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
/**
* entitler
*/
public class Entitler {
private static Logger log = Logger.getLogger(Entitler.class);
private PoolManager poolManager;
private I18n i18n;
private EventFactory evtFactory;
private EventSink sink;
private ConsumerCurator consumerCurator;
@Inject
public Entitler(PoolManager pm, ConsumerCurator cc, I18n i18n,
EventFactory evtFactory, EventSink sink) {
this.poolManager = pm;
this.i18n = i18n;
this.evtFactory = evtFactory;
this.sink = sink;
this.consumerCurator = cc;
}
public List<Entitlement> bindByPool(String poolId, String consumeruuid,
Integer quantity) {
Consumer c = consumerCurator.findByUuid(consumeruuid);
return bindByPool(poolId, c, quantity);
}
public List<Entitlement> bindByPool(String poolId, Consumer consumer,
Integer quantity) {
Pool pool = poolManager.find(poolId);
List<Entitlement> entitlementList = new LinkedList<Entitlement>();
if (log.isDebugEnabled() && pool != null) {
log.debug("pool: id[" + pool.getId() + "], consumed[" +
pool.getConsumed() + "], qty [" + pool.getQuantity() + "]");
}
if (pool == null) {
throw new BadRequestException(i18n.tr(
"Subscription pool {0} does not exist.", poolId));
}
// Attempt to create an entitlement:
entitlementList.add(createEntitlementByPool(consumer, pool, quantity));
return entitlementList;
}
private Entitlement createEntitlementByPool(Consumer consumer, Pool pool,
Integer quantity) {
// Attempt to create an entitlement:
try {
Entitlement e = poolManager.entitleByPool(consumer, pool, quantity);
log.debug("Created entitlement: " + e);
return e;
}
catch (EntitlementRefusedException e) {
// Could be multiple errors, but we'll just report the first one for
// now:
// TODO: multiple checks here for the errors will get ugly, but the
// returned
// string is dependent on the caller (ie pool vs product)
String msg;
String error = e.getResult().getErrors().get(0).getResourceKey();
if (error.equals("rulefailed.consumer.already.has.product")) {
msg = i18n.tr(
"This consumer is already subscribed to the product " +
"matching pool with id ''{0}''.", pool.getId());
}
else if (error.equals("rulefailed.no.entitlements.available")) {
msg = i18n.tr(
- "No free entitlements are available for the pool with " +
+ "No entitlements are available from the pool with " +
"id ''{0}''.", pool.getId());
}
else if (error.equals("rulefailed.consumer.type.mismatch")) {
msg = i18n.tr(
"Consumers of this type are not allowed to subscribe to " +
"the pool with id ''{0}''.", pool.getId());
}
else if (error.equals("rulefailed.pool.does.not.support.multi-entitlement")) {
msg = i18n.tr("Multi-entitlement not supported for pool with id ''{0}''.",
pool.getId());
}
else if (error.equals("virt.guest.host.does.not.match.pool.owner")) {
msg = i18n.tr("Guest''s host does not match owner of pool: ''{0}''.",
pool.getId());
}
else if (error.equals("pool.not.available.to.manifest.consumers")) {
msg = i18n.tr("Pool not available to manifest consumers: ''{0}''.",
pool.getId());
}
else if (error.equals("rulefailed.virt.only")) {
msg = i18n.tr("Pool is restricted to virtual guests: ''{0}''.",
pool.getId());
}
else {
msg = i18n.tr("Unable to entitle consumer to the pool with " +
"id ''{0}''.: {1}", pool.getId().toString(), error);
}
throw new ForbiddenException(msg);
}
}
public List<Entitlement> bindByProducts(String[] productIds,
String consumeruuid, Date entitleDate) {
Consumer c = consumerCurator.findByUuid(consumeruuid);
return bindByProducts(productIds, c, entitleDate);
}
/**
* Entitles the given Consumer to the given Product. Will seek out pools
* which provide access to this product, either directly or as a child, and
* select the best one based on a call to the rules engine.
*
* @param productIds List of product ids.
* @param consumer The consumer being entitled.
* @param entitleDate specific date to entitle by.
* @return List of Entitlements
*/
public List<Entitlement> bindByProducts(String[] productIds,
Consumer consumer, Date entitleDate) {
// Attempt to create entitlements:
try {
List<Entitlement> entitlements = poolManager.entitleByProducts(
consumer, productIds, entitleDate);
log.debug("Created entitlements: " + entitlements);
return entitlements;
}
catch (EntitlementRefusedException e) {
// Could be multiple errors, but we'll just report the first one for
// now:
// TODO: Convert resource key to user friendly string?
// See below for more TODOS
String productId = productIds[0];
String msg;
String error = e.getResult().getErrors().get(0).getResourceKey();
if (error.equals("rulefailed.consumer.already.has.product")) {
msg = i18n.tr("This consumer is already subscribed to the " +
"product ''{0}''", productId);
}
else if (error.equals("rulefailed.no.entitlements.available")) {
msg = i18n.tr("There are not enough free entitlements " +
"available for the product ''{0}''", productId);
}
else if (error.equals("rulefailed.consumer.type.mismatch")) {
msg = i18n.tr("Consumers of this type are not allowed to the " +
"product ''{0}''", productId);
}
else if (error.equals("rulefailed.virt.only")) {
msg = i18n.tr(
"Only virtual systems can consume the product ''{0}''",
productId);
}
else {
msg = i18n.tr(
"Unable to entitle consumer to the product ''{0}'': {1}",
productId, error);
}
throw new ForbiddenException(msg);
}
}
/**
* Entitles the given Consumer to the given Product. Will seek out pools
* which provide access to this product, either directly or as a child, and
* select the best one based on a call to the rules engine.
*
* @param consumer The consumer being entitled.
* @return List of Entitlements
*/
public List<PoolQuantity> getDryRunMap(Consumer consumer,
String serviceLevelOverride) {
try {
Owner owner = consumer.getOwner();
Date entitleDate = new Date();
List<PoolQuantity> map = poolManager.getBestPools(
consumer, null, entitleDate, owner, serviceLevelOverride);
log.debug("Created map: " + map);
return map;
}
catch (EntitlementRefusedException e) {
// Could be multiple errors, but we'll just report the first one for
// now:
// TODO: Convert resource key to user friendly string?
// See below for more TODOS
String error = e.getResult().getErrors().get(0).getResourceKey();
throw new ForbiddenException(error);
}
}
public void sendEvents(List<Entitlement> entitlements) {
if (entitlements != null) {
for (Entitlement e : entitlements) {
Event event = evtFactory.entitlementCreated(e);
sink.sendEvent(event);
}
}
}
}
| true | true | private Entitlement createEntitlementByPool(Consumer consumer, Pool pool,
Integer quantity) {
// Attempt to create an entitlement:
try {
Entitlement e = poolManager.entitleByPool(consumer, pool, quantity);
log.debug("Created entitlement: " + e);
return e;
}
catch (EntitlementRefusedException e) {
// Could be multiple errors, but we'll just report the first one for
// now:
// TODO: multiple checks here for the errors will get ugly, but the
// returned
// string is dependent on the caller (ie pool vs product)
String msg;
String error = e.getResult().getErrors().get(0).getResourceKey();
if (error.equals("rulefailed.consumer.already.has.product")) {
msg = i18n.tr(
"This consumer is already subscribed to the product " +
"matching pool with id ''{0}''.", pool.getId());
}
else if (error.equals("rulefailed.no.entitlements.available")) {
msg = i18n.tr(
"No free entitlements are available for the pool with " +
"id ''{0}''.", pool.getId());
}
else if (error.equals("rulefailed.consumer.type.mismatch")) {
msg = i18n.tr(
"Consumers of this type are not allowed to subscribe to " +
"the pool with id ''{0}''.", pool.getId());
}
else if (error.equals("rulefailed.pool.does.not.support.multi-entitlement")) {
msg = i18n.tr("Multi-entitlement not supported for pool with id ''{0}''.",
pool.getId());
}
else if (error.equals("virt.guest.host.does.not.match.pool.owner")) {
msg = i18n.tr("Guest''s host does not match owner of pool: ''{0}''.",
pool.getId());
}
else if (error.equals("pool.not.available.to.manifest.consumers")) {
msg = i18n.tr("Pool not available to manifest consumers: ''{0}''.",
pool.getId());
}
else if (error.equals("rulefailed.virt.only")) {
msg = i18n.tr("Pool is restricted to virtual guests: ''{0}''.",
pool.getId());
}
else {
msg = i18n.tr("Unable to entitle consumer to the pool with " +
"id ''{0}''.: {1}", pool.getId().toString(), error);
}
throw new ForbiddenException(msg);
}
}
| private Entitlement createEntitlementByPool(Consumer consumer, Pool pool,
Integer quantity) {
// Attempt to create an entitlement:
try {
Entitlement e = poolManager.entitleByPool(consumer, pool, quantity);
log.debug("Created entitlement: " + e);
return e;
}
catch (EntitlementRefusedException e) {
// Could be multiple errors, but we'll just report the first one for
// now:
// TODO: multiple checks here for the errors will get ugly, but the
// returned
// string is dependent on the caller (ie pool vs product)
String msg;
String error = e.getResult().getErrors().get(0).getResourceKey();
if (error.equals("rulefailed.consumer.already.has.product")) {
msg = i18n.tr(
"This consumer is already subscribed to the product " +
"matching pool with id ''{0}''.", pool.getId());
}
else if (error.equals("rulefailed.no.entitlements.available")) {
msg = i18n.tr(
"No entitlements are available from the pool with " +
"id ''{0}''.", pool.getId());
}
else if (error.equals("rulefailed.consumer.type.mismatch")) {
msg = i18n.tr(
"Consumers of this type are not allowed to subscribe to " +
"the pool with id ''{0}''.", pool.getId());
}
else if (error.equals("rulefailed.pool.does.not.support.multi-entitlement")) {
msg = i18n.tr("Multi-entitlement not supported for pool with id ''{0}''.",
pool.getId());
}
else if (error.equals("virt.guest.host.does.not.match.pool.owner")) {
msg = i18n.tr("Guest''s host does not match owner of pool: ''{0}''.",
pool.getId());
}
else if (error.equals("pool.not.available.to.manifest.consumers")) {
msg = i18n.tr("Pool not available to manifest consumers: ''{0}''.",
pool.getId());
}
else if (error.equals("rulefailed.virt.only")) {
msg = i18n.tr("Pool is restricted to virtual guests: ''{0}''.",
pool.getId());
}
else {
msg = i18n.tr("Unable to entitle consumer to the pool with " +
"id ''{0}''.: {1}", pool.getId().toString(), error);
}
throw new ForbiddenException(msg);
}
}
|
diff --git a/teeda/teeda-core/src/main/java/org/seasar/teeda/core/render/TeedaObjectInputStream.java b/teeda/teeda-core/src/main/java/org/seasar/teeda/core/render/TeedaObjectInputStream.java
index 125d2016c..b23350891 100644
--- a/teeda/teeda-core/src/main/java/org/seasar/teeda/core/render/TeedaObjectInputStream.java
+++ b/teeda/teeda-core/src/main/java/org/seasar/teeda/core/render/TeedaObjectInputStream.java
@@ -1,44 +1,45 @@
/*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* 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.seasar.teeda.core.render;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
/**
* @author shot
*/
public class TeedaObjectInputStream extends ObjectInputStream {
public TeedaObjectInputStream(final InputStream is) throws IOException {
super(is);
}
protected Class resolveClass(final ObjectStreamClass clazz)
throws IOException, ClassNotFoundException {
String clazzName = clazz.getName();
if (clazzName.indexOf("$$") > 0) {
clazzName = clazzName.substring(0, clazzName.indexOf("$$"));
}
try {
- return Class.forName(clazzName);
+ return Class.forName(clazzName, true, Thread.currentThread()
+ .getContextClassLoader());
} catch (final ClassNotFoundException e) {
return super.resolveClass(clazz);
}
}
}
| true | true | protected Class resolveClass(final ObjectStreamClass clazz)
throws IOException, ClassNotFoundException {
String clazzName = clazz.getName();
if (clazzName.indexOf("$$") > 0) {
clazzName = clazzName.substring(0, clazzName.indexOf("$$"));
}
try {
return Class.forName(clazzName);
} catch (final ClassNotFoundException e) {
return super.resolveClass(clazz);
}
}
| protected Class resolveClass(final ObjectStreamClass clazz)
throws IOException, ClassNotFoundException {
String clazzName = clazz.getName();
if (clazzName.indexOf("$$") > 0) {
clazzName = clazzName.substring(0, clazzName.indexOf("$$"));
}
try {
return Class.forName(clazzName, true, Thread.currentThread()
.getContextClassLoader());
} catch (final ClassNotFoundException e) {
return super.resolveClass(clazz);
}
}
|
diff --git a/org.sonar.ide.eclipse.core/src/org/sonar/ide/eclipse/internal/core/resources/SonarProjectManager.java b/org.sonar.ide.eclipse.core/src/org/sonar/ide/eclipse/internal/core/resources/SonarProjectManager.java
index 0d732202..296df676 100644
--- a/org.sonar.ide.eclipse.core/src/org/sonar/ide/eclipse/internal/core/resources/SonarProjectManager.java
+++ b/org.sonar.ide.eclipse.core/src/org/sonar/ide/eclipse/internal/core/resources/SonarProjectManager.java
@@ -1,99 +1,99 @@
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2010-2012 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.ide.eclipse.internal.core.resources;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.osgi.service.prefs.BackingStoreException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ide.eclipse.core.SonarCorePlugin;
/**
* @author Evgeny Mandrikov
*/
public class SonarProjectManager {
private static final Logger LOG = LoggerFactory.getLogger(SonarProjectManager.class);
private static final String P_VERSION = "version";
private static final String P_SONAR_SERVER_URL = "serverUrl";
private static final String P_PROJECT_GROUPID = "projectGroupId";
private static final String P_PROJECT_ARTIFACTID = "projectArtifactId";
private static final String P_PROJECT_BRANCH = "projectBranch";
private static final String P_ANALYSE_LOCALLY = "analyseLocally";
private static final String VERSION = "1";
public ProjectProperties readSonarConfiguration(IProject project) {
- LOG.debug("Rading configuration for project " + project.getName());
+ LOG.debug("Reading configuration for project " + project.getName());
IScopeContext projectScope = new ProjectScope(project);
IEclipsePreferences projectNode = projectScope.getNode(SonarCorePlugin.PLUGIN_ID);
if (projectNode == null) {
LOG.warn("Unable to read configuration");
return new ProjectProperties(project);
}
String version = projectNode.get(P_VERSION, null);
// Godin: we can perform migration here
String artifactId = projectNode.get(P_PROJECT_ARTIFACTID, "");
if (version == null) {
if (StringUtils.isBlank(artifactId)) {
artifactId = project.getName();
}
}
ProjectProperties configuration = new ProjectProperties(project);
configuration.setUrl(projectNode.get(P_SONAR_SERVER_URL, ""));
configuration.setGroupId(projectNode.get(P_PROJECT_GROUPID, ""));
configuration.setArtifactId(artifactId);
configuration.setBranch(projectNode.get(P_PROJECT_BRANCH, ""));
configuration.setAnalysedLocally(projectNode.getBoolean(P_ANALYSE_LOCALLY, false));
return configuration;
}
/**
* @return false, if unable to save configuration
*/
public boolean saveSonarConfiguration(IProject project, ProjectProperties configuration) {
IScopeContext projectScope = new ProjectScope(project);
IEclipsePreferences projectNode = projectScope.getNode(SonarCorePlugin.PLUGIN_ID);
if (projectNode != null) {
LOG.debug("Saving configuration for project " + project.getName());
projectNode.put(P_VERSION, VERSION);
projectNode.put(P_SONAR_SERVER_URL, configuration.getUrl());
projectNode.put(P_PROJECT_GROUPID, configuration.getGroupId());
projectNode.put(P_PROJECT_ARTIFACTID, configuration.getArtifactId());
projectNode.put(P_PROJECT_BRANCH, configuration.getBranch());
projectNode.putBoolean(P_ANALYSE_LOCALLY, configuration.isAnalysedLocally());
try {
projectNode.flush();
return true;
} catch (BackingStoreException e) {
LOG.error("Failed to save project configuration", e);
}
}
return false;
}
}
| true | true | public ProjectProperties readSonarConfiguration(IProject project) {
LOG.debug("Rading configuration for project " + project.getName());
IScopeContext projectScope = new ProjectScope(project);
IEclipsePreferences projectNode = projectScope.getNode(SonarCorePlugin.PLUGIN_ID);
if (projectNode == null) {
LOG.warn("Unable to read configuration");
return new ProjectProperties(project);
}
String version = projectNode.get(P_VERSION, null);
// Godin: we can perform migration here
String artifactId = projectNode.get(P_PROJECT_ARTIFACTID, "");
if (version == null) {
if (StringUtils.isBlank(artifactId)) {
artifactId = project.getName();
}
}
ProjectProperties configuration = new ProjectProperties(project);
configuration.setUrl(projectNode.get(P_SONAR_SERVER_URL, ""));
configuration.setGroupId(projectNode.get(P_PROJECT_GROUPID, ""));
configuration.setArtifactId(artifactId);
configuration.setBranch(projectNode.get(P_PROJECT_BRANCH, ""));
configuration.setAnalysedLocally(projectNode.getBoolean(P_ANALYSE_LOCALLY, false));
return configuration;
}
| public ProjectProperties readSonarConfiguration(IProject project) {
LOG.debug("Reading configuration for project " + project.getName());
IScopeContext projectScope = new ProjectScope(project);
IEclipsePreferences projectNode = projectScope.getNode(SonarCorePlugin.PLUGIN_ID);
if (projectNode == null) {
LOG.warn("Unable to read configuration");
return new ProjectProperties(project);
}
String version = projectNode.get(P_VERSION, null);
// Godin: we can perform migration here
String artifactId = projectNode.get(P_PROJECT_ARTIFACTID, "");
if (version == null) {
if (StringUtils.isBlank(artifactId)) {
artifactId = project.getName();
}
}
ProjectProperties configuration = new ProjectProperties(project);
configuration.setUrl(projectNode.get(P_SONAR_SERVER_URL, ""));
configuration.setGroupId(projectNode.get(P_PROJECT_GROUPID, ""));
configuration.setArtifactId(artifactId);
configuration.setBranch(projectNode.get(P_PROJECT_BRANCH, ""));
configuration.setAnalysedLocally(projectNode.getBoolean(P_ANALYSE_LOCALLY, false));
return configuration;
}
|
diff --git a/net.sourceforge.eclipseccase/src/net/sourceforge/eclipseccase/ClearCaseProvider.java b/net.sourceforge.eclipseccase/src/net/sourceforge/eclipseccase/ClearCaseProvider.java
index bada242..479aae6 100644
--- a/net.sourceforge.eclipseccase/src/net/sourceforge/eclipseccase/ClearCaseProvider.java
+++ b/net.sourceforge.eclipseccase/src/net/sourceforge/eclipseccase/ClearCaseProvider.java
@@ -1,2404 +1,2404 @@
/*******************************************************************************
* Copyright (c) 2002, 2004 eclipse-ccase.sourceforge.net.
* 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:
* Matthew Conway - initial API and implementation
* IBM Corporation - concepts and ideas from Eclipse
* Gunnar Wagenknecht - new features, enhancements and bug fixes
*******************************************************************************/
package net.sourceforge.eclipseccase;
import java.io.File;
import java.text.MessageFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sourceforge.clearcase.ClearCase;
import net.sourceforge.clearcase.ClearCaseCLIImpl;
import net.sourceforge.clearcase.ClearCaseElementState;
import net.sourceforge.clearcase.ClearCaseException;
import net.sourceforge.clearcase.ClearCaseInterface;
import net.sourceforge.clearcase.events.OperationListener;
import net.sourceforge.eclipseccase.ClearCasePreferences;
import org.eclipse.core.resources.*;
import org.eclipse.core.resources.team.FileModificationValidator;
import org.eclipse.core.resources.team.IMoveDeleteHook;
import org.eclipse.core.runtime.*;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.Team;
import org.eclipse.team.core.TeamException;
import org.eclipse.ui.PlatformUI;
/**
* The ClearCase repository provider. Layer to clearcase java api.
*/
public class ClearCaseProvider extends RepositoryProvider {
/** trace id */
private static final String TRACE_ID_IS_IGNORED = "ClearCaseProvider#isIgnored"; //$NON-NLS-1$
private static Map<String, String> viewLookupTable = new Hashtable<String, String>(
200);
private static Map<String, IContainer> viewAccessLookupTable = new Hashtable<String, IContainer>(
30);
private static Map<String, Boolean> snapshotViewLookupTable = new Hashtable<String, Boolean>(
30);
UncheckOutOperation UNCHECK_OUT = new UncheckOutOperation();
CheckInOperation CHECK_IN = new CheckInOperation();
CheckOutOperation CHECKOUT = new CheckOutOperation();
UnHijackOperation UNHIJACK = new UnHijackOperation();
AddOperation ADD = new AddOperation();
RefreshStateOperation REFRESH_STATE = new RefreshStateOperation();
CheckoutUnreservedOperation CO_UNRESERVED = new CheckoutUnreservedOperation();
CheckoutReservedOperation CO_RESERVED = new CheckoutReservedOperation();
private final IMoveDeleteHook moveHandler = new MoveHandler(this);
private String comment = ""; //$NON-NLS-1$
public static final String ID = "net.sourceforge.eclipseccase.ClearcaseProvider"; //$NON-NLS-1$
private static final String TRACE_ID = "ClearCaseProvider"; //$NON-NLS-1$
public static final Status OK_STATUS = new Status(IStatus.OK, ID,
TeamException.OK, "OK", null); //$NON-NLS-1$
public static final Status FAILED_STATUS = new Status(IStatus.ERROR, ID,
TeamException.UNABLE, "FAILED", null); //$NON-NLS-1$
public static final IStatus CANCEL_STATUS = Status.CANCEL_STATUS;
public static final String SNAIL = "@";
public static final String NO_ACTIVITY = "No activity in view";
public static final String UNRESERVED = "unreserved";
public static final String RESERVED = "reserved";
// is used to keep track of which views that has a file checked out when
// doing a move.
public static final ArrayList<String> checkedOutInOtherView = new ArrayList<String>();
boolean refreshResources = true;
private OperationListener opListener = null;
private boolean isTest = false;
private static final int YES = 0;
private static final int NO = 1;
public ClearCaseProvider() {
super();
}
UpdateOperation UPDATE = new UpdateOperation();
DeleteOperation DELETE = new DeleteOperation();
/**
* Checks if the monitor has been canceled.
*
* @param monitor
*/
protected static void checkCanceled(IProgressMonitor monitor) {
if (null != monitor && monitor.isCanceled())
throw new OperationCanceledException();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.team.core.RepositoryProvider#configureProject()
*/
@Override
public void configureProject() throws CoreException {
// configureProject
}
/*
* (non-Javadoc)
*
* @see org.eclipse.team.core.RepositoryProvider#getID()
*/
@Override
public String getID() {
return ID;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IProjectNature#deconfigure()
*/
public void deconfigure() throws CoreException {
// deconfigure
}
public static ClearCaseProvider getClearCaseProvider(IResource resource) {
if (null == resource)
return null;
IProject project = resource.getProject();
if (null == project)
return null;
RepositoryProvider provider = RepositoryProvider.getProvider(project);
if (provider instanceof ClearCaseProvider) {
// FIXME Achim: Whats this next line for?
((ClearCaseProvider) provider).opListener = null;
return (ClearCaseProvider) provider;
} else
return null;
}
/*
* @see SimpleAccessOperations#get(IResource[], int, IProgressMonitor)
*/
public void get(IResource[] resources, int depth, IProgressMonitor progress)
throws TeamException {
execute(UPDATE, resources, depth, progress);
}
/*
* @see SimpleAccessOperations#checkout(IResource[], int, IProgressMonitor)
*/
public void checkout(IResource[] resources, int depth,
IProgressMonitor progress) throws TeamException {
try {
execute(CHECKOUT, resources, depth, progress);
} finally {
setComment("");
}
}
public void unhijack(IResource[] resources, int depth,
IProgressMonitor progress) throws TeamException {
try {
execute(UNHIJACK, resources, depth, progress);
} finally {
setComment("");
}
}
/**
* Invalidates the state cache of all specified resources.
*
* @param resourceToRefresh
* @param monitor
* @throws CoreException
*/
public void refreshRecursive(IResource resourceToRefresh,
IProgressMonitor monitor) throws CoreException {
try {
monitor.beginTask("Refreshing " + resourceToRefresh.getName(), 50);
final List<IResource> toRefresh = new ArrayList<IResource>(80);
monitor.subTask("collecting members");
resourceToRefresh.accept(new IResourceVisitor() {
public boolean visit(IResource resource) throws CoreException {
if (!Team.isIgnoredHint(resource)) {
toRefresh.add(resource);
}
return true;
}
});
monitor.worked(30);
monitor.subTask("scheduling updates");
if (!toRefresh.isEmpty()) {
StateCacheFactory.getInstance().refreshStateAsyncHighPriority(
toRefresh.toArray(new IResource[toRefresh.size()]),
monitor);
}
monitor.worked(10);
} finally {
monitor.done();
}
}
public void refreshRecursive(IResource[] resources, IProgressMonitor monitor) {
StateCacheFactory.getInstance().refreshStateAsyncHighPriority(
resources, monitor);
}
/**
* Invalidates the state of the specified resource and only of the specified
* resource, not recursive
*
* @param resource
*/
public void refresh(IResource resource) {
StateCacheFactory.getInstance().get(resource).updateAsync(true);
}
/*
* @see SimpleAccessOperations#checkin(IResource[], int, IProgressMonitor)
*/
public void checkin(IResource[] resources, int depth,
IProgressMonitor progressMonitor) throws TeamException {
try {
execute(CHECK_IN, resources, depth, progressMonitor);
} finally {
setComment("");
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.team.core.RepositoryProvider#getRuleFactory()
*/
@Override
public IResourceRuleFactory getRuleFactory() {
return new ClearCaseResourceRuleFactory();
}
/**
* @see SimpleAccessOperations#uncheckout(IResource[], int,
* IProgressMonitor)
*/
public void uncheckout(IResource[] resources, int depth,
IProgressMonitor progress) throws TeamException {
execute(UNCHECK_OUT, resources, depth, progress);
}
/**
* @see SimpleAccessOperations#delete(IResource[], IProgressMonitor)
*/
public void delete(IResource[] resources, IProgressMonitor progress)
throws TeamException {
try {
execute(DELETE, resources, IResource.DEPTH_INFINITE, progress);
} finally {
setComment("");
}
}
public void add(IResource[] resources, int depth, IProgressMonitor progress)
throws TeamException {
try {
execute(ADD, resources, depth, progress);
} finally {
setComment("");
}
}
public void unreserved(IResource[] resources, int depth,
IProgressMonitor progress) throws TeamException {
try {
execute(CO_UNRESERVED, resources, depth, progress);
} finally {
setComment("");
}
}
public void reserved(IResource[] resources, int depth,
IProgressMonitor progress) throws TeamException {
try {
execute(CO_RESERVED, resources, depth, progress);
} finally {
setComment("");
}
}
/*
* @see SimpleAccessOperations#moved(IPath, IResource, IProgressMonitor)
*/
public void moved(IPath source, IResource target, IProgressMonitor progress)
throws TeamException {
// moved
}
/**
* @see SimpleAccessOperations#isCheckedOut(IResource)
*/
public boolean isCheckedOut(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isCheckedOut();
}
/**
* Indicates if the specified resource is contained in a Snapshot view.
*
* @param resource
* @return
*/
public boolean isSnapShot(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isSnapShot();
}
public boolean isHijacked(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isHijacked();
}
public boolean isUnknownState(IResource resource) {
return StateCacheFactory.getInstance().isUninitialized(resource);
}
/**
* @see SimpleAccessOperations#isClearCaseElement(IResource)
*/
public boolean isClearCaseElement(IResource resource) {
return StateCacheFactory.getInstance().get(resource)
.isClearCaseElement();
}
/*
* @see SimpleAccessOperations#isDirty(IResource)
*/
public boolean isDirty(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isDirty();
}
public String getVersion(IResource resource) {
return StateCacheFactory.getInstance().get(resource).getVersion();
}
public String getPredecessorVersion(IResource resource) {
return StateCacheFactory.getInstance().get(resource)
.getPredecessorVersion();
}
public void showVersionTree(String element, File workingDir) {
ClearCasePlugin.getEngine().showVersionTree(element, workingDir);
}
public void showFindMerge(File workingDir) {
ClearCasePlugin.getEngine().showFindMerge(workingDir);
}
public String[] loadBrancheList(File workingDir) {
return ClearCasePlugin.getEngine().loadBrancheList(workingDir);
}
public String[] searchFilesInBranch(String branchName, File workingDir,
OperationListener listener) {
return ClearCasePlugin.getEngine().searchFilesInBranch(branchName,
workingDir, listener);
}
public void update(String element, int flags, boolean workingDir) {
ClearCasePlugin.getEngine().update(element, flags, workingDir);
}
public void compareWithPredecessor(String element) {
ClearCasePlugin.getEngine().compareWithPredecessor(element);
}
public void describeVersionGUI(String element) {
ClearCasePlugin.getEngine().describeVersionGUI(element);
}
public String[] describe(String element, int flag, String format) {
return ClearCasePlugin.getEngine().describe(element, flag, format);
}
public void compareWithVersion(String element1, String element2) {
ClearCasePlugin.getEngine().compareWithVersion(element1, element2);
}
/**
* Parsers single/multiple line/-s of output. Type.java Predecessor:
* /main/dev/0 View:eraonel_w12b2 Status: unreserved
*
* @param element
* @return
*/
public boolean isCheckedOutInAnyView(String element) {
// UCM we do not need to know of another stream co.
if (ClearCasePreferences.isUCM()) {
return false;
}
boolean isCheckedoutInOtherView = false;
checkedOutInOtherView.clear();
HashMap<Integer, String> args = new HashMap<Integer, String>();
args.put(Integer.valueOf(ClearCase.FORMAT),
"%En\tPredecessor: %[version_predecessor]p\tView: %Tf\tStatus: %Rf\n");
String[] output = ClearCasePlugin.getEngine().findCheckouts(
ClearCase.FORMAT, args, new String[] { element });
// Check if line ends with these keywords.
Pattern pattern = Pattern.compile(".*View:\\s(.*)\\sStatus:.*");
if (output.length > 0) {
// we have file checked-out in other view.
isCheckedoutInOtherView = true;
for (int i = 0; i < output.length; i++) {
String line = output[i];
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
// Adding information to user.Filter out current view.
String view = matcher.group(1);
if (!view.equals(getViewName(element))) {
checkedOutInOtherView.add(view);
}
}
}
}
return isCheckedoutInOtherView;
}
public static String getViewName(IResource resource) {
if (resource == null || resource.getProject() == null)
return "";
// assume that a complete project is inside one view
String path;
try {
path = resource.getProject().getLocation().toOSString();
} catch (NullPointerException e) {
return "";
}
String res = viewLookupTable.get(path);
if (res == null || res.length() == 0) {
// use the originally given resource for the cleartool query
if (!(resource instanceof IContainer)) {
resource = resource.getParent();
}
res = getViewName(resource.getLocation().toOSString());
if (res.length() > 0) {
viewLookupTable.put(path, res);
viewAccessLookupTable.put(res, (IContainer) resource);
}
}
return res;
}
public static IContainer getViewFolder(final String viewname) {
IContainer res = viewAccessLookupTable.get(viewname);
if (res == null) {
// TODO: search for a directory in view
} else if (!res.isAccessible()) {
// TODO: search for a new directory in view
}
return res;
}
public static String getViewName(final String path) {
String res = viewLookupTable.get(path);
if (res == null) {
res = ClearCasePlugin.getEngine().getViewName(path);
viewLookupTable.put(path, res);
}
return res;
}
public static String[] getUsedViewNames() {
Set<String> views = new HashSet<String>();
for (String v : viewLookupTable.values()) {
views.add(v);
}
return views.toArray(new String[views.size()]);
}
/**
* Returns the view type of the view containing the resource.
*
* @param resource
* The resource inside a view.
* @return "dynamic" or "snapshot"
*/
public static String getViewType(IResource resource) {
return isSnapshotView(getViewName(resource)) ? ClearCaseInterface.VIEW_TYPE_SNAPSHOT
: ClearCaseInterface.VIEW_TYPE_DYNAMIC;
}
public static boolean isSnapshotView(final String viewName) {
Boolean res = snapshotViewLookupTable.get(viewName);
if (res == null) {
if (viewName.length() == 0) {
// special case, can happen after queries in non-view
// directories
res = false;
} else {
// standard case, we have a viewname, ask CC for the type
String viewtype = ClearCasePlugin.getEngine().getViewType(
viewName);
res = viewtype.equals(ClearCaseInterface.VIEW_TYPE_SNAPSHOT);
}
snapshotViewLookupTable.put(viewName, res);
}
return res;
}
/**
* Returns the root of the view. An empty view root indicates a dynamic
* view.
*
* @param resource
* @return
*/
public String getViewRoot(IResource resource) throws TeamException {
return ClearCasePlugin.getEngine().getViewLocation();
}
/**
* Returns the name of the vob that contains the specified element
*
* @param resource
* @return
*/
public String getVobName(IResource resource) throws TeamException {
String viewRoot = getViewRoot(resource);
IPath viewLocation = new Path(viewRoot);
IPath resourceLocation = resource.getLocation();
// ignore device when dealing with dynamic views
if (viewRoot.length() == 0) {
viewLocation = viewLocation.setDevice(resourceLocation.getDevice());
}
if (viewLocation.isPrefixOf(resourceLocation)) {
IPath vobLocation = resourceLocation
.removeFirstSegments(viewLocation.segmentCount());
if (!ClearCasePlugin.isWindows() && vobLocation.segmentCount() > 0) {
// on unix vobs are prefixed with directory named "/vobs"
vobLocation = vobLocation.removeFirstSegments(1);
}
if (vobLocation.segmentCount() > 0)
return vobLocation.segment(0);
}
return "none";
}
/**
* Returns the vob relative path of the specified element
*
* @param resource
* @return the vob relativ path (maybe <code>null</code> if outside vob)
*/
public String getVobRelativPath(IResource resource) throws TeamException {
String viewRoot = getViewRoot(resource);
IPath viewLocation = new Path(viewRoot).setDevice(null); // ignore
// device
IPath resourceLocation = resource.getLocation().setDevice(null); // ignore
// devices
if (viewLocation.isPrefixOf(resourceLocation)) {
IPath vobLocation = resourceLocation
.removeFirstSegments(viewLocation.segmentCount());
if (!ClearCasePlugin.isWindows() && vobLocation.segmentCount() > 0) {
// on unix vobs are prefixed with directory named "/vobs"
vobLocation = vobLocation.removeFirstSegments(1);
}
if (vobLocation.segmentCount() > 0)
return vobLocation.removeFirstSegments(1).makeRelative()
.toString();
}
return null;
}
// FIXME: We need to handle exceptions.
public boolean setActivity(String activitySelector, String viewName) {
ClearCaseElementState[] cces = ClearCasePlugin.getEngine().setActivity(
ClearCase.VIEW, activitySelector, viewName);
if (cces == null) {
System.out.println("ERROR: Could not set activity: "
+ activitySelector + " Got null response.");
return false;
}
if (cces[0].state == ClearCase.ACTIVITY_SET) {
return true;
} else {
return false;
}
}
/**
* Returns a list of actvities. Makes a new request each time and does not
* cache.
*
* @param viewName
* @return
*/
public ArrayList<String> listMyActivities() {
String[] output = ClearCasePlugin.getEngine().getActivity(
ClearCase.CVIEW | ClearCase.ME | ClearCase.SHORT, null);
if (output.length > 0) {
return new ArrayList<String>(Arrays.asList(output));
}
return new ArrayList<String>(
Arrays.asList(new String[] { NO_ACTIVITY }));
}
public ArrayList<String> listAllActivities() {
String[] output = ClearCasePlugin.getEngine().getActivity(
ClearCase.CVIEW | ClearCase.SHORT, null);
return new ArrayList<String>(Arrays.asList(output));
}
/**
*
* @return
*/
public boolean activityAssociated(String viewName) {
HashMap<Integer, String> args = new HashMap<Integer, String>();
args.put(Integer.valueOf(ClearCase.VIEW), viewName);
String[] output = ClearCasePlugin.getEngine().getActivity(
ClearCase.VIEW | ClearCase.SHORT, args);
if (output.length > 0) {
if (ClearCasePlugin.DEBUG_PROVIDER) {
ClearCasePlugin.trace(TRACE_ID,
"Activity " + output[0] + " is associated!"); //$NON-NLS-1$
}
return true;
}
return false;
}
/**
* Get name of set activity in current view.
*
* @return
*/
public String getCurrentActivity() {
String result = "";
String[] output = ClearCasePlugin.getEngine().getActivity(
ClearCase.SHORT | ClearCase.CACT, null);
if (output == null | output.length == 0) {
return result;
}
if (output[0] != null && output[0].length() > 0) {
return output[0];
}
return result;
}
public ClearCaseElementState createActivity(String headline,
String activitySelector, String path) throws ClearCaseException {
ClearCaseElementState[] cces = ClearCasePlugin.getEngine().mkActivity(
ClearCase.HEADLINE | ClearCase.FORCE | ClearCase.NSET,
headline, activitySelector, path);
if (cces != null) {
return cces[0];
} else {
return null;
}
}
// public String getStream(String viewName) {
// return ClearCasePlugin.getEngine().getStream(
// ClearCase.SHORT | ClearCase.VIEW, viewName);
// }
public String getCurrentStream() {
String result = "";
String[] output = ClearCasePlugin.getEngine().getStream(
ClearCase.SHORT, null);
if (output != null && output.length > 0) {
result = output[0];
}
return result;
}
/**
* Extract pvob tag. (Unix) activity:<activity_name>@/vobs/$pvob or
* /vob/$pvob (Windows) activity:<activity_name@\$pvob
*
* @param activitySelector
* @return pVobTag $pvob
*/
public String getPvobTag(String activitySelector) {
int index = activitySelector.indexOf(SNAIL) + 1;
String path = activitySelector.substring(index).trim();
return path.substring(0);
}
/**
* getStream() returns an array but contains one or no element.If we have
* actvities in stream we have one element.
* activity:<activityId>@/vobs/$pvob,activity:<activityId>@/vobs/$pvob,
* activity: ... All activities are on one line.
*
* @return array of activities or an empty array.
*/
public String[] getActivitySelectors(String view) {
String[] result = new String[] {};
HashMap<Integer, String> args = new HashMap<Integer, String>();
args.put(Integer.valueOf(ClearCase.FORMAT), "%[activities]CXp");
args.put(Integer.valueOf(ClearCase.VIEW), view);
String[] output = ClearCasePlugin.getEngine().getStream(
ClearCase.FORMAT | ClearCase.VIEW, args);
if (output != null && output.length == 1) {
result = output[0].split(", ");
}
return result;
}
/**
* Before the move operation we check if parent directories are checked out.
* We use that after the move has been performed in clearcase to set
* directories state (co/ci) as prior to move operation. If checkout is need
* then it is performed within the java clearcase package. The checkin is
* however performed within this method since we know the state prior to
* move operation and there is no need to send this information to the
* clearcase package. So an evetual checkin will be performed in this
* method.
*
* @param source
* @param destination
* @param monitor
* @return result status of the operation.
*/
public IStatus move(IResource source, IResource destination,
IProgressMonitor monitor) {
int returnCode = 1;// Used in messge dialog.
try {
monitor.beginTask("Moving " + source.getFullPath() + " to "
+ destination.getFullPath(), 100);
// Sanity check - can't move something that is not part of clearcase
if (!isClearCaseElement(source))
return new Status(
IStatus.ERROR,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format("Resource \"{0}\" is not under source control!",
new Object[] { source.getFullPath()
.toString() }), null);
IStatus result = OK_STATUS;
ClearCaseElementState[] state = null;
if (isCheckedOutInAnyView(source.getLocation().toOSString())) {
StringBuffer sb = new StringBuffer();
for (String view : checkedOutInOtherView) {
sb.append(view + "\t");
}
// Open message dialog and ask if we want to continue.
returnCode = showMessageDialog(
"File Checkedout in Other View ",
"File checkedout in the following views: "
+ sb.toString() + "\n"
+ " Do you still want to move, "
+ source.getName() + "?");
if (returnCode != 0) {
return cancelCheckout(source, monitor, opListener);
}
}
if (ClearCasePreferences.isAutoCheckinParentAfterMoveAllowed()) {
state = ClearCasePlugin.getEngine()
.move(source.getLocation().toOSString(),
destination.getLocation().toOSString(),
getComment(),
ClearCase.FORCE | ClearCase.CHECKIN
| getCheckoutType(), opListener);
} else {
state = ClearCasePlugin.getEngine().move(
source.getLocation().toOSString(),
destination.getLocation().toOSString(), getComment(),
ClearCase.FORCE | getCheckoutType(), opListener);
}
StateCacheFactory.getInstance().remove(source);
updateState(source.getParent(), IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
updateState(destination.getParent(), IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
updateState(destination, IResource.DEPTH_INFINITE,
new SubProgressMonitor(monitor, 10));
if (!state[0].isMoved())
return new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Could not move element: "
// + ccStatus.message
, null);
return result;
} finally {
setComment("");
monitor.done();
}
}
public IStatus checkoutParent(IResource resource, IProgressMonitor monitor) {
try {
monitor.beginTask("Checking out "
+ resource.getParent().getFullPath().toString(), 10);
IStatus result = OK_STATUS;
String parent = null;
// IProject's parent is the workspace directory, we want the
// filesystem
// parent if the workspace is not itself in clearcase
boolean flag = resource instanceof IProject
&& !isClearCaseElement(resource.getParent());
if (flag) {
parent = resource.getLocation().toFile().getParent().toString();
} else {
parent = resource.getParent().getLocation().toOSString();
}
monitor.worked(2);
ClearCaseElementState elementState = ClearCasePlugin.getEngine()
.getElementState(parent);
if (!elementState.isElement()) {
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Could not find a parent that is a clearcase element",
null);
return result;
}
monitor.worked(2);
if (!elementState.isCheckedOut() && !elementState.isLink()) {
String[] element = { parent };
ClearCaseElementState[] elementState2 = ClearCasePlugin
.getEngine().checkout(element, getComment(),
getCheckoutType(), opListener);
monitor.worked(4);
if (!flag) {
updateState(resource.getParent(), IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
}
if (elementState2 == null) {
// TODO: Handle ccStatus.message.
result = new Status(IStatus.ERROR, ID,
TeamException.UNABLE,
"Could not check out parent: " + "ccStatus", null);
}
}
return result;
} finally {
monitor.done();
}
}
// Notifies decorator that state has changed for an element
public void updateState(IResource resource, int depth,
IProgressMonitor monitor) {
try {
monitor.beginTask("Refreshing " + resource.getFullPath(), 20);
if (!refreshResources) {
StateCacheFactory.getInstance().removeSingle(resource);
monitor.worked(10);
} else {
resource.refreshLocal(depth,
new SubProgressMonitor(monitor, 10));
}
if (resource.exists()) {
doUpdateState(resource, depth, new SubProgressMonitor(monitor,
10));
} else {
StateCacheFactory.getInstance().refreshStateAsyncHighPriority(
new IResource[] { resource }, null);
}
} catch (CoreException ex) {
ClearCasePlugin.log(IStatus.ERROR,
"Error refreshing ClearCase state: " + ex.getMessage(), ex);
} finally {
monitor.done();
}
}
private IStatus doUpdateState(IResource resource, int depth,
IProgressMonitor progressMonitor) {
IStatus result = execute(REFRESH_STATE, resource, depth,
progressMonitor);
return result;
}
/**
* @see RepositoryProvider#getMoveDeleteHook()
*/
@Override
public IMoveDeleteHook getMoveDeleteHook() {
return moveHandler;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.team.core.RepositoryProvider#getFileModificationValidator2()
*/
@Override
public FileModificationValidator getFileModificationValidator2() {
return ClearCasePlugin.getDefault().getClearCaseModificationHandler();
}
/**
* Gets the comment.
*
* @return Returns a String
*/
public String getComment() {
return comment;
}
/**
* Sets the comment.
*
* @param comment
* The comment to set
*/
public void setComment(String comment) {
// escape comment if enabled
// if (comment.trim().length() > 0 && ClearCasePlugin.isCommentEscape())
// comment = ClearCaseUtil.getEscaped(comment);
this.comment = comment;
}
// Out of sheer laziness, I appropriated the following code from the team
// provider example =)
private static final class RefreshStateOperation implements
IRecursiveOperation {
@SuppressWarnings("deprecation")
public IStatus visit(IResource resource, IProgressMonitor monitor) {
try {
checkCanceled(monitor);
monitor.beginTask("Refreshing State " + resource.getFullPath(),
10);
// probably overkill/expensive to do it here - should do it
// on a
// case by case basis for each method that actually changes
// state
StateCache cache = StateCacheFactory.getInstance()
.get(resource);
if (!cache.isSymbolicLink()) {
// force update immediately. For symlinks, the symlink
// target has to be updated first, see below
cache.doUpdate();
}
// check if a symbolic link target is also in our workspace
if (cache.isSymbolicLink()
&& null != cache.getSymbolicLinkTarget()) {
File target = new File(cache.getSymbolicLinkTarget());
if (!target.isAbsolute()) {
target = null != cache.getPath() ? new File(
cache.getPath()).getParentFile() : null;
if (null != target) {
target = new File(target,
cache.getSymbolicLinkTarget());
}
}
if (null != target && target.exists()) {
IPath targetLocation = new Path(
target.getAbsolutePath());
IResource[] resources = null;
if (target.isDirectory()) {
resources = ResourcesPlugin.getWorkspace()
.getRoot()
.findContainersForLocation(targetLocation);
} else {
resources = ResourcesPlugin.getWorkspace()
.getRoot()
.findFilesForLocation(targetLocation);
}
if (null != resources) {
for (int i = 0; i < resources.length; i++) {
IResource foundResource = resources[i];
ClearCaseProvider provider = ClearCaseProvider
.getClearCaseProvider(foundResource);
if (null != provider) {
StateCacheFactory.getInstance()
.get(foundResource)
.updateAsync(false);
// after the target is updated, we must
// update the
// symlink itself again :-(
cache.updateAsync(false);
}
}
}
}
}
return OK_STATUS;
} finally {
monitor.done();
}
}
}
private final class AddOperation implements IRecursiveOperation {
ArrayList<IResource> privateElement = new ArrayList<IResource>();
ArrayList<IResource> parentToCheckin = new ArrayList<IResource>();
public IStatus visit(IResource resource, IProgressMonitor monitor) {
try {
monitor.beginTask(
"Adding " + resource.getFullPath().toString(), 100);
IStatus result = OK_STATUS;
// Sanity check - can't add something that already is under VC
if (isClearCaseElement(resource))
// return status with severity OK
return new Status(
IStatus.OK,
ID,
TeamException.UNABLE,
MessageFormat
.format("Resource \"{0}\" is already under source control!",
new Object[] { resource
.getFullPath().toString() }),
null);
result = findPrivateElements(resource, monitor);
if (result.isOK()) {
Collections.reverse(privateElement);
for (Object element : privateElement) {
IResource myResource = (IResource) element;
if (myResource.getType() == IResource.FOLDER) {
result = makeFolderElement(myResource, monitor);
} else if (myResource.getType() == IResource.FILE) {
result = makeFileElement(myResource, monitor);
}
}
}
// Add operation checks out parent directory. Change state to
// checked-out. No resource changed event is sent since this is
// implicitly done by
// add.
IResource directory = resource.getParent();
try {
directory.refreshLocal(IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
updateState(directory, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
} catch (CoreException e) {
System.out.println("We got an exception!");
e.printStackTrace();
result = new Status(IStatus.ERROR, ID,
TeamException.UNABLE, "Add failed: " + "Exception"
+ e.getMessage(), null);
}
// Add check recursive checkin of files.
if (ClearCasePreferences.isAddWithCheckin()
&& result == OK_STATUS) {
try {
for (Object element : privateElement) {
IResource res = (IResource) element;
IResource folder = res.getParent();
if (!parentToCheckin.contains(folder)) {
parentToCheckin.add(folder);
}
if (isCheckedOut(res)) {
checkin(new IResource[] { res },
IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
}
}
for (IResource parent : parentToCheckin) {
if (isCheckedOut(parent)) {
checkin(new IResource[] { parent },
IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
}
}
} catch (TeamException e) {
result = new Status(IStatus.ERROR, ID,
TeamException.UNABLE,
"Checkin of resource failed: " + "Exception"
+ e.getMessage(), null);
}
}
monitor.worked(40);
return result;
} finally {
monitor.done();
privateElement.clear();
parentToCheckin.clear();
}
}
/**
* Recursively from bottom of file path to top until clearcase element
* is found.
*
* @param resource
* @param monitor
* @return
*/
private IStatus findPrivateElements(IResource resource,
IProgressMonitor monitor) {
IStatus result = OK_STATUS;
IResource parent = resource.getParent();
// When resource is a project, try checkout its parent, and if
// that fails,
// then neither project nor workspace is in clearcase.
if (isClearCaseElement(parent)) {
privateElement.add(resource);
updateState(parent, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));// make sure state
// for parent is
// correct.
if (!isCheckedOut(parent)) {
ClearCaseElementState[] state = ClearCasePlugin.getEngine()
.checkout(
new String[] { parent.getLocation()
.toOSString() }, getComment(),
ClearCase.NONE, opListener);
if (state[0].isCheckedOut()) {
updateState(parent, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
}
}
} else if (resource instanceof IProject
&& !(isClearCaseElement(resource))) {
// We reached project top and it is not a cc element.
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Add failed: " + "project folder " + resource.getName()
+ " is not an element is not an cc element",
null);
} else {
privateElement.add(resource);
findPrivateElements(parent, new SubProgressMonitor(monitor, 10));
}
return result;
}
}
private Status makeFileElement(IResource resource, IProgressMonitor monitor) {
Status result = OK_STATUS;
ClearCaseElementState state = ClearCasePlugin
.getEngine()
.add(resource.getLocation().toOSString(),
false,
getComment(),
ClearCase.PTIME
| (ClearCasePreferences.isUseMasterForAdd() ? ClearCase.MASTER
: ClearCase.NONE), opListener);
if (state.isElement()) {
// Do nothing!
} else {
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Add failed: " + "Could not add element"
+ resource.getName(), null);
}
try {
resource.refreshLocal(IResource.DEPTH_ZERO, new SubProgressMonitor(
monitor, 10));
} catch (CoreException e) {
System.out.println("We got an exception!");
e.printStackTrace();
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Add failed: " + "Exception" + e.getMessage(), null);
}
updateState(resource, IResource.DEPTH_ZERO, new SubProgressMonitor(
monitor, 10));
if (result.isOK()) {
result = forceSetChgrp(resource);
}
return result;
}
private Status makeFolderElement(IResource resource,
IProgressMonitor monitor) {
File dir = new File(resource.getLocation().toOSString());
File tmpDir = new File(dir.getParentFile(), dir.getName() + ".tmp");
Status result = OK_STATUS;
try {
// rename target dir to <name>.tmp since clearcase cannot make
// an directory element out of an existing view private one.
if (!dir.renameTo(tmpDir)) {
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Add failed: " + "Could not rename " + dir.getPath()
+ " to " + tmpDir.getPath()
+ resource.getName(), null);
}
// Now time to create the original directory in
// clearcase.
ClearCaseElementState state = ClearCasePlugin.getEngine().add(
resource.getLocation().toOSString(),
true,
getComment(),
ClearCasePreferences.isUseMasterForAdd() ? ClearCase.MASTER
: ClearCase.NONE, opListener);
if (!state.isElement()) {
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Add failed: " + "Could not add element"
+ resource.getName(), null);
}
// Now move back the content of <name>.tmp to cc created one.
if (!moveDirRec(tmpDir, dir)) {
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Could not move back the content of " + dir.getPath()
+ " as part of adding it to Clearcase:\n"
+ "Its old content is in " + tmpDir.getName()
+ ". Please move it back manually", null);
}
if (result.isOK()) {
result = forceSetChgrp(resource);
}
// Now move back the content of tmp to original.
// To avoid CoreException do a refreshLocal(). Does
// not recognize the cc created resource directory.
resource.refreshLocal(IResource.DEPTH_ZERO, new SubProgressMonitor(
monitor, 10));
updateState(resource, IResource.DEPTH_ZERO, new SubProgressMonitor(
monitor, 10));
} catch (CoreException ce) {
System.out.println("We got an exception!");
ce.printStackTrace();
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Add failed: " + "Exception" + ce.getMessage(), null);
}
return result;
}
private Status forceSetChgrp(IResource resource) {
Status result = OK_STATUS;
String group = ClearCasePreferences.getClearCasePrimaryGroup().trim();
if (group.length() > 0) {
try {
ClearCasePlugin.getEngine().setGroup(
resource.getLocation().toOSString(), group, opListener);
} catch (Exception e) {
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Chgrp failed: " + "Could not change group element "
+ resource.getName() + "\n" + e.getMessage(),
null);
}
}
return result;
}
private final class UncheckOutOperation implements IRecursiveOperation {
public IStatus visit(final IResource resource,
final IProgressMonitor monitor) {
try {
monitor.beginTask("Uncheckout " + resource.getFullPath(), 100);
StateCache cache = getCache(resource);
final StateCache targetElement = getFinalTargetElement(cache);
// Sanity check - can't process something that is not part of
// clearcase
if (targetElement == null
|| !targetElement.isClearCaseElement())
return new Status(
IStatus.WARNING,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format("Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
// Sanity check - can't uncheckout something that is not checked
// out
if (!targetElement.isCheckedOut())
// return severity OK
return new Status(IStatus.OK, ID,
TeamException.NOT_CHECKED_OUT,
MessageFormat.format(
"Resource \"{0}\" is not checked out!",
new Object[] { targetElement.getPath() }),
null);
IStatus result = OK_STATUS;
// Yes continue checking out.
int flags = ClearCase.RECURSIVE;
if (ClearCasePreferences.isKeepChangesAfterUncheckout()) {
flags |= ClearCase.KEEP;
}
ClearCasePlugin.getEngine().uncheckout(
new String[] { targetElement.getPath() }, flags,
opListener);
monitor.worked(40);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
// if (!status.status) {
// result = new Status(IStatus.ERROR, ID,
// TeamException.UNABLE, "Uncheckout failed: "
// + status.message, null);
// }
return result;
} finally {
monitor.done();
}
}
}
private final class DeleteOperation implements IIterativeOperation {
public IStatus visit(IResource resource, int depth,
IProgressMonitor monitor) {
try {
monitor.beginTask("Deleting " + resource.getFullPath(), 100);
// Sanity check - can't delete something that is not part of
// clearcase
if (!isClearCaseElement(resource))
return new Status(
IStatus.ERROR,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format("Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
IStatus result = checkoutParent(resource,
new SubProgressMonitor(monitor, 10));
if (result.isOK()) {
ClearCasePlugin.getEngine()
.delete(new String[] { resource.getLocation()
.toOSString() }, getComment(),
ClearCase.RECURSIVE | ClearCase.KEEP,
opListener);
monitor.worked(40);
updateState(resource, IResource.DEPTH_INFINITE,
new SubProgressMonitor(monitor, 10));
// if (!status.status) {
// result = new Status(IStatus.ERROR, ID,
// TeamException.UNABLE, "Delete failed: "
// + status.message, null);
// }
}
return result;
} finally {
monitor.done();
}
}
}
protected final class CheckInOperation implements IRecursiveOperation {
public IStatus visit(IResource resource, IProgressMonitor monitor) {
try {
int returnCode = 1;// Used in messge dialog.
monitor.beginTask("Checkin in " + resource.getFullPath(), 100);
StateCache cache = getCache(resource);
final StateCache targetElement = getFinalTargetElement(cache);
IStatus result = OK_STATUS;
// Sanity check - can't check in something that is not part of
// clearcase
if (targetElement == null
|| !targetElement.isClearCaseElement())
return new Status(
IStatus.WARNING,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format("Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
// Sanity check - can't checkin something that is not checked
// out
if (!targetElement.isCheckedOut())
// return status with severity OK
return new Status(IStatus.OK, ID,
TeamException.NOT_CHECKED_OUT,
MessageFormat.format(
"Resource \"{0}\" is not checked out!",
new Object[] { targetElement.getPath() }),
null);
if (ClearCasePreferences.isCheckinIdenticalAllowed()) {
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement.getPath() },
getComment(),
ClearCase.PTIME | ClearCase.IDENTICAL, opListener);
} else {
try {
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement.getPath() },
getComment(), ClearCase.PTIME, opListener);
} catch (ClearCaseException cce) {
// check error
switch (cce.getErrorCode()) {
case ClearCase.ERROR_PREDECESSOR_IS_IDENTICAL:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.identicalPredecessor"),
new Object[] { cce.getElements() }),
null);
break;
case ClearCase.ERROR_ELEMENT_HAS_CHECKOUTS:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.elementHasCheckouts"),
new Object[] { cce.getElements() }),
null);
break;
case ClearCase.ERROR_MOST_RECENT_NOT_PREDECESSOR_OF_THIS_VERSION:
// Only support for: To merge the latest version
// with your checkout
// getVersion --> \branch\CHECKEDOUT.
String branchName = getBranchName(getVersion(resource));
String latestVersion = resource.getLocation()
.toOSString()
+ "@@"
+ branchName
+ "LATEST";
ClearCaseElementState myState = ClearCasePlugin
.getEngine().merge(targetElement.getPath(),
- new String[] { latestVersion },
+ new String[] { latestVersion },null,
ClearCase.GRAPHICAL);
if (myState.isMerged()) {
returnCode = showMessageDialog("Checkin",
"Do you want to checkin the merged result?");
if (returnCode == 0) {
// Yes continue checkin
ClearCasePlugin
.getEngine()
.checkin(
new String[] { targetElement
.getPath() },
getComment(),
ClearCase.PTIME, opListener);
}
} else {
result = new Status(
IStatus.ERROR,
ID,
TeamException.CONFLICT,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.mergeLatestProblem"),
new Object[] { cce
.getElements() }), null);
}
break;
default:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.unknown"),
new Object[] { cce.getElements() }),
null);
break;
}
}
}
monitor.worked(40);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
}
private final class CheckOutOperation implements IRecursiveOperation {
public IStatus visit(final IResource resource,
final IProgressMonitor monitor) {
try {
int returnCode = 1;// Used for message dialogs.
monitor.beginTask("Checking out " + resource.getFullPath(), 100);
StateCache cache = getCache(resource);
final StateCache targetElement = getFinalTargetElement(cache);
// Sanity check - can't checkout something that is not part of
// clearcase
if (targetElement == null
|| !targetElement.isClearCaseElement())
return new Status(
IStatus.WARNING,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format("Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
// Sanity check - can't checkout something that is already
// checked out
if (targetElement.isCheckedOut())
// return status with severity OK
return new Status(IStatus.OK, ID,
TeamException.NOT_CHECKED_IN, MessageFormat.format(
"Resource \"{0}\" is already checked out!",
new Object[] { targetElement.getPath() }),
null);
IStatus result = OK_STATUS;
// update if necessary
if (ClearCasePreferences.isCheckoutLatest()
&& targetElement.isSnapShot()) {
monitor.subTask("Updating " + targetElement.getPath());
update(resource.getFullPath().toOSString(), 0, false);
}
monitor.worked(20);
// only checkout if update was successful
if (result == OK_STATUS) {
monitor.subTask("Checking out " + targetElement.getPath());
try {
ClearCasePlugin
.getEngine()
.checkout(
new String[] { targetElement.getPath() },
getComment(),
getCheckoutType()
| ClearCase.PTIME
| (targetElement.isHijacked() ? ClearCase.HIJACKED
: ClearCase.NONE)
| (ClearCasePreferences
.isUseMasterForAdd() ? ClearCase.NMASTER
: ClearCase.NONE),
opListener);
} catch (ClearCaseException cce) {
switch (cce.getErrorCode()) {
case ClearCase.ERROR_ELEMENT_HAS_CHECKOUTS:
returnCode = showMessageDialog("Checkout",
"Resource already checked-out reserved.\nDo you want to check-out unreserved?");
if (returnCode == 0) {
// Yes continue checking out but
// unreserved.
ClearCasePlugin
.getEngine()
.checkout(
new String[] { targetElement
.getPath() },
getComment(),
ClearCase.UNRESERVED
| ClearCase.PTIME
| (ClearCasePreferences
.isUseMasterForAdd() ? ClearCase.NMASTER
: ClearCase.NONE),
opListener);
monitor.worked(40);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
}
break;
case ClearCase.ERROR_BRANCH_IS_MASTERED_BY_REPLICA:
returnCode = showMessageDialog(
"Checkout",
"Resource could not be checked out since not your replica.\nDo you want change mastership?");
changeMastershipSequence(returnCode, targetElement,
opListener);
monitor.worked(40);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
break;
default:
result = new Status(
IStatus.ERROR,
ID,
TeamException.UNABLE,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.unknown"),
new Object[] { cce.getElements() }),
null);
break;
}
}
}
monitor.worked(20);
// update state of target element first (if symlink)
if (!targetElement.equals(cache)) {
targetElement.doUpdate();
}
// update state
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
}
private final class UnHijackOperation implements IRecursiveOperation {
public IStatus visit(final IResource resource,
final IProgressMonitor monitor) {
try {
monitor.beginTask("Checkin out " + resource.getFullPath(), 100);
// Sanity check - can't checkout something that is not part of
// clearcase
if (!isHijacked(resource))
return new Status(
IStatus.WARNING,
ID,
TeamException.NOT_AUTHORIZED,
MessageFormat
.format("Resource \"{0}\" is not a Hijacked ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
IStatus result = OK_STATUS;
try {
/* remove existing xx.keep file */
File keep = new File(resource.getLocation().toOSString()
+ ".keep");
if (keep.exists()) {
keep.delete();
}
/* rename existing xx.keep file */
keep = new File(resource.getLocation().toOSString());
if (keep.exists()) {
keep.renameTo(new File(resource.getLocation()
.toOSString() + ".keep"));
}
} catch (Exception e) {
result = FAILED_STATUS;
}
monitor.worked(20);
if (result == OK_STATUS) {
// update if necessary
if (ClearCasePreferences.isCheckoutLatest()
&& isSnapShot(resource)) {
monitor.subTask("Updating " + resource.getName());
update(resource.getLocation().toOSString(),
ClearCase.GRAPHICAL, false);
}
}
monitor.worked(20);
// update state
updateState(resource.getParent(), IResource.DEPTH_ONE,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
}
private final class UpdateOperation implements IIterativeOperation {
public IStatus visit(IResource resource, int depth,
IProgressMonitor monitor) {
try {
monitor.beginTask("Updating " + resource.getFullPath(), 100);
// Sanity check - can't update something that is not part of
// clearcase
if (!isClearCaseElement(resource))
return new Status(
IStatus.ERROR,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format("Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
IStatus result = OK_STATUS;
String element = resource.getLocation().toOSString();
ClearCasePlugin.getEngine().update(element, 0, false);
monitor.worked(40);
updateState(resource, IResource.DEPTH_INFINITE,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
}
private final class CheckoutUnreservedOperation implements
IIterativeOperation {
public IStatus visit(IResource resource, int depth,
IProgressMonitor monitor) {
try {
monitor.beginTask(
"Changing checkout to unreserved "
+ resource.getFullPath(), 100);
// Sanity check - can't update something that is not part of
// clearcase
if (!isClearCaseElement(resource))
return new Status(
IStatus.ERROR,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format("Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
IStatus result = OK_STATUS;
String element = resource.getLocation().toOSString();
ClearCasePlugin.getEngine().unreserved(
new String[] { element }, null, 0, opListener);
monitor.worked(40);
updateState(resource, IResource.DEPTH_INFINITE,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
}
private final class CheckoutReservedOperation implements
IIterativeOperation {
public IStatus visit(IResource resource, int depth,
IProgressMonitor monitor) {
try {
monitor.beginTask(
"Changing checkout to reserved "
+ resource.getFullPath(), 100);
// Sanity check - can't update something that is not part of
// clearcase
if (!isClearCaseElement(resource))
return new Status(
IStatus.ERROR,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format("Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
IStatus result = OK_STATUS;
String element = resource.getLocation().toOSString();
ClearCasePlugin.getEngine().reserved(new String[] { element },
null, 0, opListener);
monitor.worked(40);
updateState(resource, IResource.DEPTH_INFINITE,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
}
/**
* These interfaces are to operations that can be performed on the array of
* resources, and on all resources identified by the depth parameter.
*
* @see execute(IOperation, IResource[], int, IProgressMonitor)
*/
public static interface IOperation {
// empty
}
public static interface IIterativeOperation extends IOperation {
public IStatus visit(IResource resource, int depth,
IProgressMonitor progress);
}
public static interface IRecursiveOperation extends IOperation {
public IStatus visit(IResource resource, IProgressMonitor progress);
}
/**
* Perform the given operation on the array of resources, each to the
* specified depth. Throw an exception if a problem ocurs, otherwise remain
* silent.
*/
protected void execute(IOperation operation, IResource[] resources,
int depth, IProgressMonitor progress) throws TeamException {
if (null == progress) {
progress = new NullProgressMonitor();
}
// Create an array to hold the status for each resource.
MultiStatus multiStatus = new MultiStatus(getID(), TeamException.OK,
"OK", null);
// For each resource in the local resources array until we have errors.
try {
progress.beginTask("Processing", 1000 * resources.length);
for (int i = 0; i < resources.length
&& !multiStatus.matches(IStatus.ERROR); i++) {
progress.subTask(resources[i].getFullPath().toString());
if (!isIgnored(resources[i])) {
if (operation instanceof IRecursiveOperation) {
multiStatus.merge(execute(
(IRecursiveOperation) operation, resources[i],
depth, new SubProgressMonitor(progress, 1000)));
} else {
multiStatus
.merge(((IIterativeOperation) operation).visit(
resources[i], depth,
new SubProgressMonitor(progress, 1000)));
}
} else {
progress.worked(1000);
}
}
// Finally, if any problems occurred, throw the exeption with all
// the statuses,
// but if there were no problems exit silently.
if (!multiStatus.isOK()) {
String message = multiStatus.matches(IStatus.ERROR) ? "There were errors that prevent the requested operation from finishing successfully."
: "The requested operation finished with warnings.";
throw new TeamException(new MultiStatus(
multiStatus.getPlugin(), multiStatus.getCode(),
multiStatus.getChildren(), message,
multiStatus.getException()));
}
// Cause all the resource changes to be broadcast to listeners.
// TeamPlugin.getManager().broadcastResourceStateChanges(resources);
} finally {
progress.done();
}
}
/**
* Perform the given operation on a resource to the given depth.
*/
protected IStatus execute(IRecursiveOperation operation,
IResource resource, int depth, IProgressMonitor progress) {
if (null == progress) {
progress = new NullProgressMonitor();
}
try {
progress.beginTask("Processing", 1000);
// Visit the given resource first.
IStatus status = operation.visit(resource, new SubProgressMonitor(
progress, 200));
// If the resource is a file then the depth parameter is irrelevant.
if (resource.getType() == IResource.FILE)
return status;
// If we are not considering any members of the container then we
// are done.
if (depth == IResource.DEPTH_ZERO)
return status;
// If the operation was unsuccessful, do not attempt to go deep.
if (status.matches(IStatus.ERROR)) // if (!status.isOK())
return status;
// if operation was cancaled, do not go deep
if (CANCEL_STATUS == status)
return OK_STATUS;
// If the container has no children then we are done.
IResource[] members = getMembers(resource);
if (members.length == 0)
return status;
// There are children and we are going deep, the response will be a
// multi-status.
MultiStatus multiStatus = new MultiStatus(status.getPlugin(),
status.getCode(), status.getMessage(),
status.getException());
// The next level will be one less than the current level...
int childDepth = (depth == IResource.DEPTH_ONE) ? IResource.DEPTH_ZERO
: IResource.DEPTH_INFINITE;
// Collect the responses in the multistatus (use merge to flatten
// the tree).
int ticks = 800 / members.length;
for (int i = 0; i < members.length
&& !multiStatus.matches(IStatus.ERROR); i++) {
progress.subTask(members[i].getFullPath().toString());
if (!isIgnored(members[i])) {
multiStatus
.merge(execute(operation, members[i], childDepth,
new SubProgressMonitor(progress, ticks)));
} else {
progress.worked(ticks);
}
}
// correct the MultiStatus message
if (!multiStatus.isOK()) {
/*
* Remember: the multi status was created with "OK" as message!
* This is not meaningful anymore. We have to correct it.
*/
String message = multiStatus.matches(IStatus.ERROR) ? "There were errors that prevent the requested operation from finishing successfully."
: "The requested operation finished with warnings.";
multiStatus = new MultiStatus(multiStatus.getPlugin(),
multiStatus.getCode(), multiStatus.getChildren(),
message, multiStatus.getException());
}
return multiStatus;
} finally {
progress.done();
}
}
protected IResource[] getMembers(IResource resource) {
if (resource.getType() != IResource.FILE) {
try {
return ((IContainer) resource).members();
} catch (CoreException exception) {
exception.printStackTrace();
throw new RuntimeException();
}
} // end-if
else
return new IResource[0];
}
/**
* @see org.eclipse.team.core.RepositoryProvider#canHandleLinkedResources()
*/
@Override
public boolean canHandleLinkedResources() {
return true;
}
@Override
public boolean canHandleLinkedResourceURI() {
return true;
}
/**
* Used to prevent co of resources like .project, .cproject ..
*
* @param resource
* @return
*/
public boolean isPreventCheckout(IResource resource) {
String list_csv = ClearCasePreferences.isPreventCheckOut().trim()
.replaceAll(" ", "");
String[] preventCoElements = null;
if (list_csv != null && list_csv.length() > 0) {
if (!list_csv.endsWith(",")) {
preventCoElements = list_csv.split(",");
} else {
// no list just one file.
preventCoElements = new String[] { list_csv };
}
for (String element : preventCoElements) {
if (resource.getName().equals(element)) {
return true;
}
}
}
return false;
}
/**
* Indicates if a resource is ignored and not handled.
* <p>
* Resources are never ignored, if they have a remote resource.
* </p>
*
* @param resource
* @return
*/
public boolean isIgnored(IResource resource) {
// // ignore eclipse linked resource
// if (resource.isLinked()) {
// if (ClearCasePlugin.DEBUG_PROVIDER_IGNORED_RESOURCES) {
// ClearCasePlugin.trace(TRACE_ID_IS_IGNORED,
// "linked resource: " + resource); //$NON-NLS-1$
// }
// return true;
// }
// never ignore handled resources
if (isClearCaseElement(resource))
return false;
// never ignore workspace root
IResource parent = resource.getParent();
if (null == parent)
return false;
// check the global ignores from Team (includes derived resources)
if (Team.isIgnoredHint(resource)) {
if (ClearCasePlugin.DEBUG_PROVIDER_IGNORED_RESOURCES) {
ClearCasePlugin.trace(TRACE_ID_IS_IGNORED,
"ignore hint from team plug-in: " + resource); //$NON-NLS-1$
}
return true;
}
// never ignore uninitialized resources
if (isUnknownState(resource))
return false;
// ignore resources outside view
if (!isInsideView(resource)) {
if (ClearCasePlugin.DEBUG_PROVIDER_IGNORED_RESOURCES) {
ClearCasePlugin.trace(TRACE_ID_IS_IGNORED,
"outside view: " + resource); //$NON-NLS-1$
}
return true;
}
// bug 904248: do not ignore if parent is a linked resource
if (parent.isLinked())
return false;
// check the parent, if the parent is ignored
// then this resource is ignored also
return isIgnored(parent);
}
/**
* @param resource
* @return
*/
public boolean isSymbolicLink(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isSymbolicLink();
}
/**
* @param resource
* @return
*/
public boolean isSymbolicLinkTargetValid(IResource resource) {
return StateCacheFactory.getInstance().get(resource)
.isSymbolicLinkTargetValid();
}
/**
* @param resource
* @return
*/
public String getSymbolicLinkTarget(IResource resource) {
return StateCacheFactory.getInstance().get(resource)
.getSymbolicLinkTarget();
}
/**
* Indicates if the specified resource is edited (checked out) by someone
* else.
*
* @param childResource
* @return <code>true</code> if the specified resource is edited (checked
* out) by someone else, <code>false</code> otherwise
*/
public boolean isEdited(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isEdited();
}
/**
* Indicates if the specified resource is a view root directory containing
* vobs.
*
* @param resource
* @return <code>true</code> if the specified resource is a view root
* directory
*/
public boolean isViewRoot(IResource resource) {
/*
* todo: we need a better check for the view root; this only supports
* structures where a project is the view directory containing the vobs
*/
return null != resource && resource.getType() == IResource.PROJECT
&& !isClearCaseElement(resource);
}
/**
* Indicates if the specified resource is a vob root directory.
*
* @param resource
* @return <code>true</code> if the specified resource is a vob root
* directory
*/
public boolean isVobRoot(IResource resource) {
/*
* todo: we need a better check for the vob root; this only supports
* structures where a project is the view directory containing the vobs
*/
// return resource.getType() == IResource.FOLDER && !resource.isLinked()
// && isViewRoot(resource.getParent());
return false;
}
/**
* Indicates if the specified resource is inside a view directory.
*
* @param resource
* @return <code>true</code> if the specified resource is a view directory
*/
public boolean isInsideView(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isInsideView();
}
/**
* Get the StateCache for an element
*
* @param resource
* @return the corresponding StateCache
*/
public StateCache getCache(IResource resource) {
return StateCacheFactory.getInstance().get(resource);
}
/**
* Ensures the specified resource is initialized.
*
* @param resource
*/
public void ensureInitialized(IResource resource) {
StateCacheFactory.getInstance().ensureInitialized(resource);
}
/**
*
* Helper method that retrieves the branch name. Handles both win and unix
* versions.
*
* @param version
* @return
*/
private String getBranchName(String version) {
int firstBackSlash = 0;
int lastBackSlash = 0;
if (version.startsWith("\\")) {
// Win32
firstBackSlash = version.indexOf("\\");
lastBackSlash = version.lastIndexOf("\\");
} else {
// Unix
firstBackSlash = version.indexOf("/");
lastBackSlash = version.lastIndexOf("/");
}
return version.substring(firstBackSlash, lastBackSlash + 1);
}
private int getCheckoutType() {
if(ClearCasePreferences.isAskCoType()){
if(PreventCheckoutHelper.getcoUnresAnswer() == YES){
return ClearCase.UNRESERVED;
}else{
return ClearCase.RESERVED;
}
}else if (ClearCasePreferences.isReservedCheckoutsAlways())
return ClearCase.RESERVED;
else if (ClearCasePreferences.isReservedCheckoutsIfPossible())
return ClearCase.RESERVED_IF_POSSIBLE;
else
return ClearCase.UNRESERVED;
}
public void setOperationListener(OperationListener opListener) {
this.opListener = opListener;
}
/**
* For a given element, calculates the final CC element that a checkout/in
* operation can act on. If the given cache points to a regular file or
* directory element, it is returned verbatim. If it is a symlink, we try to
* resolve the symlink to the final element and return a StateCache for
* that.
*
* @param cache
* a valid StateCache which maybe points to a symlink
* @return the final CC element, no symlink. If the symlink can't be
* resolved in CC null is returned
*/
@SuppressWarnings("deprecation")
public StateCache getFinalTargetElement(StateCache cache) {
if (!cache.isSymbolicLink() || null == cache.getSymbolicLinkTarget())
return cache;
File target = new File(cache.getSymbolicLinkTarget());
if (!target.isAbsolute()) {
target = null != cache.getPath() ? new File(cache.getPath())
.getParentFile() : null;
if (null != target) {
target = new File(target, cache.getSymbolicLinkTarget());
}
}
if (null != target && target.exists()) {
IPath targetLocation = new Path(target.getAbsolutePath());
IResource[] resources = null;
if (target.isDirectory()) {
resources = ResourcesPlugin.getWorkspace().getRoot()
.findContainersForLocation(targetLocation);
} else {
resources = ResourcesPlugin.getWorkspace().getRoot()
.findFilesForLocation(targetLocation);
}
if (null != resources) {
for (int i = 0; i < resources.length; i++) {
IResource foundResource = resources[i];
ClearCaseProvider provider = ClearCaseProvider
.getClearCaseProvider(foundResource);
if (null != provider)
return StateCacheFactory.getInstance().get(
foundResource);
}
}
}
return null;
}
// FIXME: eraonel 20100503 move this to other file.
public static boolean moveDirRec(File fromDir, File toDir) {
if (!toDir.exists()) {
return fromDir.renameTo(toDir);
}
File[] files = fromDir.listFiles();
if (files == null) {
return false;
}
boolean success = true;
for (int i = 0; i < files.length; i++) {
File fromFile = files[i];
File toFile = new File(toDir, fromFile.getName());
success = success && fromFile.renameTo(toFile);
}
fromDir.delete();
return success;
}
/**
* Shows a message dialog where user can select: Yes=0 No=1 Cancel=2
*
* @param operationType
* @param msg
* @return result
*/
private int showMessageDialog(String operationType, String msg) {
DialogMessageRunnable dm = new DialogMessageRunnable(operationType, msg);
PlatformUI.getWorkbench().getDisplay().syncExec(dm);
return dm.getResult();
}
/**
* Request mastership and then checkout sequence.
*
* @param returnCode
* @param targetElement
* @param opListener
*/
private void changeMastershipSequence(int returnCode,
StateCache targetElement, OperationListener opListener) {
if (returnCode == 0) {
// Request mastership
ClearCaseElementState[] cces = ClearCasePlugin
.getEngine()
.requestMastership(targetElement.getPath(), getComment(), 0);
if (cces[0].state == ClearCase.MASTERSHIP_CHANGED) {
// Now possible to checkout.
ClearCasePlugin.getEngine().checkout(
new String[] { targetElement.getPath() },
getComment(),
getCheckoutType() | ClearCase.PTIME
| ClearCase.UNRESERVED | ClearCase.NMASTER,
opListener);
}
}
}
public void copyVersionIntoSnapShot(String destinationPath,
String versionToCopy) {
HashMap<Integer, String> args = new HashMap<Integer, String>();
args.put(Integer.valueOf(ClearCase.TO), destinationPath);
ClearCasePlugin.getEngine().get(ClearCase.TO, args, versionToCopy);
}
/**
* Method is used for a rename refactoring when the file to be renamed have
* been checkedout. When the file is checked out in another view and the
* user don't want to proceed we cancel checkout and return fail status.
* This is due to undo operation is not working.
*
* @param resource
* @param monitor
* @param opListener
* @return
*/
private IStatus cancelCheckout(IResource resource,
IProgressMonitor monitor, OperationListener opListener) {
// uncheckout since we do not want to checkout.
ClearCasePlugin.getEngine().uncheckout(
new String[] { resource.getLocation().toOSString() },
ClearCase.NONE, opListener);
updateState(resource, IResource.DEPTH_ZERO, new SubProgressMonitor(
monitor, 10));
return new Status(IStatus.ERROR, ID, TeamException.CONFLICT,
MessageFormat.format("Cancelled move operation for \"{0}\"!",
new Object[] { resource.getFullPath().toString() }),
null);
}
}
| true | true | public IStatus visit(IResource resource, IProgressMonitor monitor) {
try {
int returnCode = 1;// Used in messge dialog.
monitor.beginTask("Checkin in " + resource.getFullPath(), 100);
StateCache cache = getCache(resource);
final StateCache targetElement = getFinalTargetElement(cache);
IStatus result = OK_STATUS;
// Sanity check - can't check in something that is not part of
// clearcase
if (targetElement == null
|| !targetElement.isClearCaseElement())
return new Status(
IStatus.WARNING,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format("Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
// Sanity check - can't checkin something that is not checked
// out
if (!targetElement.isCheckedOut())
// return status with severity OK
return new Status(IStatus.OK, ID,
TeamException.NOT_CHECKED_OUT,
MessageFormat.format(
"Resource \"{0}\" is not checked out!",
new Object[] { targetElement.getPath() }),
null);
if (ClearCasePreferences.isCheckinIdenticalAllowed()) {
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement.getPath() },
getComment(),
ClearCase.PTIME | ClearCase.IDENTICAL, opListener);
} else {
try {
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement.getPath() },
getComment(), ClearCase.PTIME, opListener);
} catch (ClearCaseException cce) {
// check error
switch (cce.getErrorCode()) {
case ClearCase.ERROR_PREDECESSOR_IS_IDENTICAL:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.identicalPredecessor"),
new Object[] { cce.getElements() }),
null);
break;
case ClearCase.ERROR_ELEMENT_HAS_CHECKOUTS:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.elementHasCheckouts"),
new Object[] { cce.getElements() }),
null);
break;
case ClearCase.ERROR_MOST_RECENT_NOT_PREDECESSOR_OF_THIS_VERSION:
// Only support for: To merge the latest version
// with your checkout
// getVersion --> \branch\CHECKEDOUT.
String branchName = getBranchName(getVersion(resource));
String latestVersion = resource.getLocation()
.toOSString()
+ "@@"
+ branchName
+ "LATEST";
ClearCaseElementState myState = ClearCasePlugin
.getEngine().merge(targetElement.getPath(),
new String[] { latestVersion },
ClearCase.GRAPHICAL);
if (myState.isMerged()) {
returnCode = showMessageDialog("Checkin",
"Do you want to checkin the merged result?");
if (returnCode == 0) {
// Yes continue checkin
ClearCasePlugin
.getEngine()
.checkin(
new String[] { targetElement
.getPath() },
getComment(),
ClearCase.PTIME, opListener);
}
} else {
result = new Status(
IStatus.ERROR,
ID,
TeamException.CONFLICT,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.mergeLatestProblem"),
new Object[] { cce
.getElements() }), null);
}
break;
default:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.unknown"),
new Object[] { cce.getElements() }),
null);
break;
}
}
}
monitor.worked(40);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
| public IStatus visit(IResource resource, IProgressMonitor monitor) {
try {
int returnCode = 1;// Used in messge dialog.
monitor.beginTask("Checkin in " + resource.getFullPath(), 100);
StateCache cache = getCache(resource);
final StateCache targetElement = getFinalTargetElement(cache);
IStatus result = OK_STATUS;
// Sanity check - can't check in something that is not part of
// clearcase
if (targetElement == null
|| !targetElement.isClearCaseElement())
return new Status(
IStatus.WARNING,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format("Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
// Sanity check - can't checkin something that is not checked
// out
if (!targetElement.isCheckedOut())
// return status with severity OK
return new Status(IStatus.OK, ID,
TeamException.NOT_CHECKED_OUT,
MessageFormat.format(
"Resource \"{0}\" is not checked out!",
new Object[] { targetElement.getPath() }),
null);
if (ClearCasePreferences.isCheckinIdenticalAllowed()) {
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement.getPath() },
getComment(),
ClearCase.PTIME | ClearCase.IDENTICAL, opListener);
} else {
try {
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement.getPath() },
getComment(), ClearCase.PTIME, opListener);
} catch (ClearCaseException cce) {
// check error
switch (cce.getErrorCode()) {
case ClearCase.ERROR_PREDECESSOR_IS_IDENTICAL:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.identicalPredecessor"),
new Object[] { cce.getElements() }),
null);
break;
case ClearCase.ERROR_ELEMENT_HAS_CHECKOUTS:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.elementHasCheckouts"),
new Object[] { cce.getElements() }),
null);
break;
case ClearCase.ERROR_MOST_RECENT_NOT_PREDECESSOR_OF_THIS_VERSION:
// Only support for: To merge the latest version
// with your checkout
// getVersion --> \branch\CHECKEDOUT.
String branchName = getBranchName(getVersion(resource));
String latestVersion = resource.getLocation()
.toOSString()
+ "@@"
+ branchName
+ "LATEST";
ClearCaseElementState myState = ClearCasePlugin
.getEngine().merge(targetElement.getPath(),
new String[] { latestVersion },null,
ClearCase.GRAPHICAL);
if (myState.isMerged()) {
returnCode = showMessageDialog("Checkin",
"Do you want to checkin the merged result?");
if (returnCode == 0) {
// Yes continue checkin
ClearCasePlugin
.getEngine()
.checkin(
new String[] { targetElement
.getPath() },
getComment(),
ClearCase.PTIME, opListener);
}
} else {
result = new Status(
IStatus.ERROR,
ID,
TeamException.CONFLICT,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.mergeLatestProblem"),
new Object[] { cce
.getElements() }), null);
}
break;
default:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat.format(
Messages.getString("ClearCasePlugin.error.checkin.unknown"),
new Object[] { cce.getElements() }),
null);
break;
}
}
}
monitor.worked(40);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
|
diff --git a/src/mitzi/MitziBrain.java b/src/mitzi/MitziBrain.java
index ad40947..097ce1a 100644
--- a/src/mitzi/MitziBrain.java
+++ b/src/mitzi/MitziBrain.java
@@ -1,282 +1,287 @@
package mitzi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import static mitzi.MateScores.*;
import mitzi.UCIReporter.InfoType;
public class MitziBrain implements IBrain {
private IBoard board;
private Variation principal_variation;
private long eval_counter;
private IBoardAnalyzer board_analyzer = new BasicBoardAnalyzer();
@Override
public void set(IBoard board) {
this.board = board;
this.eval_counter = 0;
this.principal_variation = null;
}
/**
* Sends updates about evaluation status to UCI GUI.
*
*/
class UCIUpdater extends TimerTask {
private long old_mtime;
private long old_eval_counter;
@Override
public void run() {
long mtime = System.currentTimeMillis();
long eval_span = eval_counter - old_eval_counter;
if (old_mtime != 0) {
long time_span = mtime - old_mtime;
UCIReporter.sendInfoNum(InfoType.NPS, eval_span * 1000
/ time_span);
}
old_mtime = mtime;
old_eval_counter += eval_span;
}
}
/**
* NegaMax with Alpha Beta Pruning
*
* @see <a
* href="https://en.wikipedia.org/wiki/Negamax#NegaMax_with_Alpha_Beta_Pruning">NegaMax
* with Alpha Beta Pruning</a>
* @param board
* the current board
* @param total_depth
* the total depth to search
* @param depth
* the remaining depth to search
* @param alpha
* @param beta
* @return returns a Variation tree
*/
private Variation evalBoard(IBoard board, int total_depth, int depth,
int alpha, int beta, Variation old_tree) {
// whose move is it?
Side side = board.getActiveColor();
int side_sign = Side.getSideSign(side);
// generate moves
Set<IMove> moves = board.getPossibleMoves();
// check for mate and stalemate (the side should alternate)
if (moves.isEmpty()) {
Variation base_variation;
if (board.isCheckPosition()) {
base_variation = new Variation(null, NEG_INF * side_sign,
Side.getOppositeSide(side));
} else {
base_variation = new Variation(null, 0,
Side.getOppositeSide(side));
}
eval_counter++;
return base_variation;
}
// base case (the side should alternate)
if (depth == 0) {
AnalysisResult result = board_analyzer.eval0(board);
Variation base_variation = new Variation(null, result.getScore(),
Side.getOppositeSide(side));
eval_counter++;
return base_variation;
}
int best_value = NEG_INF; // this starts always at negative!
// Sort the moves:
BasicMoveComparator move_comparator = new BasicMoveComparator(board);
ArrayList<IMove> ordered_moves;
ArrayList<Variation> ordered_variations = null;
if (old_tree == null || old_tree.getSubVariations().isEmpty()) {
// no previous computation given, use basic heuristic
ordered_moves = new ArrayList<IMove>(moves);
- Collections.sort(ordered_moves, move_comparator);
+ Collections.sort(ordered_moves,
+ Collections.reverseOrder(move_comparator));
} else {
// use old Variation tree for ordering
Set<Variation> children = old_tree.getSubVariations();
ordered_variations = new ArrayList<Variation>(children);
- Collections.sort(ordered_variations);
- if (side == Side.WHITE)
- Collections.reverse(ordered_variations);
+ if (side == Side.BLACK)
+ Collections.sort(ordered_variations);
+ else
+ Collections
+ .sort(ordered_variations, Collections.reverseOrder());
ordered_moves = new ArrayList<IMove>();
for (Variation var : ordered_variations) {
ordered_moves.add(var.getMove());
}
// add remaining moves in basic heuristic order
- ArrayList<IMove> basic_ordered_moves = new ArrayList<IMove>();
+ ArrayList<IMove> remaining_moves = new ArrayList<IMove>();
for (IMove move : moves) {
if (!ordered_moves.contains(move))
- basic_ordered_moves.add(move);
+ remaining_moves.add(move);
}
- Collections.sort(basic_ordered_moves, move_comparator);
- ordered_moves.addAll(basic_ordered_moves);
+ Collections.sort(remaining_moves,
+ Collections.reverseOrder(move_comparator));
+ ordered_moves.addAll(remaining_moves);
}
+ UCIReporter.sendInfoString(ordered_moves.toString());
// create new parent Variation
Variation parent = new Variation(null, NEG_INF,
Side.getOppositeSide(side));
int i = 0;
// alpha beta search
for (IMove move : ordered_moves) {
if (depth == total_depth && total_depth >= 6) {
// output currently searched move to UCI
UCIReporter.sendInfoCurrMove(move, i + 1);
}
Variation variation;
if (ordered_variations != null && i < ordered_variations.size()) {
variation = evalBoard(board.doMove(move), total_depth,
depth - 1, -beta, -alpha, ordered_variations.get(i));
} else {
variation = evalBoard(board.doMove(move), total_depth,
depth - 1, -beta, -alpha);
}
int negaval = variation.getValue() * side_sign;
// better variation found
if (negaval >= best_value) {
boolean truly_better = negaval > best_value;
best_value = negaval;
// update variation tree
parent.update(null, variation.getValue());
// update the missing move for the child
variation.update(move, variation.getValue());
parent.addSubVariation(variation);
// output to UCI
if (depth == total_depth && truly_better) {
principal_variation = parent.getPrincipalVariation();
UCIReporter.sendInfoPV(principal_variation, total_depth,
variation.getValue(), board.getActiveColor());
}
}
// alpha beta cutoff
alpha = Math.max(alpha, negaval);
if (alpha >= beta)
break;
i++; // keep ordered_moves and ordered_variations in sync
}
return parent;
}
private Variation evalBoard(IBoard board, int total_depth, int depth,
int alpha, int beta) {
return evalBoard(board, total_depth, depth, alpha, beta, null);
}
@Override
public IMove search(int movetime, int maxMoveTime, int searchDepth,
boolean infinite, Set<IMove> searchMoves) {
// first of all, ignoring the timings and restriction to certain
// moves...
Timer timer = new Timer();
timer.scheduleAtFixedRate(new UCIUpdater(), 1000, 5000);
// iterative deepening
Variation var_tree = null; // TODO: use previous searches as starting
// point
Variation var_tree_temp;
// Parameters for aspiration windows
int alpha = NEG_INF; // initial value
int beta = POS_INF; // initial value
int asp_window = 200; // often 50 or 25 is used
int factor = 3; // factor for increasing if out of bounds
for (int current_depth = 1; current_depth < searchDepth; current_depth++) {
this.principal_variation = null;
var_tree_temp = evalBoard(board, current_depth, current_depth,
alpha, beta, var_tree);
// mate found
if (principal_variation != null
&& principal_variation.getValue() == POS_INF
&& board.getActiveColor() == Side.WHITE
|| principal_variation.getValue() == NEG_INF
&& board.getActiveColor() == Side.BLACK) {
timer.cancel();
return principal_variation.getMove();
}
// If Value is out of bounds, redo search with larger bounds, but
// with the same variation tree
if (var_tree_temp.getValue() <= alpha) {
alpha -= factor * asp_window;
current_depth--;
continue;
} else if (var_tree_temp.getValue() >= beta) {
beta += factor * asp_window;
current_depth--;
continue;
}
alpha = var_tree_temp.getValue() - asp_window;
beta = var_tree_temp.getValue() + asp_window;
var_tree = var_tree_temp;
}
// repeat until a value inside the alpha-beta bound is found.
while (true) {
this.principal_variation = null;
var_tree_temp = evalBoard(board, searchDepth, searchDepth, alpha,
beta, var_tree);
if (var_tree_temp.getValue() <= alpha) {
alpha -= factor * asp_window;
} else if (var_tree_temp.getValue() >= beta) {
beta += factor * asp_window;
} else {
var_tree = var_tree_temp;
break;
}
}
timer.cancel();
if (principal_variation != null) {
return principal_variation.getMove();
} else {
// mitzi cannot avoid mate :(
return var_tree.getBestMove();
}
}
@Override
public IMove stop() {
// TODO Auto-generated method stub
return null;
}
}
| false | true | private Variation evalBoard(IBoard board, int total_depth, int depth,
int alpha, int beta, Variation old_tree) {
// whose move is it?
Side side = board.getActiveColor();
int side_sign = Side.getSideSign(side);
// generate moves
Set<IMove> moves = board.getPossibleMoves();
// check for mate and stalemate (the side should alternate)
if (moves.isEmpty()) {
Variation base_variation;
if (board.isCheckPosition()) {
base_variation = new Variation(null, NEG_INF * side_sign,
Side.getOppositeSide(side));
} else {
base_variation = new Variation(null, 0,
Side.getOppositeSide(side));
}
eval_counter++;
return base_variation;
}
// base case (the side should alternate)
if (depth == 0) {
AnalysisResult result = board_analyzer.eval0(board);
Variation base_variation = new Variation(null, result.getScore(),
Side.getOppositeSide(side));
eval_counter++;
return base_variation;
}
int best_value = NEG_INF; // this starts always at negative!
// Sort the moves:
BasicMoveComparator move_comparator = new BasicMoveComparator(board);
ArrayList<IMove> ordered_moves;
ArrayList<Variation> ordered_variations = null;
if (old_tree == null || old_tree.getSubVariations().isEmpty()) {
// no previous computation given, use basic heuristic
ordered_moves = new ArrayList<IMove>(moves);
Collections.sort(ordered_moves, move_comparator);
} else {
// use old Variation tree for ordering
Set<Variation> children = old_tree.getSubVariations();
ordered_variations = new ArrayList<Variation>(children);
Collections.sort(ordered_variations);
if (side == Side.WHITE)
Collections.reverse(ordered_variations);
ordered_moves = new ArrayList<IMove>();
for (Variation var : ordered_variations) {
ordered_moves.add(var.getMove());
}
// add remaining moves in basic heuristic order
ArrayList<IMove> basic_ordered_moves = new ArrayList<IMove>();
for (IMove move : moves) {
if (!ordered_moves.contains(move))
basic_ordered_moves.add(move);
}
Collections.sort(basic_ordered_moves, move_comparator);
ordered_moves.addAll(basic_ordered_moves);
}
// create new parent Variation
Variation parent = new Variation(null, NEG_INF,
Side.getOppositeSide(side));
int i = 0;
// alpha beta search
for (IMove move : ordered_moves) {
if (depth == total_depth && total_depth >= 6) {
// output currently searched move to UCI
UCIReporter.sendInfoCurrMove(move, i + 1);
}
Variation variation;
if (ordered_variations != null && i < ordered_variations.size()) {
variation = evalBoard(board.doMove(move), total_depth,
depth - 1, -beta, -alpha, ordered_variations.get(i));
} else {
variation = evalBoard(board.doMove(move), total_depth,
depth - 1, -beta, -alpha);
}
int negaval = variation.getValue() * side_sign;
// better variation found
if (negaval >= best_value) {
boolean truly_better = negaval > best_value;
best_value = negaval;
// update variation tree
parent.update(null, variation.getValue());
// update the missing move for the child
variation.update(move, variation.getValue());
parent.addSubVariation(variation);
// output to UCI
if (depth == total_depth && truly_better) {
principal_variation = parent.getPrincipalVariation();
UCIReporter.sendInfoPV(principal_variation, total_depth,
variation.getValue(), board.getActiveColor());
}
}
// alpha beta cutoff
alpha = Math.max(alpha, negaval);
if (alpha >= beta)
break;
i++; // keep ordered_moves and ordered_variations in sync
}
return parent;
}
| private Variation evalBoard(IBoard board, int total_depth, int depth,
int alpha, int beta, Variation old_tree) {
// whose move is it?
Side side = board.getActiveColor();
int side_sign = Side.getSideSign(side);
// generate moves
Set<IMove> moves = board.getPossibleMoves();
// check for mate and stalemate (the side should alternate)
if (moves.isEmpty()) {
Variation base_variation;
if (board.isCheckPosition()) {
base_variation = new Variation(null, NEG_INF * side_sign,
Side.getOppositeSide(side));
} else {
base_variation = new Variation(null, 0,
Side.getOppositeSide(side));
}
eval_counter++;
return base_variation;
}
// base case (the side should alternate)
if (depth == 0) {
AnalysisResult result = board_analyzer.eval0(board);
Variation base_variation = new Variation(null, result.getScore(),
Side.getOppositeSide(side));
eval_counter++;
return base_variation;
}
int best_value = NEG_INF; // this starts always at negative!
// Sort the moves:
BasicMoveComparator move_comparator = new BasicMoveComparator(board);
ArrayList<IMove> ordered_moves;
ArrayList<Variation> ordered_variations = null;
if (old_tree == null || old_tree.getSubVariations().isEmpty()) {
// no previous computation given, use basic heuristic
ordered_moves = new ArrayList<IMove>(moves);
Collections.sort(ordered_moves,
Collections.reverseOrder(move_comparator));
} else {
// use old Variation tree for ordering
Set<Variation> children = old_tree.getSubVariations();
ordered_variations = new ArrayList<Variation>(children);
if (side == Side.BLACK)
Collections.sort(ordered_variations);
else
Collections
.sort(ordered_variations, Collections.reverseOrder());
ordered_moves = new ArrayList<IMove>();
for (Variation var : ordered_variations) {
ordered_moves.add(var.getMove());
}
// add remaining moves in basic heuristic order
ArrayList<IMove> remaining_moves = new ArrayList<IMove>();
for (IMove move : moves) {
if (!ordered_moves.contains(move))
remaining_moves.add(move);
}
Collections.sort(remaining_moves,
Collections.reverseOrder(move_comparator));
ordered_moves.addAll(remaining_moves);
}
UCIReporter.sendInfoString(ordered_moves.toString());
// create new parent Variation
Variation parent = new Variation(null, NEG_INF,
Side.getOppositeSide(side));
int i = 0;
// alpha beta search
for (IMove move : ordered_moves) {
if (depth == total_depth && total_depth >= 6) {
// output currently searched move to UCI
UCIReporter.sendInfoCurrMove(move, i + 1);
}
Variation variation;
if (ordered_variations != null && i < ordered_variations.size()) {
variation = evalBoard(board.doMove(move), total_depth,
depth - 1, -beta, -alpha, ordered_variations.get(i));
} else {
variation = evalBoard(board.doMove(move), total_depth,
depth - 1, -beta, -alpha);
}
int negaval = variation.getValue() * side_sign;
// better variation found
if (negaval >= best_value) {
boolean truly_better = negaval > best_value;
best_value = negaval;
// update variation tree
parent.update(null, variation.getValue());
// update the missing move for the child
variation.update(move, variation.getValue());
parent.addSubVariation(variation);
// output to UCI
if (depth == total_depth && truly_better) {
principal_variation = parent.getPrincipalVariation();
UCIReporter.sendInfoPV(principal_variation, total_depth,
variation.getValue(), board.getActiveColor());
}
}
// alpha beta cutoff
alpha = Math.max(alpha, negaval);
if (alpha >= beta)
break;
i++; // keep ordered_moves and ordered_variations in sync
}
return parent;
}
|
diff --git a/src/org/openstreetmap/josm/actions/mapmode/AddNodeAction.java b/src/org/openstreetmap/josm/actions/mapmode/AddNodeAction.java
index 2274d59c..1cf90f7e 100644
--- a/src/org/openstreetmap/josm/actions/mapmode/AddNodeAction.java
+++ b/src/org/openstreetmap/josm/actions/mapmode/AddNodeAction.java
@@ -1,243 +1,241 @@
// License: GPL. Copyright 2007 by Immanuel Scholz and others
package org.openstreetmap.josm.actions.mapmode;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.Cursor;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.actions.GroupAction;
import org.openstreetmap.josm.command.AddCommand;
import org.openstreetmap.josm.command.ChangeCommand;
import org.openstreetmap.josm.command.Command;
import org.openstreetmap.josm.command.SequenceCommand;
import org.openstreetmap.josm.data.coor.EastNorth;
import org.openstreetmap.josm.data.osm.Node;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.Way;
import org.openstreetmap.josm.data.osm.WaySegment;
import org.openstreetmap.josm.gui.MapFrame;
import org.openstreetmap.josm.tools.ImageProvider;
/**
* This mode adds a new node to the dataset. The user clicks on a place to add
* and there is it. Nothing more, nothing less.
*
* FIXME: "nothing more, nothing less" is a bit out-of-date
*
* Newly created nodes are selected. Shift modifier does not cancel the old
* selection as usual.
*
* @author imi
*
*/
public class AddNodeAction extends MapMode {
enum Mode {node, nodeway, autonode}
private final Mode mode;
public static class AddNodeGroup extends GroupAction {
public AddNodeGroup(MapFrame mf) {
super(KeyEvent.VK_N,0);
putValue("help", "Action/AddNode");
actions.add(new AddNodeAction(mf,tr("Add node"), Mode.node, tr("Add a new node to the map")));
actions.add(new AddNodeAction(mf, tr("Add node into way"), Mode.nodeway,tr( "Add a node into an existing way")));
actions.add(new AddNodeAction(mf, tr("Add node and connect"), Mode.autonode,tr( "Add a node and connect it to the selected node (with CTRL: add node into way; with SHIFT: re-use existing node)")));
setCurrent(0);
}
}
public AddNodeAction(MapFrame mapFrame, String name, Mode mode, String desc) {
super(name, "node/"+mode, desc, mapFrame, getCursor());
this.mode = mode;
putValue("help", "Action/AddNode/"+Character.toUpperCase(mode.toString().charAt(0))+mode.toString().substring(1));
}
private static Cursor getCursor() {
try {
return ImageProvider.getCursor("crosshair", null);
} catch (Exception e) {
}
return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
}
@Override public void enterMode() {
super.enterMode();
Main.map.mapView.addMouseListener(this);
}
@Override public void exitMode() {
super.exitMode();
Main.map.mapView.removeMouseListener(this);
}
/**
* If user clicked with the left button, add a node at the current mouse
* position.
*
* If in nodeway mode, insert the node into the way.
*/
@Override public void mouseClicked(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1)
return;
Node n = new Node(Main.map.mapView.getLatLon(e.getX(), e.getY()));
if (n.coor.isOutSideWorld()) {
JOptionPane.showMessageDialog(Main.parent,tr("Cannot add a node outside of the world."));
return;
}
Command c = new AddCommand(n);
if (mode == Mode.nodeway) {
WaySegment ws = Main.map.mapView.getNearestWaySegment(e.getPoint());
if (ws == null)
return;
// see if another segment is also near
WaySegment other = Main.map.mapView.getNearestWaySegment(e.getPoint(),
Collections.singleton(ws));
Node n1 = ws.way.nodes.get(ws.lowerIndex),
n2 = ws.way.nodes.get(ws.lowerIndex + 1);
if (other == null && (e.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) == 0) {
// moving the new point to the perpendicular point
// FIXME: when two way segments are split, should move the new point to the
// intersection point!
EastNorth A = n1.eastNorth;
EastNorth B = n2.eastNorth;
double ab = A.distance(B);
double nb = n.eastNorth.distance(B);
double na = n.eastNorth.distance(A);
double q = (nb-na+ab)/ab/2;
n.eastNorth = new EastNorth(B.east() + q*(A.east()-B.east()), B.north() + q*(A.north()-B.north()));
n.coor = Main.proj.eastNorth2latlon(n.eastNorth);
}
Collection<Command> cmds = new LinkedList<Command>();
cmds.add(c);
// split the first segment
splitWaySegmentAtNode(ws, n, cmds);
// if a second segment was found, split that as well
if (other != null) splitWaySegmentAtNode(other, n, cmds);
c = new SequenceCommand(tr((other == null) ?
"Add node into way" : "Add common node into two ways"), cmds);
}
// Add a node and connecting segment.
if (mode == Mode.autonode) {
WaySegment insertInto = null;
Node reuseNode = null;
// If CTRL is held, insert the node into a potentially existing way segment
if ((e.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) != 0) {
insertInto = Main.map.mapView.getNearestWaySegment(e.getPoint());
if (insertInto == null) System.err.println("Couldn't find nearby way segment");
if (insertInto == null)
return;
}
// If SHIFT is held, instead of creating a new node, re-use an existing
// node (making this action identical to AddSegmentAction with the
// small difference that the node used will then be selected to allow
// continuation of the "add node and connect" stuff)
else if ((e.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0) {
OsmPrimitive clicked = Main.map.mapView.getNearest(e.getPoint());
if (clicked == null || !(clicked instanceof Node))
return;
reuseNode = (Node) clicked;
}
Collection<OsmPrimitive> selection = Main.ds.getSelected();
if (selection.size() == 1 && selection.iterator().next() instanceof Node) {
Node n1 = (Node)selection.iterator().next();
Collection<Command> cmds = new LinkedList<Command>();
if (reuseNode != null) {
// in re-use node mode, n1 must not be identical to clicked node
if (n1 == reuseNode) System.err.println("n1 == reuseNode");
if (n1 == reuseNode) return;
// replace newly created node with existing node
n = reuseNode;
} else {
// only add the node creation command if we're not re-using
cmds.add(c);
}
/* Keep track of the way we change, it might be the same into
* which we insert the node.
*/
- Way newInsertInto = null;
+ Way wayInsertedInto = null;
if (insertInto != null)
- newInsertInto = splitWaySegmentAtNode(insertInto, n, cmds);
+ wayInsertedInto = splitWaySegmentAtNode(insertInto, n, cmds);
Way way = getWayForNode(n1);
if (way == null) {
way = new Way();
way.nodes.add(n1);
cmds.add(new AddCommand(way));
} else {
- if (insertInto != null) {
- if (way == insertInto.way) {
- way = newInsertInto;
- }
+ if (insertInto != null && way == insertInto.way) {
+ way = wayInsertedInto;
} else {
Way wnew = new Way(way);
cmds.add(new ChangeCommand(way, wnew));
way = wnew;
}
}
if (way.nodes.get(way.nodes.size() - 1) == n1) {
way.nodes.add(n);
} else {
way.nodes.add(0, n);
}
c = new SequenceCommand(tr((insertInto == null) ? "Add node and connect" : "Add node into way and connect"), cmds);
}
}
Main.main.undoRedo.add(c);
Main.ds.setSelected(n);
Main.map.mapView.repaint();
}
/**
* @return If the node is the end of exactly one way, return this.
* <code>null</code> otherwise.
*/
private Way getWayForNode(Node n) {
Way way = null;
for (Way w : Main.ds.ways) {
if (w.nodes.size() < 1) continue;
int i = w.nodes.indexOf(n);
if (w.nodes.get(0) == n || w.nodes.get(w.nodes.size() - 1) == n) {
if (way != null)
return null;
way = w;
}
}
return way;
}
private Way splitWaySegmentAtNode(WaySegment ws, Node n, Collection<Command> cmds) {
Way wnew = new Way(ws.way);
wnew.nodes.add(ws.lowerIndex + 1, n);
cmds.add(new ChangeCommand(ws.way, wnew));
return wnew;
}
}
| false | true | @Override public void mouseClicked(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1)
return;
Node n = new Node(Main.map.mapView.getLatLon(e.getX(), e.getY()));
if (n.coor.isOutSideWorld()) {
JOptionPane.showMessageDialog(Main.parent,tr("Cannot add a node outside of the world."));
return;
}
Command c = new AddCommand(n);
if (mode == Mode.nodeway) {
WaySegment ws = Main.map.mapView.getNearestWaySegment(e.getPoint());
if (ws == null)
return;
// see if another segment is also near
WaySegment other = Main.map.mapView.getNearestWaySegment(e.getPoint(),
Collections.singleton(ws));
Node n1 = ws.way.nodes.get(ws.lowerIndex),
n2 = ws.way.nodes.get(ws.lowerIndex + 1);
if (other == null && (e.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) == 0) {
// moving the new point to the perpendicular point
// FIXME: when two way segments are split, should move the new point to the
// intersection point!
EastNorth A = n1.eastNorth;
EastNorth B = n2.eastNorth;
double ab = A.distance(B);
double nb = n.eastNorth.distance(B);
double na = n.eastNorth.distance(A);
double q = (nb-na+ab)/ab/2;
n.eastNorth = new EastNorth(B.east() + q*(A.east()-B.east()), B.north() + q*(A.north()-B.north()));
n.coor = Main.proj.eastNorth2latlon(n.eastNorth);
}
Collection<Command> cmds = new LinkedList<Command>();
cmds.add(c);
// split the first segment
splitWaySegmentAtNode(ws, n, cmds);
// if a second segment was found, split that as well
if (other != null) splitWaySegmentAtNode(other, n, cmds);
c = new SequenceCommand(tr((other == null) ?
"Add node into way" : "Add common node into two ways"), cmds);
}
// Add a node and connecting segment.
if (mode == Mode.autonode) {
WaySegment insertInto = null;
Node reuseNode = null;
// If CTRL is held, insert the node into a potentially existing way segment
if ((e.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) != 0) {
insertInto = Main.map.mapView.getNearestWaySegment(e.getPoint());
if (insertInto == null) System.err.println("Couldn't find nearby way segment");
if (insertInto == null)
return;
}
// If SHIFT is held, instead of creating a new node, re-use an existing
// node (making this action identical to AddSegmentAction with the
// small difference that the node used will then be selected to allow
// continuation of the "add node and connect" stuff)
else if ((e.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0) {
OsmPrimitive clicked = Main.map.mapView.getNearest(e.getPoint());
if (clicked == null || !(clicked instanceof Node))
return;
reuseNode = (Node) clicked;
}
Collection<OsmPrimitive> selection = Main.ds.getSelected();
if (selection.size() == 1 && selection.iterator().next() instanceof Node) {
Node n1 = (Node)selection.iterator().next();
Collection<Command> cmds = new LinkedList<Command>();
if (reuseNode != null) {
// in re-use node mode, n1 must not be identical to clicked node
if (n1 == reuseNode) System.err.println("n1 == reuseNode");
if (n1 == reuseNode) return;
// replace newly created node with existing node
n = reuseNode;
} else {
// only add the node creation command if we're not re-using
cmds.add(c);
}
/* Keep track of the way we change, it might be the same into
* which we insert the node.
*/
Way newInsertInto = null;
if (insertInto != null)
newInsertInto = splitWaySegmentAtNode(insertInto, n, cmds);
Way way = getWayForNode(n1);
if (way == null) {
way = new Way();
way.nodes.add(n1);
cmds.add(new AddCommand(way));
} else {
if (insertInto != null) {
if (way == insertInto.way) {
way = newInsertInto;
}
} else {
Way wnew = new Way(way);
cmds.add(new ChangeCommand(way, wnew));
way = wnew;
}
}
if (way.nodes.get(way.nodes.size() - 1) == n1) {
way.nodes.add(n);
} else {
way.nodes.add(0, n);
}
c = new SequenceCommand(tr((insertInto == null) ? "Add node and connect" : "Add node into way and connect"), cmds);
}
}
Main.main.undoRedo.add(c);
Main.ds.setSelected(n);
Main.map.mapView.repaint();
}
| @Override public void mouseClicked(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1)
return;
Node n = new Node(Main.map.mapView.getLatLon(e.getX(), e.getY()));
if (n.coor.isOutSideWorld()) {
JOptionPane.showMessageDialog(Main.parent,tr("Cannot add a node outside of the world."));
return;
}
Command c = new AddCommand(n);
if (mode == Mode.nodeway) {
WaySegment ws = Main.map.mapView.getNearestWaySegment(e.getPoint());
if (ws == null)
return;
// see if another segment is also near
WaySegment other = Main.map.mapView.getNearestWaySegment(e.getPoint(),
Collections.singleton(ws));
Node n1 = ws.way.nodes.get(ws.lowerIndex),
n2 = ws.way.nodes.get(ws.lowerIndex + 1);
if (other == null && (e.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) == 0) {
// moving the new point to the perpendicular point
// FIXME: when two way segments are split, should move the new point to the
// intersection point!
EastNorth A = n1.eastNorth;
EastNorth B = n2.eastNorth;
double ab = A.distance(B);
double nb = n.eastNorth.distance(B);
double na = n.eastNorth.distance(A);
double q = (nb-na+ab)/ab/2;
n.eastNorth = new EastNorth(B.east() + q*(A.east()-B.east()), B.north() + q*(A.north()-B.north()));
n.coor = Main.proj.eastNorth2latlon(n.eastNorth);
}
Collection<Command> cmds = new LinkedList<Command>();
cmds.add(c);
// split the first segment
splitWaySegmentAtNode(ws, n, cmds);
// if a second segment was found, split that as well
if (other != null) splitWaySegmentAtNode(other, n, cmds);
c = new SequenceCommand(tr((other == null) ?
"Add node into way" : "Add common node into two ways"), cmds);
}
// Add a node and connecting segment.
if (mode == Mode.autonode) {
WaySegment insertInto = null;
Node reuseNode = null;
// If CTRL is held, insert the node into a potentially existing way segment
if ((e.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) != 0) {
insertInto = Main.map.mapView.getNearestWaySegment(e.getPoint());
if (insertInto == null) System.err.println("Couldn't find nearby way segment");
if (insertInto == null)
return;
}
// If SHIFT is held, instead of creating a new node, re-use an existing
// node (making this action identical to AddSegmentAction with the
// small difference that the node used will then be selected to allow
// continuation of the "add node and connect" stuff)
else if ((e.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0) {
OsmPrimitive clicked = Main.map.mapView.getNearest(e.getPoint());
if (clicked == null || !(clicked instanceof Node))
return;
reuseNode = (Node) clicked;
}
Collection<OsmPrimitive> selection = Main.ds.getSelected();
if (selection.size() == 1 && selection.iterator().next() instanceof Node) {
Node n1 = (Node)selection.iterator().next();
Collection<Command> cmds = new LinkedList<Command>();
if (reuseNode != null) {
// in re-use node mode, n1 must not be identical to clicked node
if (n1 == reuseNode) System.err.println("n1 == reuseNode");
if (n1 == reuseNode) return;
// replace newly created node with existing node
n = reuseNode;
} else {
// only add the node creation command if we're not re-using
cmds.add(c);
}
/* Keep track of the way we change, it might be the same into
* which we insert the node.
*/
Way wayInsertedInto = null;
if (insertInto != null)
wayInsertedInto = splitWaySegmentAtNode(insertInto, n, cmds);
Way way = getWayForNode(n1);
if (way == null) {
way = new Way();
way.nodes.add(n1);
cmds.add(new AddCommand(way));
} else {
if (insertInto != null && way == insertInto.way) {
way = wayInsertedInto;
} else {
Way wnew = new Way(way);
cmds.add(new ChangeCommand(way, wnew));
way = wnew;
}
}
if (way.nodes.get(way.nodes.size() - 1) == n1) {
way.nodes.add(n);
} else {
way.nodes.add(0, n);
}
c = new SequenceCommand(tr((insertInto == null) ? "Add node and connect" : "Add node into way and connect"), cmds);
}
}
Main.main.undoRedo.add(c);
Main.ds.setSelected(n);
Main.map.mapView.repaint();
}
|
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/SubstitutionOperation.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/SubstitutionOperation.java
index 524c3314..0878b8b2 100644
--- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/SubstitutionOperation.java
+++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/commands/SubstitutionOperation.java
@@ -1,133 +1,137 @@
package net.sourceforge.vrapper.vim.commands;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import net.sourceforge.vrapper.platform.SearchAndReplaceService;
import net.sourceforge.vrapper.utils.ContentType;
import net.sourceforge.vrapper.utils.LineInformation;
import net.sourceforge.vrapper.utils.TextRange;
import net.sourceforge.vrapper.vim.EditorAdaptor;
/**
* Perform a substitution on a range of lines. Can be current line,
* all lines, or any range in between.
* For example, :s/foo/blah/g or :%s/foo/blah/g or :2,5s/foo/blah/g
*/
public class SubstitutionOperation extends SimpleTextOperation {
private String substitution;
public SubstitutionOperation(String substitution) {
this.substitution = substitution;
}
@Override
public void execute(EditorAdaptor editorAdaptor, TextRange region, ContentType contentType) {
int startLine;
int endLine;
if(region == null) {
//special case, recalculate 'current line' every time
//(this is to ensure '.' always works on current line)
int offset = editorAdaptor.getPosition().getModelOffset();
startLine = editorAdaptor.getModelContent().getLineInformationOfOffset(offset).getNumber();
endLine = startLine;
}
else {
startLine = editorAdaptor.getModelContent()
.getLineInformationOfOffset( region.getLeftBound().getModelOffset() ).getNumber();
endLine = editorAdaptor.getModelContent()
.getLineInformationOfOffset( region.getRightBound().getModelOffset() ).getNumber();
}
//whatever character is after 's' is our delimiter
String delim = "" + substitution.charAt( substitution.indexOf('s') + 1);
String[] fields = substitution.split(delim);
String find = "";
String replace = "";
String flags = "";
//'s' or '%s' = fields[0]
if(fields.length > 1) {
find = fields[1];
+ if(find.length() == 0) {
+ //if no pattern defined, use last search
+ find = editorAdaptor.getRegisterManager().getRegister("/").getContent().getText();
+ }
}
if(fields.length > 2) {
replace = fields[2];
}
if(fields.length > 3) {
flags = fields[3];
}
//before attempting substitution, is this regex even valid?
try {
Pattern.compile(find);
} catch (PatternSyntaxException e) {
editorAdaptor.getUserInterfaceService().setErrorMessage(e.getDescription());
return;
}
int numReplaces = 0;
int lineReplaceCount = 0;
if(startLine == endLine) {
LineInformation currentLine = editorAdaptor.getModelContent().getLineInformation(startLine);
//begin and end compound change so a single 'u' undoes all replaces
editorAdaptor.getHistory().beginCompoundChange();
numReplaces = performReplace(currentLine, find, replace, flags, editorAdaptor);
editorAdaptor.getHistory().endCompoundChange();
}
else {
LineInformation line;
int lineChanges = 0;
//perform search individually on each line in the range
//(so :%s without 'g' flag runs once on each line)
editorAdaptor.getHistory().beginCompoundChange();
for(int i=startLine; i < endLine; i++) {
line = editorAdaptor.getModelContent().getLineInformation(i);
lineChanges = performReplace(line, find, replace, flags, editorAdaptor);
if(lineChanges > 0) {
lineReplaceCount++;
}
numReplaces += lineChanges;
}
editorAdaptor.getHistory().endCompoundChange();
}
if(numReplaces == 0) {
editorAdaptor.getUserInterfaceService().setErrorMessage("'"+find+"' not found");
}
else if(lineReplaceCount > 0) {
editorAdaptor.getUserInterfaceService().setInfoMessage(
numReplaces + " substitutions on " + lineReplaceCount + " lines"
);
}
//enable '&', 'g&', and ':s' features
editorAdaptor.getRegisterManager().setLastSubstitution(this);
}
private int performReplace(LineInformation line, String find,
String replace, String flags, EditorAdaptor editorAdaptor) {
//Eclipse regex doesn't handle '^' and '$' like Vim does.
//Time for some special cases!
if(find.equals("^")) {
//insert the text at the beginning of the line
editorAdaptor.getModelContent().replace(line.getBeginOffset(), 0, replace);
return 1;
}
else if(find.equals("$")) {
//insert the text at the end of the line
editorAdaptor.getModelContent().replace(line.getEndOffset(), 0, replace);
return 1;
}
else {
//let Eclipse handle the regex
SearchAndReplaceService searchAndReplace = editorAdaptor.getSearchAndReplaceService();
return searchAndReplace.replace(line, find, replace, flags);
}
}
public TextOperation repetition() {
return this;
}
}
| true | true | public void execute(EditorAdaptor editorAdaptor, TextRange region, ContentType contentType) {
int startLine;
int endLine;
if(region == null) {
//special case, recalculate 'current line' every time
//(this is to ensure '.' always works on current line)
int offset = editorAdaptor.getPosition().getModelOffset();
startLine = editorAdaptor.getModelContent().getLineInformationOfOffset(offset).getNumber();
endLine = startLine;
}
else {
startLine = editorAdaptor.getModelContent()
.getLineInformationOfOffset( region.getLeftBound().getModelOffset() ).getNumber();
endLine = editorAdaptor.getModelContent()
.getLineInformationOfOffset( region.getRightBound().getModelOffset() ).getNumber();
}
//whatever character is after 's' is our delimiter
String delim = "" + substitution.charAt( substitution.indexOf('s') + 1);
String[] fields = substitution.split(delim);
String find = "";
String replace = "";
String flags = "";
//'s' or '%s' = fields[0]
if(fields.length > 1) {
find = fields[1];
}
if(fields.length > 2) {
replace = fields[2];
}
if(fields.length > 3) {
flags = fields[3];
}
//before attempting substitution, is this regex even valid?
try {
Pattern.compile(find);
} catch (PatternSyntaxException e) {
editorAdaptor.getUserInterfaceService().setErrorMessage(e.getDescription());
return;
}
int numReplaces = 0;
int lineReplaceCount = 0;
if(startLine == endLine) {
LineInformation currentLine = editorAdaptor.getModelContent().getLineInformation(startLine);
//begin and end compound change so a single 'u' undoes all replaces
editorAdaptor.getHistory().beginCompoundChange();
numReplaces = performReplace(currentLine, find, replace, flags, editorAdaptor);
editorAdaptor.getHistory().endCompoundChange();
}
else {
LineInformation line;
int lineChanges = 0;
//perform search individually on each line in the range
//(so :%s without 'g' flag runs once on each line)
editorAdaptor.getHistory().beginCompoundChange();
for(int i=startLine; i < endLine; i++) {
line = editorAdaptor.getModelContent().getLineInformation(i);
lineChanges = performReplace(line, find, replace, flags, editorAdaptor);
if(lineChanges > 0) {
lineReplaceCount++;
}
numReplaces += lineChanges;
}
editorAdaptor.getHistory().endCompoundChange();
}
if(numReplaces == 0) {
editorAdaptor.getUserInterfaceService().setErrorMessage("'"+find+"' not found");
}
else if(lineReplaceCount > 0) {
editorAdaptor.getUserInterfaceService().setInfoMessage(
numReplaces + " substitutions on " + lineReplaceCount + " lines"
);
}
//enable '&', 'g&', and ':s' features
editorAdaptor.getRegisterManager().setLastSubstitution(this);
}
| public void execute(EditorAdaptor editorAdaptor, TextRange region, ContentType contentType) {
int startLine;
int endLine;
if(region == null) {
//special case, recalculate 'current line' every time
//(this is to ensure '.' always works on current line)
int offset = editorAdaptor.getPosition().getModelOffset();
startLine = editorAdaptor.getModelContent().getLineInformationOfOffset(offset).getNumber();
endLine = startLine;
}
else {
startLine = editorAdaptor.getModelContent()
.getLineInformationOfOffset( region.getLeftBound().getModelOffset() ).getNumber();
endLine = editorAdaptor.getModelContent()
.getLineInformationOfOffset( region.getRightBound().getModelOffset() ).getNumber();
}
//whatever character is after 's' is our delimiter
String delim = "" + substitution.charAt( substitution.indexOf('s') + 1);
String[] fields = substitution.split(delim);
String find = "";
String replace = "";
String flags = "";
//'s' or '%s' = fields[0]
if(fields.length > 1) {
find = fields[1];
if(find.length() == 0) {
//if no pattern defined, use last search
find = editorAdaptor.getRegisterManager().getRegister("/").getContent().getText();
}
}
if(fields.length > 2) {
replace = fields[2];
}
if(fields.length > 3) {
flags = fields[3];
}
//before attempting substitution, is this regex even valid?
try {
Pattern.compile(find);
} catch (PatternSyntaxException e) {
editorAdaptor.getUserInterfaceService().setErrorMessage(e.getDescription());
return;
}
int numReplaces = 0;
int lineReplaceCount = 0;
if(startLine == endLine) {
LineInformation currentLine = editorAdaptor.getModelContent().getLineInformation(startLine);
//begin and end compound change so a single 'u' undoes all replaces
editorAdaptor.getHistory().beginCompoundChange();
numReplaces = performReplace(currentLine, find, replace, flags, editorAdaptor);
editorAdaptor.getHistory().endCompoundChange();
}
else {
LineInformation line;
int lineChanges = 0;
//perform search individually on each line in the range
//(so :%s without 'g' flag runs once on each line)
editorAdaptor.getHistory().beginCompoundChange();
for(int i=startLine; i < endLine; i++) {
line = editorAdaptor.getModelContent().getLineInformation(i);
lineChanges = performReplace(line, find, replace, flags, editorAdaptor);
if(lineChanges > 0) {
lineReplaceCount++;
}
numReplaces += lineChanges;
}
editorAdaptor.getHistory().endCompoundChange();
}
if(numReplaces == 0) {
editorAdaptor.getUserInterfaceService().setErrorMessage("'"+find+"' not found");
}
else if(lineReplaceCount > 0) {
editorAdaptor.getUserInterfaceService().setInfoMessage(
numReplaces + " substitutions on " + lineReplaceCount + " lines"
);
}
//enable '&', 'g&', and ':s' features
editorAdaptor.getRegisterManager().setLastSubstitution(this);
}
|
diff --git a/Chat/src/States/ConnectedServer.java b/Chat/src/States/ConnectedServer.java
index 45ef96e..c1a53ee 100644
--- a/Chat/src/States/ConnectedServer.java
+++ b/Chat/src/States/ConnectedServer.java
@@ -1,32 +1,33 @@
package States;
import Communications.*;
import Messages.*;
import Utilities.User;
public class ConnectedServer extends State {
public State process(String input, TCP tcp, UDPSender us, Message udpMessage, Message tcpMessage, long timeEnteredState,boolean firstCall) {
if(firstCall){
System.out.println("You are connected to a server.\nType :update to try to bind your name to your ip.\nType :query <username> to ask the server for the ip of that username\nType :dc to disconnect");
}
if (tcp.getActive() == false) {
System.out.println("Server disconnected");
try{
tcp.close();
}
catch(Exception e){}
return new Disconnected();
} else if (input.startsWith(":update")) {
Message message=new ClientRequestUpdateMessage(6,ClientRequestUpdateMessage.minSize+Message.minSize,0,"",User.userName,tcp.getIP());
tcp.send(message);
return new ServerUpdate();
} else if (input.startsWith(":query")) {
Message message=new ClientRequestInfoMessage(8,ClientRequestInfoMessage.minSize+Message.minSize,0,"",User.userName,input.substring(7).trim(),tcp.getIP());
+ System.out.println(new String(message.convert(),0,message.convert().length));
System.out.println(tcp.send(message));
return new ServerQuery();
} else {
return this;
}
}
}
| true | true | public State process(String input, TCP tcp, UDPSender us, Message udpMessage, Message tcpMessage, long timeEnteredState,boolean firstCall) {
if(firstCall){
System.out.println("You are connected to a server.\nType :update to try to bind your name to your ip.\nType :query <username> to ask the server for the ip of that username\nType :dc to disconnect");
}
if (tcp.getActive() == false) {
System.out.println("Server disconnected");
try{
tcp.close();
}
catch(Exception e){}
return new Disconnected();
} else if (input.startsWith(":update")) {
Message message=new ClientRequestUpdateMessage(6,ClientRequestUpdateMessage.minSize+Message.minSize,0,"",User.userName,tcp.getIP());
tcp.send(message);
return new ServerUpdate();
} else if (input.startsWith(":query")) {
Message message=new ClientRequestInfoMessage(8,ClientRequestInfoMessage.minSize+Message.minSize,0,"",User.userName,input.substring(7).trim(),tcp.getIP());
System.out.println(tcp.send(message));
return new ServerQuery();
} else {
return this;
}
}
| public State process(String input, TCP tcp, UDPSender us, Message udpMessage, Message tcpMessage, long timeEnteredState,boolean firstCall) {
if(firstCall){
System.out.println("You are connected to a server.\nType :update to try to bind your name to your ip.\nType :query <username> to ask the server for the ip of that username\nType :dc to disconnect");
}
if (tcp.getActive() == false) {
System.out.println("Server disconnected");
try{
tcp.close();
}
catch(Exception e){}
return new Disconnected();
} else if (input.startsWith(":update")) {
Message message=new ClientRequestUpdateMessage(6,ClientRequestUpdateMessage.minSize+Message.minSize,0,"",User.userName,tcp.getIP());
tcp.send(message);
return new ServerUpdate();
} else if (input.startsWith(":query")) {
Message message=new ClientRequestInfoMessage(8,ClientRequestInfoMessage.minSize+Message.minSize,0,"",User.userName,input.substring(7).trim(),tcp.getIP());
System.out.println(new String(message.convert(),0,message.convert().length));
System.out.println(tcp.send(message));
return new ServerQuery();
} else {
return this;
}
}
|
diff --git a/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/nhttp/Axis2HttpRequest.java b/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/nhttp/Axis2HttpRequest.java
index ace323291..96561c15f 100644
--- a/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/nhttp/Axis2HttpRequest.java
+++ b/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/nhttp/Axis2HttpRequest.java
@@ -1,387 +1,389 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.synapse.transport.nhttp;
import org.apache.axiom.om.OMOutputFormat;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.MessageFormatter;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpVersion;
import org.apache.http.nio.util.ContentOutputBuffer;
import org.apache.http.nio.entity.ContentOutputStream;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.protocol.HTTP;
import org.apache.synapse.transport.nhttp.util.MessageFormatterDecoratorFactory;
import org.apache.synapse.transport.nhttp.util.NhttpUtil;
import org.apache.synapse.commons.util.TemporaryData;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.ClosedChannelException;
import java.util.Iterator;
import java.util.Map;
import java.net.URL;
/**
* Represents an outgoing Axis2 HTTP/s request. It holds the EPR of the destination, the
* Axis2 MessageContext to be sent, an HttpHost object which captures information about the
* destination, and a Pipe used to write the message stream to the destination
*/
public class Axis2HttpRequest {
private static final Log log = LogFactory.getLog(Axis2HttpRequest.class);
/** the EPR of the destination */
private EndpointReference epr = null;
/** the HttpHost that contains the HTTP connection information */
private HttpHost httpHost = null;
/** The [socket | connect] timeout */
private int timeout = -1;
/** the message context being sent */
private MessageContext msgContext = null;
/** The Axis2 MessageFormatter that will ensure proper serialization as per Axis2 semantics */
MessageFormatter messageFormatter = null;
/** The OM Output format holder */
OMOutputFormat format = null;
private ContentOutputBuffer outputBuffer = null;
/** ready to begin streaming? */
private volatile boolean readyToStream = false;
/** The sending of this request has fully completed */
private volatile boolean sendingCompleted = false;
/**
* for request complete checking - request complete means the request has been fully sent
* and the response it fully received
*/
private volatile boolean completed = false;
/** The URL prefix of the endpoint (to be used for Location header re-writing in the response)*/
private String endpointURLPrefix = null;
/** weather chunking is enabled or not */
private boolean chunked = true;
public Axis2HttpRequest(EndpointReference epr, HttpHost httpHost, MessageContext msgContext) {
this.epr = epr;
this.httpHost = httpHost;
this.msgContext = msgContext;
this.format = NhttpUtil.getOMOutputFormat(msgContext);
this.messageFormatter =
MessageFormatterDecoratorFactory.createMessageFormatterDecorator(msgContext);
this.chunked = !msgContext.isPropertyTrue(NhttpConstants.DISABLE_CHUNKING);
}
public void setReadyToStream(boolean readyToStream) {
this.readyToStream = readyToStream;
}
public void setOutputBuffer(ContentOutputBuffer outputBuffer) {
this.outputBuffer = outputBuffer;
}
public void clear() {
this.epr = null;
this.httpHost = null;
this.msgContext = null;
this.format = null;
this.messageFormatter = null;
this.outputBuffer = null;
}
public EndpointReference getEpr() {
return epr;
}
public HttpHost getHttpHost() {
return httpHost;
}
public MessageContext getMsgContext() {
return msgContext;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public String getEndpointURLPrefix() {
return endpointURLPrefix;
}
public void setEndpointURLPrefix(String endpointURLPrefix) {
this.endpointURLPrefix = endpointURLPrefix;
}
/**
* Create and return a new HttpPost request to the destination EPR
* @return the HttpRequest to be sent out
*/
public HttpRequest getRequest() throws IOException {
String httpMethod = (String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD);
if (httpMethod == null) {
httpMethod = "POST";
}
endpointURLPrefix = (String) msgContext.getProperty(NhttpConstants.ENDPOINT_PREFIX);
HttpRequest httpRequest = null;
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod)) {
+ URL url = new URL(epr.getAddress());
httpRequest = new BasicHttpEntityEnclosingRequest(
httpMethod,
msgContext.isPropertyTrue(NhttpConstants.POST_TO_URI) ?
- epr.getAddress() : new URL(epr.getAddress()).getPath(),
+ epr.getAddress() : url.getPath()
+ + (url.getQuery() != null ? "?" + url.getQuery() : ""),
msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0) ?
HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1);
BasicHttpEntity entity = new BasicHttpEntity();
if (msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) {
setStreamAsTempData(entity);
} else {
entity.setChunked(chunked);
if (!chunked) {
setStreamAsTempData(entity);
}
}
((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(entity);
httpRequest.setHeader(
HTTP.CONTENT_TYPE,
messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
} else if ("GET".equals(httpMethod)) {
URL reqURI = messageFormatter.getTargetAddress(
msgContext, format, new URL(epr.getAddress()));
String path = (msgContext.isPropertyTrue(NhttpConstants.POST_TO_URI) ?
reqURI.toString() : reqURI.getPath() +
(reqURI.getQuery() != null ? "?" + reqURI.getQuery() : ""));
httpRequest = new BasicHttpRequest(httpMethod, path,
msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0) ?
HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1);
httpRequest.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(
msgContext, format, msgContext.getSoapAction()));
} else {
httpRequest = new BasicHttpRequest(
httpMethod,
msgContext.isPropertyTrue(NhttpConstants.POST_TO_URI) ?
epr.getAddress() : new URL(epr.getAddress()).getPath(),
msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0) ?
HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1);
}
// set any transport headers
Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
if (o != null && o instanceof Map) {
Map headers = (Map) o;
Iterator iter = headers.keySet().iterator();
while (iter.hasNext()) {
Object header = iter.next();
Object value = headers.get(header);
if (header instanceof String && value != null && value instanceof String) {
if (!HTTPConstants.HEADER_HOST.equalsIgnoreCase((String) header)) {
httpRequest.setHeader((String) header, (String) value);
}
}
}
}
// if the message is SOAP 11 (for which a SOAPAction is *required*), and
// the msg context has a SOAPAction or a WSA-Action (give pref to SOAPAction)
// use that over any transport header that may be available
String soapAction = msgContext.getSoapAction();
if (soapAction == null) {
soapAction = msgContext.getWSAAction();
}
if (soapAction == null) {
msgContext.getAxisOperation().getInputAction();
}
if (msgContext.isSOAP11() && soapAction != null &&
soapAction.length() > 0) {
Header existingHeader =
httpRequest.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
if (existingHeader != null) {
httpRequest.removeHeader(existingHeader);
}
httpRequest.setHeader(HTTPConstants.HEADER_SOAP_ACTION,
messageFormatter.formatSOAPAction(msgContext, null, soapAction));
}
if (NHttpConfiguration.getInstance().isKeepAliveDisabled() ||
msgContext.isPropertyTrue(NhttpConstants.NO_KEEPALIVE)) {
httpRequest.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
}
return httpRequest;
}
/**
* Start streaming the message into the Pipe, so that the contents could be read off the source
* channel returned by getSourceChannel()
* @throws AxisFault on error
*/
public void streamMessageContents() throws AxisFault {
if (log.isDebugEnabled()) {
log.debug("Start streaming outgoing http request : [Message ID : " + msgContext.getMessageID() + "]");
if (log.isTraceEnabled()) {
log.trace("Message [Request Message ID : " + msgContext.getMessageID() + "] " +
"[Request Message Payload : [ " + msgContext.getEnvelope() + "]");
}
}
synchronized(this) {
while (!readyToStream && !completed) {
try {
this.wait();
} catch (InterruptedException ignore) {}
}
}
if (!completed) {
OutputStream out = new ContentOutputStream(outputBuffer);
try {
if (msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) {
writeMessageFromTempData(out);
} else {
if (chunked) {
messageFormatter.writeTo(msgContext, format, out, false);
} else {
writeMessageFromTempData(out);
}
}
} catch (Exception e) {
Throwable t = e.getCause();
if (t != null && t.getCause() != null && t.getCause() instanceof ClosedChannelException) {
if (log.isDebugEnabled()) {
log.debug("Ignore closed channel exception, as the " +
"SessionRequestCallback handles this exception");
}
} else {
Integer errorCode = msgContext == null ? null :
(Integer) msgContext.getProperty(NhttpConstants.ERROR_CODE);
if (errorCode == null || errorCode == NhttpConstants.SEND_ABORT) {
if (log.isDebugEnabled()) {
log.debug("Remote server aborted request being sent, and responded");
}
} else {
if (e instanceof AxisFault) {
throw (AxisFault) e;
} else {
handleException("Error streaming message context", e);
}
}
}
}
finally {
try {
out.flush();
out.close();
} catch (IOException e) {
handleException("Error closing outgoing message stream", e);
}
setSendingCompleted(true);
}
}
}
/**
* Write the stream to a temporary storage and calculate the content length
* @param entity HTTPEntity
* @throws IOException if an exception occurred while writing data
*/
private void setStreamAsTempData(BasicHttpEntity entity) throws IOException {
TemporaryData serialized = new TemporaryData(256, 4096, "http-nio_", ".dat");
OutputStream out = serialized.getOutputStream();
try {
messageFormatter.writeTo(msgContext, format, out, true);
} finally {
out.close();
}
msgContext.setProperty(NhttpConstants.SERIALIZED_BYTES, serialized);
entity.setContentLength(serialized.getLength());
}
/**
* Take the data from temporary storage and write it to the output stream
* @param out output stream
* @throws IOException if an exception occurred while writing data
*/
private void writeMessageFromTempData(OutputStream out) throws IOException {
TemporaryData serialized =
(TemporaryData) msgContext.getProperty(NhttpConstants.SERIALIZED_BYTES);
try {
serialized.writeTo(out);
} finally {
serialized.release();
}
}
// -------------- utility methods -------------
private void handleException(String msg, Exception e) throws AxisFault {
log.error(msg, e);
throw new AxisFault(msg, e);
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
synchronized(this) {
this.notifyAll();
}
}
public boolean isSendingCompleted() {
return sendingCompleted;
}
public void setSendingCompleted(boolean sendingCompleted) {
this.sendingCompleted = sendingCompleted;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Axis2Request [Message ID : ").append(msgContext.getMessageID()).append("] ");
sb.append("[Status Completed : ").append(isCompleted() ? "true" : "false").append("] ");
sb.append("[Status SendingCompleted : ").append(
isSendingCompleted() ? "true" : "false").append("]");
return sb.toString();
}
}
| false | true | public HttpRequest getRequest() throws IOException {
String httpMethod = (String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD);
if (httpMethod == null) {
httpMethod = "POST";
}
endpointURLPrefix = (String) msgContext.getProperty(NhttpConstants.ENDPOINT_PREFIX);
HttpRequest httpRequest = null;
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod)) {
httpRequest = new BasicHttpEntityEnclosingRequest(
httpMethod,
msgContext.isPropertyTrue(NhttpConstants.POST_TO_URI) ?
epr.getAddress() : new URL(epr.getAddress()).getPath(),
msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0) ?
HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1);
BasicHttpEntity entity = new BasicHttpEntity();
if (msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) {
setStreamAsTempData(entity);
} else {
entity.setChunked(chunked);
if (!chunked) {
setStreamAsTempData(entity);
}
}
((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(entity);
httpRequest.setHeader(
HTTP.CONTENT_TYPE,
messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
} else if ("GET".equals(httpMethod)) {
URL reqURI = messageFormatter.getTargetAddress(
msgContext, format, new URL(epr.getAddress()));
String path = (msgContext.isPropertyTrue(NhttpConstants.POST_TO_URI) ?
reqURI.toString() : reqURI.getPath() +
(reqURI.getQuery() != null ? "?" + reqURI.getQuery() : ""));
httpRequest = new BasicHttpRequest(httpMethod, path,
msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0) ?
HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1);
httpRequest.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(
msgContext, format, msgContext.getSoapAction()));
} else {
httpRequest = new BasicHttpRequest(
httpMethod,
msgContext.isPropertyTrue(NhttpConstants.POST_TO_URI) ?
epr.getAddress() : new URL(epr.getAddress()).getPath(),
msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0) ?
HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1);
}
// set any transport headers
Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
if (o != null && o instanceof Map) {
Map headers = (Map) o;
Iterator iter = headers.keySet().iterator();
while (iter.hasNext()) {
Object header = iter.next();
Object value = headers.get(header);
if (header instanceof String && value != null && value instanceof String) {
if (!HTTPConstants.HEADER_HOST.equalsIgnoreCase((String) header)) {
httpRequest.setHeader((String) header, (String) value);
}
}
}
}
// if the message is SOAP 11 (for which a SOAPAction is *required*), and
// the msg context has a SOAPAction or a WSA-Action (give pref to SOAPAction)
// use that over any transport header that may be available
String soapAction = msgContext.getSoapAction();
if (soapAction == null) {
soapAction = msgContext.getWSAAction();
}
if (soapAction == null) {
msgContext.getAxisOperation().getInputAction();
}
if (msgContext.isSOAP11() && soapAction != null &&
soapAction.length() > 0) {
Header existingHeader =
httpRequest.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
if (existingHeader != null) {
httpRequest.removeHeader(existingHeader);
}
httpRequest.setHeader(HTTPConstants.HEADER_SOAP_ACTION,
messageFormatter.formatSOAPAction(msgContext, null, soapAction));
}
if (NHttpConfiguration.getInstance().isKeepAliveDisabled() ||
msgContext.isPropertyTrue(NhttpConstants.NO_KEEPALIVE)) {
httpRequest.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
}
return httpRequest;
}
| public HttpRequest getRequest() throws IOException {
String httpMethod = (String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD);
if (httpMethod == null) {
httpMethod = "POST";
}
endpointURLPrefix = (String) msgContext.getProperty(NhttpConstants.ENDPOINT_PREFIX);
HttpRequest httpRequest = null;
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod)) {
URL url = new URL(epr.getAddress());
httpRequest = new BasicHttpEntityEnclosingRequest(
httpMethod,
msgContext.isPropertyTrue(NhttpConstants.POST_TO_URI) ?
epr.getAddress() : url.getPath()
+ (url.getQuery() != null ? "?" + url.getQuery() : ""),
msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0) ?
HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1);
BasicHttpEntity entity = new BasicHttpEntity();
if (msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) {
setStreamAsTempData(entity);
} else {
entity.setChunked(chunked);
if (!chunked) {
setStreamAsTempData(entity);
}
}
((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(entity);
httpRequest.setHeader(
HTTP.CONTENT_TYPE,
messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
} else if ("GET".equals(httpMethod)) {
URL reqURI = messageFormatter.getTargetAddress(
msgContext, format, new URL(epr.getAddress()));
String path = (msgContext.isPropertyTrue(NhttpConstants.POST_TO_URI) ?
reqURI.toString() : reqURI.getPath() +
(reqURI.getQuery() != null ? "?" + reqURI.getQuery() : ""));
httpRequest = new BasicHttpRequest(httpMethod, path,
msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0) ?
HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1);
httpRequest.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(
msgContext, format, msgContext.getSoapAction()));
} else {
httpRequest = new BasicHttpRequest(
httpMethod,
msgContext.isPropertyTrue(NhttpConstants.POST_TO_URI) ?
epr.getAddress() : new URL(epr.getAddress()).getPath(),
msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0) ?
HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1);
}
// set any transport headers
Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
if (o != null && o instanceof Map) {
Map headers = (Map) o;
Iterator iter = headers.keySet().iterator();
while (iter.hasNext()) {
Object header = iter.next();
Object value = headers.get(header);
if (header instanceof String && value != null && value instanceof String) {
if (!HTTPConstants.HEADER_HOST.equalsIgnoreCase((String) header)) {
httpRequest.setHeader((String) header, (String) value);
}
}
}
}
// if the message is SOAP 11 (for which a SOAPAction is *required*), and
// the msg context has a SOAPAction or a WSA-Action (give pref to SOAPAction)
// use that over any transport header that may be available
String soapAction = msgContext.getSoapAction();
if (soapAction == null) {
soapAction = msgContext.getWSAAction();
}
if (soapAction == null) {
msgContext.getAxisOperation().getInputAction();
}
if (msgContext.isSOAP11() && soapAction != null &&
soapAction.length() > 0) {
Header existingHeader =
httpRequest.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
if (existingHeader != null) {
httpRequest.removeHeader(existingHeader);
}
httpRequest.setHeader(HTTPConstants.HEADER_SOAP_ACTION,
messageFormatter.formatSOAPAction(msgContext, null, soapAction));
}
if (NHttpConfiguration.getInstance().isKeepAliveDisabled() ||
msgContext.isPropertyTrue(NhttpConstants.NO_KEEPALIVE)) {
httpRequest.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
}
return httpRequest;
}
|
diff --git a/c/JavaExpr.java b/c/JavaExpr.java
index aa527a4..0a62fc4 100644
--- a/c/JavaExpr.java
+++ b/c/JavaExpr.java
@@ -1,444 +1,450 @@
// ex: se sts=4 sw=4 expandtab:
/*
* Yeti language compiler java bytecode generator for java foreign interface.
*
* Copyright (c) 2007-2012 Madis Janson
* 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 name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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 yeti.lang.compiler;
import yeti.renamed.asm3.*;
class JavaExpr extends Code {
Code object;
JavaType.Method method;
Code[] args;
int line;
JavaExpr(Code object, JavaType.Method method, Code[] args, int line) {
this.object = object;
this.method = method;
this.args = args;
this.line = line;
}
// convert to java
private static void convert(Ctx ctx, YType given, YType argType) {
given = given.deref();
argType = argType.deref();
String descr = argType.javaType == null
? "" : argType.javaType.description;
if (argType.type == YetiType.JAVA_ARRAY &&
given.type == YetiType.JAVA_ARRAY) {
ctx.typeInsn(CHECKCAST, JavaType.descriptionOf(argType));
return; // better than thinking, that array was given...
// still FIXME for a case of different arrays
}
if (given.type != YetiType.JAVA &&
(argType.type == YetiType.JAVA_ARRAY ||
argType.type == YetiType.JAVA &&
argType.javaType.isCollection())) {
Label retry = new Label(), end = new Label();
ctx.typeInsn(CHECKCAST, "yeti/lang/AIter"); // i
String tmpClass = descr != "Ljava/lang/Set;"
? "java/util/ArrayList" : "java/util/HashSet";
ctx.typeInsn(NEW, tmpClass); // ia
ctx.insn(DUP); // iaa
ctx.visitInit(tmpClass, "()V"); // ia
ctx.insn(SWAP); // ai
ctx.insn(DUP); // aii
ctx.jumpInsn(IFNULL, end); // ai
ctx.insn(DUP); // aii
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/AIter",
"isEmpty", "()Z"); // aiz
ctx.jumpInsn(IFNE, end); // ai
ctx.visitLabel(retry);
ctx.insn(DUP2); // aiai
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/AIter",
"first", "()Ljava/lang/Object;");
YType t = null;
if (argType.param.length != 0 &&
((t = argType.param[0]).type != YetiType.JAVA ||
t.javaType.description.length() > 1)) {
convert(ctx, given.param[0], argType.param[0]);
}
// aiav
ctx.methodInsn(INVOKEVIRTUAL, tmpClass,
"add", "(Ljava/lang/Object;)Z"); // aiz
ctx.insn(POP); // ai
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/AIter",
"next", "()Lyeti/lang/AIter;"); // ai
ctx.insn(DUP); // aii
ctx.jumpInsn(IFNONNULL, retry); // ai
ctx.visitLabel(end);
ctx.insn(POP); // a
if (argType.type != YetiType.JAVA_ARRAY)
return; // a - List/Set
String s = "";
YType argArrayType = argType;
while ((argType = argType.param[0]).type ==
YetiType.JAVA_ARRAY) {
s += "[";
argArrayType = argType;
}
String arrayPrefix = s;
if (s == "" && argType.javaType.description.length() != 1) {
s = argType.javaType.className();
} else {
s += argType.javaType.description;
}
ctx.insn(DUP); // aa
ctx.methodInsn(INVOKEVIRTUAL, tmpClass,
"size", "()I"); // an
if (t.type != YetiType.JAVA ||
(descr = t.javaType.description).length() != 1) {
ctx.typeInsn(ANEWARRAY, s); // aA
ctx.methodInsn(INVOKEVIRTUAL, tmpClass, "toArray",
"([Ljava/lang/Object;)[Ljava/lang/Object;");
if (!s.equals("java/lang/Object")) {
ctx.typeInsn(CHECKCAST,
arrayPrefix + "[" + argType.javaType.description);
}
return; // A - object array
}
// emulate a fucking for loop to fill primitive array
int index = ctx.localVarCount++;
Label next = new Label(), done = new Label();
ctx.insn(DUP); // ann
ctx.varInsn(ISTORE, index); // an
new NewArrayExpr(argArrayType, null, 0).gen(ctx);
ctx.insn(SWAP); // Aa
ctx.visitLabel(next);
ctx.varInsn(ILOAD, index); // Aan
ctx.jumpInsn(IFEQ, done); // Aa
ctx.visitIntInsn(IINC, index); // Aa --index
ctx.insn(DUP2); // AaAa
ctx.varInsn(ILOAD, index); // AaAan
ctx.methodInsn(INVOKEVIRTUAL, tmpClass,
"get", "(I)Ljava/lang/Object;"); // AaAv
if (descr == "Z") {
ctx.typeInsn(CHECKCAST, "java/lang/Boolean");
ctx.methodInsn(INVOKEVIRTUAL, "java/lang/Boolean",
"booleanValue", "()Z");
} else {
ctx.typeInsn(CHECKCAST, "yeti/lang/Num");
convertNum(ctx, descr);
}
ctx.varInsn(ILOAD, index); // AaAvn
- ctx.insn(SWAP); // AaAnv
int insn = BASTORE;
switch (argType.javaType.description.charAt(0)) {
case 'D': insn = DASTORE; break;
case 'F': insn = FASTORE; break;
case 'I': insn = IASTORE; break;
case 'J': insn = LASTORE; break;
case 'S': insn = SASTORE;
}
+ if (insn == DASTORE || insn == LASTORE) {
+ // AaAvvn actually - long and double is 2 entries
+ ctx.insn(DUP_X2); // AaAnvvn
+ ctx.insn(POP); // AaAnvv
+ } else {
+ ctx.insn(SWAP); // AaAnv
+ }
ctx.insn(insn); // Aa
ctx.jumpInsn(GOTO, next); // Aa
ctx.visitLabel(done);
ctx.insn(POP); // A
return; // A - primitive array
}
if (given.type == YetiType.STR) {
ctx.typeInsn(CHECKCAST, "java/lang/String");
ctx.insn(DUP);
ctx.fieldInsn(GETSTATIC, "yeti/lang/Core", "UNDEF_STR",
"Ljava/lang/String;");
Label defined = new Label();
ctx.jumpInsn(IF_ACMPNE, defined);
ctx.insn(POP);
ctx.insn(ACONST_NULL);
ctx.visitLabel(defined);
return;
}
if (given.type != YetiType.NUM ||
descr == "Ljava/lang/Object;" ||
descr == "Ljava/lang/Number;") {
if (descr != "Ljava/lang/Object;") {
ctx.typeInsn(CHECKCAST, argType.javaType.className());
}
return;
}
// Convert numbers...
ctx.typeInsn(CHECKCAST, "yeti/lang/Num");
if (descr == "Ljava/math/BigInteger;") {
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/Num",
"toBigInteger", "()Ljava/math/BigInteger;");
return;
}
if (descr == "Ljava/math/BigDecimal;") {
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/Num",
"toBigDecimal", "()Ljava/math/BigDecimal;");
return;
}
String newInstr = null;
if (descr.startsWith("Ljava/lang/")) {
newInstr = argType.javaType.className();
ctx.typeInsn(NEW, newInstr);
ctx.insn(DUP_X1);
ctx.insn(SWAP);
descr = descr.substring(11, 12);
}
convertNum(ctx, descr);
if (newInstr != null) {
ctx.visitInit(newInstr, "(" + descr + ")V");
}
}
private static void convertNum(Ctx ctx, String descr) {
String method = null;
switch (descr.charAt(0)) {
case 'B': method = "byteValue"; break;
case 'D': method = "doubleValue"; break;
case 'F': method = "floatValue"; break;
case 'I': method = "intValue"; break;
case 'L': if (descr == "Lyeti/lang/Num;")
return;
case 'J': method = "longValue"; break;
case 'S': method = "shortValue"; break;
}
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/Num",
method, "()" + descr);
}
// MethodCall overrides it
void visitInvoke(Ctx ctx, int invokeInsn) {
ctx.methodInsn(invokeInsn, method.classType.javaType.className(),
method.name, method.descr(null));
}
void genCall(Ctx ctx, BindRef[] extraArgs, int invokeInsn) {
for (int i = 0; i < args.length; ++i) {
convertedArg(ctx, args[i], method.arguments[i], line);
}
if (extraArgs != null) {
for (int i = 0; i < extraArgs.length; ++i) {
BindRef arg = extraArgs[i];
CaptureWrapper cw = arg.capture();
if (cw == null) {
arg.gen(ctx);
ctx.captureCast(arg.captureType());
} else {
cw.genPreGet(ctx);
}
}
}
ctx.visitLine(line);
visitInvoke(ctx, invokeInsn);
JavaType jt = method.returnType.javaType;
if (jt != null && jt.description.charAt(0) == 'L')
ctx.forceType(jt.className());
}
static void convertedArg(Ctx ctx, Code arg, YType argType, int line) {
argType = argType.deref();
if (argType.type == YetiType.JAVA) {
// integer arguments can be directly generated
String desc = desc = argType.javaType.description;
if (desc == "I" || desc == "J") {
arg.genInt(ctx, line, desc == "J");
return;
}
}
if (genRawArg(ctx, arg, argType, line))
convert(ctx, arg.type, argType);
else if (argType.type == YetiType.STR)
convertValue(ctx, arg.type.deref()); // for as cast
}
private static boolean genRawArg(Ctx ctx, Code arg,
YType argType, int line) {
YType given = arg.type.deref();
String descr =
argType.javaType == null ? null : argType.javaType.description;
if (descr == "Z") {
// boolean
Label end = new Label(), lie = new Label();
arg.genIf(ctx, lie, false);
ctx.intConst(1);
ctx.jumpInsn(GOTO, end);
ctx.visitLabel(lie);
ctx.intConst(0);
ctx.visitLabel(end);
return false;
}
arg.gen(ctx);
if (given.type == YetiType.UNIT) {
if (!(arg instanceof UnitConstant)) {
ctx.insn(POP);
ctx.insn(ACONST_NULL);
}
return false;
}
ctx.visitLine(line);
if (descr == "C") {
ctx.typeInsn(CHECKCAST, "java/lang/String");
ctx.intConst(0);
ctx.methodInsn(INVOKEVIRTUAL,
"java/lang/String", "charAt", "(I)C");
return false;
}
if (argType.type == YetiType.JAVA_ARRAY &&
given.type == YetiType.STR) {
ctx.typeInsn(CHECKCAST, "java/lang/String");
ctx.methodInsn(INVOKEVIRTUAL,
"java/lang/String", "toCharArray", "()[C");
return false;
}
if (arg instanceof StringConstant || arg instanceof ConcatStrings)
return false;
// conversion from array to list
if (argType.type == YetiType.MAP && given.type == YetiType.JAVA_ARRAY) {
String javaItem = given.param[0].javaType.description;
if (javaItem.length() == 1) {
String arrayType = "[".concat(javaItem);
ctx.typeInsn(CHECKCAST, arrayType);
ctx.methodInsn(INVOKESTATIC, "yeti/lang/PArray",
"wrap", "(" + arrayType + ")Lyeti/lang/AList;");
return false;
}
Label isNull = new Label(), end = new Label();
ctx.typeInsn(CHECKCAST, "[Ljava/lang/Object;");
ctx.insn(DUP);
ctx.jumpInsn(IFNULL, isNull);
boolean toList = argType.param[1].deref().type == YetiType.NONE;
if (toList) {
ctx.insn(DUP);
ctx.insn(ARRAYLENGTH);
ctx.jumpInsn(IFEQ, isNull);
}
if (toList && argType.param[0].deref().type == YetiType.STR) {
// convert null's to undef_str's
ctx.methodInsn(INVOKESTATIC, "yeti/lang/MList", "ofStrArray",
"([Ljava/lang/Object;)Lyeti/lang/MList;");
} else {
ctx.typeInsn(NEW, "yeti/lang/MList");
ctx.insn(DUP_X1);
ctx.insn(SWAP);
ctx.visitInit("yeti/lang/MList", "([Ljava/lang/Object;)V");
}
ctx.jumpInsn(GOTO, end);
ctx.visitLabel(isNull);
ctx.insn(POP);
if (toList) {
ctx.insn(ACONST_NULL);
} else {
ctx.typeInsn(NEW, "yeti/lang/MList");
ctx.insn(DUP);
ctx.visitInit("yeti/lang/MList", "()V");
}
ctx.visitLabel(end);
return false;
}
return argType.type == YetiType.JAVA ||
argType.type == YetiType.JAVA_ARRAY;
}
static void genValue(Ctx ctx, Code arg, YType argType, int line) {
genRawArg(ctx, arg, argType, line);
if (arg.type.deref().type == YetiType.NUM &&
argType.javaType.description.length() == 1) {
ctx.typeInsn(CHECKCAST, "yeti/lang/Num");
convertNum(ctx, argType.javaType.description);
}
}
static void convertValue(Ctx ctx, YType t) {
if (t.type != YetiType.JAVA) {
return; // array, no automatic conversions
}
String descr = t.javaType.description;
if (descr == "V") {
ctx.insn(ACONST_NULL);
} else if (descr == "Ljava/lang/String;") {
Label nonnull = new Label();
// checkcast to not lie later the type with ctx.fieldInsn
ctx.typeInsn(CHECKCAST, "java/lang/String");
ctx.insn(DUP);
ctx.jumpInsn(IFNONNULL, nonnull);
ctx.insn(POP);
ctx.fieldInsn(GETSTATIC, "yeti/lang/Core", "UNDEF_STR",
"Ljava/lang/String;");
ctx.visitLabel(nonnull);
} else if (descr == "Z") {
Label skip = new Label(), end = new Label();
ctx.jumpInsn(IFEQ, skip);
ctx.fieldInsn(GETSTATIC, "java/lang/Boolean", "TRUE",
"Ljava/lang/Boolean;");
ctx.jumpInsn(GOTO, end);
ctx.visitLabel(skip);
ctx.fieldInsn(GETSTATIC, "java/lang/Boolean", "FALSE",
"Ljava/lang/Boolean;");
ctx.visitLabel(end);
} else if (descr == "B" || descr == "S" ||
descr == "I" || descr == "J") {
if (descr == "B") {
ctx.intConst(0xff);
ctx.insn(IAND);
}
ctx.typeInsn(NEW, "yeti/lang/IntNum");
if (descr == "J") {
ctx.insn(DUP_X2);
ctx.insn(DUP_X2);
ctx.insn(POP);
} else {
ctx.insn(DUP_X1);
ctx.insn(SWAP);
}
ctx.visitInit("yeti/lang/IntNum",
descr == "J" ? "(J)V" : "(I)V");
ctx.forceType("yeti/lang/Num");
} else if (descr == "D" || descr == "F") {
ctx.typeInsn(NEW, "yeti/lang/FloatNum");
if (descr == "F") {
ctx.insn(DUP_X1);
ctx.insn(SWAP);
ctx.insn(F2D);
} else {
ctx.insn(DUP_X2);
ctx.insn(DUP_X2);
ctx.insn(POP);
}
ctx.visitInit("yeti/lang/FloatNum", "(D)V");
ctx.forceType("yeti/lang/Num");
} else if (descr == "C") {
ctx.methodInsn(INVOKESTATIC, "java/lang/String",
"valueOf", "(C)Ljava/lang/String;");
ctx.forceType("java/lang/String");
}
}
void gen(Ctx ctx) {
throw new UnsupportedOperationException();
}
}
| false | true | private static void convert(Ctx ctx, YType given, YType argType) {
given = given.deref();
argType = argType.deref();
String descr = argType.javaType == null
? "" : argType.javaType.description;
if (argType.type == YetiType.JAVA_ARRAY &&
given.type == YetiType.JAVA_ARRAY) {
ctx.typeInsn(CHECKCAST, JavaType.descriptionOf(argType));
return; // better than thinking, that array was given...
// still FIXME for a case of different arrays
}
if (given.type != YetiType.JAVA &&
(argType.type == YetiType.JAVA_ARRAY ||
argType.type == YetiType.JAVA &&
argType.javaType.isCollection())) {
Label retry = new Label(), end = new Label();
ctx.typeInsn(CHECKCAST, "yeti/lang/AIter"); // i
String tmpClass = descr != "Ljava/lang/Set;"
? "java/util/ArrayList" : "java/util/HashSet";
ctx.typeInsn(NEW, tmpClass); // ia
ctx.insn(DUP); // iaa
ctx.visitInit(tmpClass, "()V"); // ia
ctx.insn(SWAP); // ai
ctx.insn(DUP); // aii
ctx.jumpInsn(IFNULL, end); // ai
ctx.insn(DUP); // aii
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/AIter",
"isEmpty", "()Z"); // aiz
ctx.jumpInsn(IFNE, end); // ai
ctx.visitLabel(retry);
ctx.insn(DUP2); // aiai
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/AIter",
"first", "()Ljava/lang/Object;");
YType t = null;
if (argType.param.length != 0 &&
((t = argType.param[0]).type != YetiType.JAVA ||
t.javaType.description.length() > 1)) {
convert(ctx, given.param[0], argType.param[0]);
}
// aiav
ctx.methodInsn(INVOKEVIRTUAL, tmpClass,
"add", "(Ljava/lang/Object;)Z"); // aiz
ctx.insn(POP); // ai
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/AIter",
"next", "()Lyeti/lang/AIter;"); // ai
ctx.insn(DUP); // aii
ctx.jumpInsn(IFNONNULL, retry); // ai
ctx.visitLabel(end);
ctx.insn(POP); // a
if (argType.type != YetiType.JAVA_ARRAY)
return; // a - List/Set
String s = "";
YType argArrayType = argType;
while ((argType = argType.param[0]).type ==
YetiType.JAVA_ARRAY) {
s += "[";
argArrayType = argType;
}
String arrayPrefix = s;
if (s == "" && argType.javaType.description.length() != 1) {
s = argType.javaType.className();
} else {
s += argType.javaType.description;
}
ctx.insn(DUP); // aa
ctx.methodInsn(INVOKEVIRTUAL, tmpClass,
"size", "()I"); // an
if (t.type != YetiType.JAVA ||
(descr = t.javaType.description).length() != 1) {
ctx.typeInsn(ANEWARRAY, s); // aA
ctx.methodInsn(INVOKEVIRTUAL, tmpClass, "toArray",
"([Ljava/lang/Object;)[Ljava/lang/Object;");
if (!s.equals("java/lang/Object")) {
ctx.typeInsn(CHECKCAST,
arrayPrefix + "[" + argType.javaType.description);
}
return; // A - object array
}
// emulate a fucking for loop to fill primitive array
int index = ctx.localVarCount++;
Label next = new Label(), done = new Label();
ctx.insn(DUP); // ann
ctx.varInsn(ISTORE, index); // an
new NewArrayExpr(argArrayType, null, 0).gen(ctx);
ctx.insn(SWAP); // Aa
ctx.visitLabel(next);
ctx.varInsn(ILOAD, index); // Aan
ctx.jumpInsn(IFEQ, done); // Aa
ctx.visitIntInsn(IINC, index); // Aa --index
ctx.insn(DUP2); // AaAa
ctx.varInsn(ILOAD, index); // AaAan
ctx.methodInsn(INVOKEVIRTUAL, tmpClass,
"get", "(I)Ljava/lang/Object;"); // AaAv
if (descr == "Z") {
ctx.typeInsn(CHECKCAST, "java/lang/Boolean");
ctx.methodInsn(INVOKEVIRTUAL, "java/lang/Boolean",
"booleanValue", "()Z");
} else {
ctx.typeInsn(CHECKCAST, "yeti/lang/Num");
convertNum(ctx, descr);
}
ctx.varInsn(ILOAD, index); // AaAvn
ctx.insn(SWAP); // AaAnv
int insn = BASTORE;
switch (argType.javaType.description.charAt(0)) {
case 'D': insn = DASTORE; break;
case 'F': insn = FASTORE; break;
case 'I': insn = IASTORE; break;
case 'J': insn = LASTORE; break;
case 'S': insn = SASTORE;
}
ctx.insn(insn); // Aa
ctx.jumpInsn(GOTO, next); // Aa
ctx.visitLabel(done);
ctx.insn(POP); // A
return; // A - primitive array
}
if (given.type == YetiType.STR) {
ctx.typeInsn(CHECKCAST, "java/lang/String");
ctx.insn(DUP);
ctx.fieldInsn(GETSTATIC, "yeti/lang/Core", "UNDEF_STR",
"Ljava/lang/String;");
Label defined = new Label();
ctx.jumpInsn(IF_ACMPNE, defined);
ctx.insn(POP);
ctx.insn(ACONST_NULL);
ctx.visitLabel(defined);
return;
}
if (given.type != YetiType.NUM ||
descr == "Ljava/lang/Object;" ||
descr == "Ljava/lang/Number;") {
if (descr != "Ljava/lang/Object;") {
ctx.typeInsn(CHECKCAST, argType.javaType.className());
}
return;
}
// Convert numbers...
ctx.typeInsn(CHECKCAST, "yeti/lang/Num");
if (descr == "Ljava/math/BigInteger;") {
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/Num",
"toBigInteger", "()Ljava/math/BigInteger;");
return;
}
if (descr == "Ljava/math/BigDecimal;") {
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/Num",
"toBigDecimal", "()Ljava/math/BigDecimal;");
return;
}
String newInstr = null;
if (descr.startsWith("Ljava/lang/")) {
newInstr = argType.javaType.className();
ctx.typeInsn(NEW, newInstr);
ctx.insn(DUP_X1);
ctx.insn(SWAP);
descr = descr.substring(11, 12);
}
convertNum(ctx, descr);
if (newInstr != null) {
ctx.visitInit(newInstr, "(" + descr + ")V");
}
}
| private static void convert(Ctx ctx, YType given, YType argType) {
given = given.deref();
argType = argType.deref();
String descr = argType.javaType == null
? "" : argType.javaType.description;
if (argType.type == YetiType.JAVA_ARRAY &&
given.type == YetiType.JAVA_ARRAY) {
ctx.typeInsn(CHECKCAST, JavaType.descriptionOf(argType));
return; // better than thinking, that array was given...
// still FIXME for a case of different arrays
}
if (given.type != YetiType.JAVA &&
(argType.type == YetiType.JAVA_ARRAY ||
argType.type == YetiType.JAVA &&
argType.javaType.isCollection())) {
Label retry = new Label(), end = new Label();
ctx.typeInsn(CHECKCAST, "yeti/lang/AIter"); // i
String tmpClass = descr != "Ljava/lang/Set;"
? "java/util/ArrayList" : "java/util/HashSet";
ctx.typeInsn(NEW, tmpClass); // ia
ctx.insn(DUP); // iaa
ctx.visitInit(tmpClass, "()V"); // ia
ctx.insn(SWAP); // ai
ctx.insn(DUP); // aii
ctx.jumpInsn(IFNULL, end); // ai
ctx.insn(DUP); // aii
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/AIter",
"isEmpty", "()Z"); // aiz
ctx.jumpInsn(IFNE, end); // ai
ctx.visitLabel(retry);
ctx.insn(DUP2); // aiai
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/AIter",
"first", "()Ljava/lang/Object;");
YType t = null;
if (argType.param.length != 0 &&
((t = argType.param[0]).type != YetiType.JAVA ||
t.javaType.description.length() > 1)) {
convert(ctx, given.param[0], argType.param[0]);
}
// aiav
ctx.methodInsn(INVOKEVIRTUAL, tmpClass,
"add", "(Ljava/lang/Object;)Z"); // aiz
ctx.insn(POP); // ai
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/AIter",
"next", "()Lyeti/lang/AIter;"); // ai
ctx.insn(DUP); // aii
ctx.jumpInsn(IFNONNULL, retry); // ai
ctx.visitLabel(end);
ctx.insn(POP); // a
if (argType.type != YetiType.JAVA_ARRAY)
return; // a - List/Set
String s = "";
YType argArrayType = argType;
while ((argType = argType.param[0]).type ==
YetiType.JAVA_ARRAY) {
s += "[";
argArrayType = argType;
}
String arrayPrefix = s;
if (s == "" && argType.javaType.description.length() != 1) {
s = argType.javaType.className();
} else {
s += argType.javaType.description;
}
ctx.insn(DUP); // aa
ctx.methodInsn(INVOKEVIRTUAL, tmpClass,
"size", "()I"); // an
if (t.type != YetiType.JAVA ||
(descr = t.javaType.description).length() != 1) {
ctx.typeInsn(ANEWARRAY, s); // aA
ctx.methodInsn(INVOKEVIRTUAL, tmpClass, "toArray",
"([Ljava/lang/Object;)[Ljava/lang/Object;");
if (!s.equals("java/lang/Object")) {
ctx.typeInsn(CHECKCAST,
arrayPrefix + "[" + argType.javaType.description);
}
return; // A - object array
}
// emulate a fucking for loop to fill primitive array
int index = ctx.localVarCount++;
Label next = new Label(), done = new Label();
ctx.insn(DUP); // ann
ctx.varInsn(ISTORE, index); // an
new NewArrayExpr(argArrayType, null, 0).gen(ctx);
ctx.insn(SWAP); // Aa
ctx.visitLabel(next);
ctx.varInsn(ILOAD, index); // Aan
ctx.jumpInsn(IFEQ, done); // Aa
ctx.visitIntInsn(IINC, index); // Aa --index
ctx.insn(DUP2); // AaAa
ctx.varInsn(ILOAD, index); // AaAan
ctx.methodInsn(INVOKEVIRTUAL, tmpClass,
"get", "(I)Ljava/lang/Object;"); // AaAv
if (descr == "Z") {
ctx.typeInsn(CHECKCAST, "java/lang/Boolean");
ctx.methodInsn(INVOKEVIRTUAL, "java/lang/Boolean",
"booleanValue", "()Z");
} else {
ctx.typeInsn(CHECKCAST, "yeti/lang/Num");
convertNum(ctx, descr);
}
ctx.varInsn(ILOAD, index); // AaAvn
int insn = BASTORE;
switch (argType.javaType.description.charAt(0)) {
case 'D': insn = DASTORE; break;
case 'F': insn = FASTORE; break;
case 'I': insn = IASTORE; break;
case 'J': insn = LASTORE; break;
case 'S': insn = SASTORE;
}
if (insn == DASTORE || insn == LASTORE) {
// AaAvvn actually - long and double is 2 entries
ctx.insn(DUP_X2); // AaAnvvn
ctx.insn(POP); // AaAnvv
} else {
ctx.insn(SWAP); // AaAnv
}
ctx.insn(insn); // Aa
ctx.jumpInsn(GOTO, next); // Aa
ctx.visitLabel(done);
ctx.insn(POP); // A
return; // A - primitive array
}
if (given.type == YetiType.STR) {
ctx.typeInsn(CHECKCAST, "java/lang/String");
ctx.insn(DUP);
ctx.fieldInsn(GETSTATIC, "yeti/lang/Core", "UNDEF_STR",
"Ljava/lang/String;");
Label defined = new Label();
ctx.jumpInsn(IF_ACMPNE, defined);
ctx.insn(POP);
ctx.insn(ACONST_NULL);
ctx.visitLabel(defined);
return;
}
if (given.type != YetiType.NUM ||
descr == "Ljava/lang/Object;" ||
descr == "Ljava/lang/Number;") {
if (descr != "Ljava/lang/Object;") {
ctx.typeInsn(CHECKCAST, argType.javaType.className());
}
return;
}
// Convert numbers...
ctx.typeInsn(CHECKCAST, "yeti/lang/Num");
if (descr == "Ljava/math/BigInteger;") {
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/Num",
"toBigInteger", "()Ljava/math/BigInteger;");
return;
}
if (descr == "Ljava/math/BigDecimal;") {
ctx.methodInsn(INVOKEVIRTUAL, "yeti/lang/Num",
"toBigDecimal", "()Ljava/math/BigDecimal;");
return;
}
String newInstr = null;
if (descr.startsWith("Ljava/lang/")) {
newInstr = argType.javaType.className();
ctx.typeInsn(NEW, newInstr);
ctx.insn(DUP_X1);
ctx.insn(SWAP);
descr = descr.substring(11, 12);
}
convertNum(ctx, descr);
if (newInstr != null) {
ctx.visitInit(newInstr, "(" + descr + ")V");
}
}
|
diff --git a/Todo.Apps/Android/src/net/christianweyer/tudus/MainActivity.java b/Todo.Apps/Android/src/net/christianweyer/tudus/MainActivity.java
index 96dea58..b0d06d7 100644
--- a/Todo.Apps/Android/src/net/christianweyer/tudus/MainActivity.java
+++ b/Todo.Apps/Android/src/net/christianweyer/tudus/MainActivity.java
@@ -1,16 +1,17 @@
package net.christianweyer.tudus;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import org.apache.cordova.*;
public class MainActivity extends DroidGap {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
- super.loadUrl("file:///android_asset/www/views/index.html", 3000);
+ super.setIntegerProperty("loadUrlTimeoutValue", 10000);
+ super.loadUrl("file:///android_asset/www/views/index.html", 5000);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/views/index.html", 3000);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.setIntegerProperty("loadUrlTimeoutValue", 10000);
super.loadUrl("file:///android_asset/www/views/index.html", 5000);
}
|
diff --git a/src/main/java/com/ning/metrics/collector/binder/FileSystemProvider.java b/src/main/java/com/ning/metrics/collector/binder/FileSystemProvider.java
index 4343d12..1b7f19f 100644
--- a/src/main/java/com/ning/metrics/collector/binder/FileSystemProvider.java
+++ b/src/main/java/com/ning/metrics/collector/binder/FileSystemProvider.java
@@ -1,58 +1,58 @@
/*
* Copyright 2010 Ning, Inc.
*
* Ning 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 com.ning.metrics.collector.binder;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.ning.metrics.collector.binder.config.CollectorConfig;
import com.ning.metrics.collector.events.hadoop.serialization.HadoopThriftEnvelopeSerialization;
import com.ning.metrics.collector.events.hadoop.serialization.HadoopThriftWritableSerialization;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import java.io.IOException;
public class FileSystemProvider implements Provider<FileSystem>
{
private final FileSystem fileSystem;
@Inject
public FileSystemProvider(CollectorConfig collectorConfig) throws IOException
{
String hfsHost = collectorConfig.getHfsHost();
Configuration hadoopConfig = new Configuration();
if (hfsHost.isEmpty()) {
// Local filesystem, for testing
hadoopConfig.set("fs.default.name", "file:///");
}
else {
hadoopConfig.set("fs.default.name", hfsHost);
}
hadoopConfig.setLong("dfs.block.size", collectorConfig.getHadoopBlockSize());
hadoopConfig.set("serialization.job.ugi", collectorConfig.getHadoopUgi());
- hadoopConfig.setStrings("io.serializations", HadoopThriftWritableSerialization.class.getName(), HadoopThriftEnvelopeSerialization.class.getName(), "org.apache.serialization.io.serializer.WritableSerialization");
+ hadoopConfig.setStrings("io.serializations", HadoopThriftWritableSerialization.class.getName(), HadoopThriftEnvelopeSerialization.class.getName(), "org.apache.hadoop.io.serializer.WritableSerialization");
fileSystem = FileSystem.get(hadoopConfig);
}
public FileSystem get()
{
return fileSystem;
}
}
| true | true | public FileSystemProvider(CollectorConfig collectorConfig) throws IOException
{
String hfsHost = collectorConfig.getHfsHost();
Configuration hadoopConfig = new Configuration();
if (hfsHost.isEmpty()) {
// Local filesystem, for testing
hadoopConfig.set("fs.default.name", "file:///");
}
else {
hadoopConfig.set("fs.default.name", hfsHost);
}
hadoopConfig.setLong("dfs.block.size", collectorConfig.getHadoopBlockSize());
hadoopConfig.set("serialization.job.ugi", collectorConfig.getHadoopUgi());
hadoopConfig.setStrings("io.serializations", HadoopThriftWritableSerialization.class.getName(), HadoopThriftEnvelopeSerialization.class.getName(), "org.apache.serialization.io.serializer.WritableSerialization");
fileSystem = FileSystem.get(hadoopConfig);
}
| public FileSystemProvider(CollectorConfig collectorConfig) throws IOException
{
String hfsHost = collectorConfig.getHfsHost();
Configuration hadoopConfig = new Configuration();
if (hfsHost.isEmpty()) {
// Local filesystem, for testing
hadoopConfig.set("fs.default.name", "file:///");
}
else {
hadoopConfig.set("fs.default.name", hfsHost);
}
hadoopConfig.setLong("dfs.block.size", collectorConfig.getHadoopBlockSize());
hadoopConfig.set("serialization.job.ugi", collectorConfig.getHadoopUgi());
hadoopConfig.setStrings("io.serializations", HadoopThriftWritableSerialization.class.getName(), HadoopThriftEnvelopeSerialization.class.getName(), "org.apache.hadoop.io.serializer.WritableSerialization");
fileSystem = FileSystem.get(hadoopConfig);
}
|
diff --git a/Coupling/src/coupling/app/BL/BLShopListOverview.java b/Coupling/src/coupling/app/BL/BLShopListOverview.java
index 2eca43a..ab0a701 100644
--- a/Coupling/src/coupling/app/BL/BLShopListOverview.java
+++ b/Coupling/src/coupling/app/BL/BLShopListOverview.java
@@ -1,93 +1,93 @@
package coupling.app.BL;
import org.json.JSONException;
import org.json.JSONObject;
import android.database.Cursor;
import coupling.app.Ids;
import coupling.app.com.API;
import coupling.app.com.AppFeature;
import coupling.app.com.IBLConnector;
import coupling.app.com.Message;
import coupling.app.data.DALShopListOverview;
import coupling.app.data.Enums.ActionType;
import coupling.app.data.Enums.CategoryType;
import static coupling.app.com.Constants.*;
public class BLShopListOverview extends AppFeature {
private static final String TITLE = "Title";
private DALShopListOverview dataSource;
private API api;
private IBLConnector connector;
public BLShopListOverview(){
dataSource = DALShopListOverview.getInstance();
categoryType = CategoryType.SHOPLIST_OVERVIEW;
api = API.getInstance();
}
public Cursor getSource(){
return dataSource.getSource();
}
public boolean createList(String title){
return createList(null,title, true);
}
public boolean createList(Long UId, String title, boolean remote){
long localId = dataSource.createList(UId,title);
boolean isCreated = (localId != -1);
if(remote && isCreated){
Message message = new Message();
message.getData().put(LOCALID, localId);
message.getData().put(UID, UId);
message.getData().put(TITLE, title);
message.setCategoryType(categoryType);
message.setActionType(ActionType.CREATE);
api.sync(message);
}
return isCreated;
}
@Override
public void recieveData(JSONObject data, ActionType actionType) {
try{
Ids ids = new Ids();
- if(data.has(UID) && data.get(UID).equals("null"))
+ if(data.has(UID) && !data.get(UID).equals(null))
ids.setGlobalId(data.getLong(UID));
String title = null;
if(data.has(TITLE)) title = data.getString(TITLE);
switch (actionType) {
case CREATE:
createList(ids.getGlobalId(), title, false);
break;
}
if(connector != null)
connector.Refresh();
}catch(JSONException e){
e.printStackTrace();
}
}
@Override
public boolean updateId(Ids ids) {
return dataSource.updateId(ids);
}
public void setBLConnector(IBLConnector connector){
this.connector = connector;
}
public void unsetBLConnector(){
this.connector = null;
}
}
| true | true | public void recieveData(JSONObject data, ActionType actionType) {
try{
Ids ids = new Ids();
if(data.has(UID) && data.get(UID).equals("null"))
ids.setGlobalId(data.getLong(UID));
String title = null;
if(data.has(TITLE)) title = data.getString(TITLE);
switch (actionType) {
case CREATE:
createList(ids.getGlobalId(), title, false);
break;
}
if(connector != null)
connector.Refresh();
}catch(JSONException e){
e.printStackTrace();
}
}
| public void recieveData(JSONObject data, ActionType actionType) {
try{
Ids ids = new Ids();
if(data.has(UID) && !data.get(UID).equals(null))
ids.setGlobalId(data.getLong(UID));
String title = null;
if(data.has(TITLE)) title = data.getString(TITLE);
switch (actionType) {
case CREATE:
createList(ids.getGlobalId(), title, false);
break;
}
if(connector != null)
connector.Refresh();
}catch(JSONException e){
e.printStackTrace();
}
}
|
diff --git a/org.eclipse.m2e.tests/src/org/eclipse/m2e/tests/MarkerTest.java b/org.eclipse.m2e.tests/src/org/eclipse/m2e/tests/MarkerTest.java
index 04a714e9..c1857378 100644
--- a/org.eclipse.m2e.tests/src/org/eclipse/m2e/tests/MarkerTest.java
+++ b/org.eclipse.m2e.tests/src/org/eclipse/m2e/tests/MarkerTest.java
@@ -1,93 +1,93 @@
package org.eclipse.m2e.tests;
import java.util.List;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.core.IMavenConstants;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.project.ResolverConfiguration;
import org.eclipse.m2e.tests.common.AbstractMavenProjectTestCase;
import org.eclipse.m2e.tests.common.WorkspaceHelpers;
public class MarkerTest extends AbstractMavenProjectTestCase {
@SuppressWarnings("restriction")
public void test() throws Exception {
// Import a project with bad pom.xml
IProject project = createExisting("markerTest", "projects/markers");
waitForJobsToComplete();
assertNotNull("Expected not null project", project);
IMavenProjectFacade facade = MavenPlugin.getDefault().getMavenProjectManagerImpl().create(project, monitor);
assertNull("Expected null MavenProjectFacade", facade);
String expectedErrorMessage = "Project build error: Non-readable POM ";
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_POM_LOADING_ID, expectedErrorMessage,
1 /*lineNumber*/, project);
// Fix the pom, introduce a configuration problem
copyContent(project, "pom_badConfiguration.xml", "pom.xml");
waitForJobsToComplete();
facade = MavenPlugin.getDefault().getMavenProjectManagerImpl().getProject(project);
assertNotNull("Expected not null MavenProjectFacade", facade);
project = facade.getProject();
expectedErrorMessage = "Unknown or missing lifecycle mapping with id=\"MISSING\" (project packaging type=\"war\")";
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_CONFIGURATION_ID, expectedErrorMessage,
1 /*lineNumber*/, project);
// Building the project should not remove the marker
project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
waitForJobsToComplete();
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_CONFIGURATION_ID, expectedErrorMessage,
1 /*lineNumber*/, project);
// Fix the current configuration problem, introduce a new one
copyContent(project, "pom_badConfiguration1.xml", "pom.xml");
waitForJobsToComplete();
expectedErrorMessage = "Mojo execution not covered by lifecycle configuration: org.codehaus.modello:modello-maven-plugin:1.1:java {execution: standard} (maven lifecycle phase: generate-sources)";
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_CONFIGURATION_ID, expectedErrorMessage,
1 /*lineNumber*/, project);
// Fix the current configuration problem, introduce a dependency problem
copyContent(project, "pom_badDependency.xml", "pom.xml");
waitForJobsToComplete();
MavenPlugin
.getDefault()
.getProjectConfigurationManager()
- .updateProjectConfiguration(project, new ResolverConfiguration(), mavenConfiguration.getGoalOnImport(), monitor);
+ .updateProjectConfiguration(project, new ResolverConfiguration(), monitor);
expectedErrorMessage = "Missing artifact missing:missing:jar:0.0.0:compile";
List<IMarker> markers = WorkspaceHelpers.findErrorMarkers(project);
// (jdt) The container 'Maven Dependencies' references non existing library ...missing/missing/0.0.0/missing-0.0.0.jar'
// (maven) Missing artifact missing:missing:jar:0.0.0:compile
assertEquals(WorkspaceHelpers.toString(markers), 2, markers.size());
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_DEPENDENCY_ID, expectedErrorMessage, 1 /*lineNumber*/,
markers.get(1));
// Building the project should not remove the marker
project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
waitForJobsToComplete();
markers = WorkspaceHelpers.findErrorMarkers(project);
// (jdt) The container 'Maven Dependencies' references non existing library ...missing/missing/0.0.0/missing-0.0.0.jar'
// (jdt) The project cannot be built until build path errors are resolved
// (maven) Missing artifact missing:missing:jar:0.0.0:compile
assertEquals(WorkspaceHelpers.toString(markers), 3, markers.size());
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_DEPENDENCY_ID, expectedErrorMessage, 1 /*lineNumber*/,
markers.get(2));
// Fix the current dependency problem
copyContent(project, "pom_good.xml", "pom.xml");
waitForJobsToComplete();
WorkspaceHelpers.assertErrorMarker("org.eclipse.jdt.core.problem",
"The project cannot be built until build path errors are resolved", null /*lineNumber*/,
project);
}
protected IMavenProjectFacade importMavenProject(String basedir, String pomName) throws Exception {
ResolverConfiguration configuration = new ResolverConfiguration();
IProject[] project = importProjects(basedir, new String[] {pomName}, configuration);
waitForJobsToComplete();
return MavenPlugin.getDefault().getMavenProjectManager().create(project[0], monitor);
}
}
| true | true | public void test() throws Exception {
// Import a project with bad pom.xml
IProject project = createExisting("markerTest", "projects/markers");
waitForJobsToComplete();
assertNotNull("Expected not null project", project);
IMavenProjectFacade facade = MavenPlugin.getDefault().getMavenProjectManagerImpl().create(project, monitor);
assertNull("Expected null MavenProjectFacade", facade);
String expectedErrorMessage = "Project build error: Non-readable POM ";
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_POM_LOADING_ID, expectedErrorMessage,
1 /*lineNumber*/, project);
// Fix the pom, introduce a configuration problem
copyContent(project, "pom_badConfiguration.xml", "pom.xml");
waitForJobsToComplete();
facade = MavenPlugin.getDefault().getMavenProjectManagerImpl().getProject(project);
assertNotNull("Expected not null MavenProjectFacade", facade);
project = facade.getProject();
expectedErrorMessage = "Unknown or missing lifecycle mapping with id=\"MISSING\" (project packaging type=\"war\")";
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_CONFIGURATION_ID, expectedErrorMessage,
1 /*lineNumber*/, project);
// Building the project should not remove the marker
project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
waitForJobsToComplete();
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_CONFIGURATION_ID, expectedErrorMessage,
1 /*lineNumber*/, project);
// Fix the current configuration problem, introduce a new one
copyContent(project, "pom_badConfiguration1.xml", "pom.xml");
waitForJobsToComplete();
expectedErrorMessage = "Mojo execution not covered by lifecycle configuration: org.codehaus.modello:modello-maven-plugin:1.1:java {execution: standard} (maven lifecycle phase: generate-sources)";
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_CONFIGURATION_ID, expectedErrorMessage,
1 /*lineNumber*/, project);
// Fix the current configuration problem, introduce a dependency problem
copyContent(project, "pom_badDependency.xml", "pom.xml");
waitForJobsToComplete();
MavenPlugin
.getDefault()
.getProjectConfigurationManager()
.updateProjectConfiguration(project, new ResolverConfiguration(), mavenConfiguration.getGoalOnImport(), monitor);
expectedErrorMessage = "Missing artifact missing:missing:jar:0.0.0:compile";
List<IMarker> markers = WorkspaceHelpers.findErrorMarkers(project);
// (jdt) The container 'Maven Dependencies' references non existing library ...missing/missing/0.0.0/missing-0.0.0.jar'
// (maven) Missing artifact missing:missing:jar:0.0.0:compile
assertEquals(WorkspaceHelpers.toString(markers), 2, markers.size());
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_DEPENDENCY_ID, expectedErrorMessage, 1 /*lineNumber*/,
markers.get(1));
// Building the project should not remove the marker
project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
waitForJobsToComplete();
markers = WorkspaceHelpers.findErrorMarkers(project);
// (jdt) The container 'Maven Dependencies' references non existing library ...missing/missing/0.0.0/missing-0.0.0.jar'
// (jdt) The project cannot be built until build path errors are resolved
// (maven) Missing artifact missing:missing:jar:0.0.0:compile
assertEquals(WorkspaceHelpers.toString(markers), 3, markers.size());
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_DEPENDENCY_ID, expectedErrorMessage, 1 /*lineNumber*/,
markers.get(2));
// Fix the current dependency problem
copyContent(project, "pom_good.xml", "pom.xml");
waitForJobsToComplete();
WorkspaceHelpers.assertErrorMarker("org.eclipse.jdt.core.problem",
"The project cannot be built until build path errors are resolved", null /*lineNumber*/,
project);
}
| public void test() throws Exception {
// Import a project with bad pom.xml
IProject project = createExisting("markerTest", "projects/markers");
waitForJobsToComplete();
assertNotNull("Expected not null project", project);
IMavenProjectFacade facade = MavenPlugin.getDefault().getMavenProjectManagerImpl().create(project, monitor);
assertNull("Expected null MavenProjectFacade", facade);
String expectedErrorMessage = "Project build error: Non-readable POM ";
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_POM_LOADING_ID, expectedErrorMessage,
1 /*lineNumber*/, project);
// Fix the pom, introduce a configuration problem
copyContent(project, "pom_badConfiguration.xml", "pom.xml");
waitForJobsToComplete();
facade = MavenPlugin.getDefault().getMavenProjectManagerImpl().getProject(project);
assertNotNull("Expected not null MavenProjectFacade", facade);
project = facade.getProject();
expectedErrorMessage = "Unknown or missing lifecycle mapping with id=\"MISSING\" (project packaging type=\"war\")";
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_CONFIGURATION_ID, expectedErrorMessage,
1 /*lineNumber*/, project);
// Building the project should not remove the marker
project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
waitForJobsToComplete();
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_CONFIGURATION_ID, expectedErrorMessage,
1 /*lineNumber*/, project);
// Fix the current configuration problem, introduce a new one
copyContent(project, "pom_badConfiguration1.xml", "pom.xml");
waitForJobsToComplete();
expectedErrorMessage = "Mojo execution not covered by lifecycle configuration: org.codehaus.modello:modello-maven-plugin:1.1:java {execution: standard} (maven lifecycle phase: generate-sources)";
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_CONFIGURATION_ID, expectedErrorMessage,
1 /*lineNumber*/, project);
// Fix the current configuration problem, introduce a dependency problem
copyContent(project, "pom_badDependency.xml", "pom.xml");
waitForJobsToComplete();
MavenPlugin
.getDefault()
.getProjectConfigurationManager()
.updateProjectConfiguration(project, new ResolverConfiguration(), monitor);
expectedErrorMessage = "Missing artifact missing:missing:jar:0.0.0:compile";
List<IMarker> markers = WorkspaceHelpers.findErrorMarkers(project);
// (jdt) The container 'Maven Dependencies' references non existing library ...missing/missing/0.0.0/missing-0.0.0.jar'
// (maven) Missing artifact missing:missing:jar:0.0.0:compile
assertEquals(WorkspaceHelpers.toString(markers), 2, markers.size());
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_DEPENDENCY_ID, expectedErrorMessage, 1 /*lineNumber*/,
markers.get(1));
// Building the project should not remove the marker
project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
waitForJobsToComplete();
markers = WorkspaceHelpers.findErrorMarkers(project);
// (jdt) The container 'Maven Dependencies' references non existing library ...missing/missing/0.0.0/missing-0.0.0.jar'
// (jdt) The project cannot be built until build path errors are resolved
// (maven) Missing artifact missing:missing:jar:0.0.0:compile
assertEquals(WorkspaceHelpers.toString(markers), 3, markers.size());
WorkspaceHelpers.assertErrorMarker(IMavenConstants.MARKER_DEPENDENCY_ID, expectedErrorMessage, 1 /*lineNumber*/,
markers.get(2));
// Fix the current dependency problem
copyContent(project, "pom_good.xml", "pom.xml");
waitForJobsToComplete();
WorkspaceHelpers.assertErrorMarker("org.eclipse.jdt.core.problem",
"The project cannot be built until build path errors are resolved", null /*lineNumber*/,
project);
}
|
diff --git a/enough-polish-j2me/source/src/de/enough/polish/ui/UniformContainer.java b/enough-polish-j2me/source/src/de/enough/polish/ui/UniformContainer.java
index f336edb..f9e4bdd 100644
--- a/enough-polish-j2me/source/src/de/enough/polish/ui/UniformContainer.java
+++ b/enough-polish-j2me/source/src/de/enough/polish/ui/UniformContainer.java
@@ -1,478 +1,481 @@
//#condition polish.usePolishGui
/*
* Created on Sept 24, 2012 at 10:18:40 PM.
*
* Copyright (c) 2012 Robert Virkus / Enough Software
*
* This file is part of J2ME Polish.
*
* J2ME Polish 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.
*
* J2ME Polish 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 J2ME Polish; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Commercial licenses are also available, please
* refer to the accompanying LICENSE.txt or visit
* http://www.j2mepolish.org for details.
*/
package de.enough.polish.ui;
import de.enough.polish.util.IntHashMap;
/**
* A container that contains only uniform items, meaning all items have the same type and same height.
* @author Robert Virkus, j2mepolish@enough.de
*/
public class UniformContainer
extends Container
implements ItemConsumer
{
private UniformItemSource itemSource;
private int childRowHeight;
private int childStartIndex;
private final BackupItemStorage backupItemStorage;
private boolean isIgnoreYOffsetChange;
/**
* Creates a new container
*
* @param itemSource the item source
*/
public UniformContainer(UniformItemSource itemSource)
{
this( itemSource, false, null);
}
/**
* Creates a new container
*
* @param itemSource the item source
* @param style the style
*/
public UniformContainer(UniformItemSource itemSource, Style style)
{
this( itemSource, false, style);
}
/**
* Creates a new container
*
* @param itemSource the item source
* @param focusFirst true when the first item should be focused automatically
*/
public UniformContainer(UniformItemSource itemSource, boolean focusFirst )
{
this( itemSource, focusFirst, null );
}
/**
* Creates a new container
*
* @param itemSource the item source
* @param focusFirst true when the first item should be focused automatically
* @param style the style
*/
public UniformContainer(UniformItemSource itemSource, boolean focusFirst, Style style )
{
super(focusFirst, style );
if (itemSource == null) {
throw new NullPointerException();
}
this.itemSource = itemSource;
itemSource.setItemConsumer(this);
this.backupItemStorage = new BackupItemStorage(10);
}
/**
* Sets a new item source
* @param itemSource the new item source
* @throws NullPointerException when itemSource is null
*/
public void setItemSource( UniformItemSource itemSource)
{
if (itemSource == null) {
throw new NullPointerException();
}
this.itemSource = itemSource;
requestInit();
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#initContent(int, int, int)
*/
protected void initContent(int firstLineWidth, int availWidth, int availHeight)
{
synchronized (this.itemsList)
{
this.itemsList.clear();
int count = this.itemSource.countItems();
if (count == 0)
{
this.contentHeight = 0;
return;
}
Item item = this.itemSource.createItem(0);
item.parent = this;
this.itemsList.add(item);
int rowHeight = item.getItemHeight(firstLineWidth, availWidth, availHeight) + this.paddingVertical;
this.childRowHeight = rowHeight;
int startIndex = Math.max( 0, (-this.yOffset)/rowHeight - 5);
if (startIndex != 0)
{
this.itemSource.populateItem(startIndex, item);
}
int height = (count * rowHeight) - this.paddingVertical;
this.contentHeight = height;
this.contentWidth = item.itemWidth;
int numberOfRealItems = Math.min( count, (availHeight / rowHeight) + 10);
if (count > numberOfRealItems)
{
startIndex = Math.min(count - numberOfRealItems, startIndex);
}
this.childStartIndex = startIndex;
for (int itemIndex=startIndex + 1; itemIndex < startIndex + numberOfRealItems; itemIndex++) {
item = this.itemSource.createItem(itemIndex);
item.parent = this;
item.getItemHeight(firstLineWidth, availWidth, availHeight);
item.relativeY = itemIndex * rowHeight;
this.itemsList.add(item);
}
if (this.autoFocusEnabled)
{
this.autoFocusEnabled = false;
int index = this.autoFocusIndex;
if (index < startIndex)
{
index = startIndex;
}
else if (index > startIndex + numberOfRealItems)
{
index = startIndex + numberOfRealItems;
}
focusChild(index);
}
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#onScrollYOffsetChanged(int)
*/
protected void onScrollYOffsetChanged(int offset)
{
if (this.isIgnoreYOffsetChange)
{
return;
}
- int startIndex = Math.max( 0, (-offset)/this.childRowHeight - 5);
int count = this.itemSource.countItems();
int itemsListSize = this.itemsList.size();
+ if (count <= itemsListSize)
+ {
+ return;
+ }
+ int startIndex = Math.max( 0, (-offset)/this.childRowHeight - 5);
if (count > itemsListSize)
{
startIndex = Math.min(count - itemsListSize, startIndex);
}
int delta = Math.abs(startIndex - this.childStartIndex);
if (delta != 0) {
synchronized (getSynchronizationLock())
{
itemsListSize = this.itemsList.size();
if (count > itemsListSize)
{
startIndex = Math.min(count - itemsListSize, startIndex);
}
delta = Math.abs(startIndex - this.childStartIndex);
if (delta >= itemsListSize)
{
- //System.out.println("replacing all");
// all items need to be re=populated:
Object[] items = this.itemsList.getInternalArray();
for (int itemIndex=0; itemIndex<itemsListSize; itemIndex++)
{
int index = startIndex + itemIndex;
//System.out.println(".. current index: " + itemIndex + " / " + index + ", itemsListSize=" + itemsListSize + " / " + itemsList.size());
Item item = this.backupItemStorage.extract(index);
Item prevItem = (Item) items[itemIndex];
if (item != null)
{
item.showNotify();
prevItem.hideNotify();
//this.itemsList.set(itemIndex, item);
items[itemIndex] = item; // this works as we operate on the original array
}
else
{
item = prevItem;
if (item.isFocused) {
focusChild(-1);
}
}
item.setInitialized(false);
this.itemSource.populateItem(index, item);
item.relativeY = index * this.childRowHeight;
int cw = this.availContentWidth;
int ch = this.availContentHeight;
item.getItemHeight(cw, cw, ch);
}
}
else
{
// only some items need to be re-populated
if (startIndex > this.childStartIndex)
{
// scrolling down:
for (int itemIndex=0; itemIndex<delta; itemIndex++)
{
int index = startIndex + itemsListSize - delta + itemIndex;
Item item = this.backupItemStorage.extract(index);
Item prevItem = (Item) this.itemsList.remove(0);
if (prevItem.isFocused)
{
focusChild(-1);
}
if (item != null)
{
item.showNotify();
prevItem.hideNotify();
}
else
{
item = prevItem;
}
this.itemsList.add(item);
item.setInitialized(false);
this.itemSource.populateItem(index, item);
item.relativeY = index * this.childRowHeight;
int cw = this.availContentWidth;
int ch = this.availContentHeight;
item.getItemHeight(cw, cw, ch);
}
}
else
{
// scrolling up:
for (int itemIndex=0; itemIndex<delta; itemIndex++)
{
Item item = (Item) this.itemsList.remove(itemsListSize-1);
if (item.isFocused)
{
focusChild(-1);
}
this.itemsList.add(0, item);
int index = this.childStartIndex - itemIndex - 1;
item.setInitialized(false);
this.itemSource.populateItem(index, item);
item.relativeY = index * this.childRowHeight;
int cw = this.availContentWidth;
int ch = this.availContentHeight;
item.getItemHeight(cw, cw, ch);
}
}
}
this.childStartIndex = startIndex;
}
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#shiftFocus(boolean, int)
*/
protected boolean shiftFocus(boolean forwardFocus, int steps)
{
if (forwardFocus)
{
int itemStartIndex = this.focusedIndex - this.childStartIndex + 1;
int itemsListSize = this.itemsList.size();
if (itemStartIndex >= 0 && itemStartIndex < itemsListSize)
{
for (int itemIndex = itemStartIndex; itemIndex < itemsListSize; itemIndex++)
{
Item item = (Item) this.itemsList.get(itemIndex);
if (item.isInteractive())
{
focusChild(itemStartIndex + this.childStartIndex, item, Canvas.DOWN, false);
return true;
}
}
}
}
else
{
int itemStartIndex = this.focusedIndex - this.childStartIndex - 1;
int itemsListSize = this.itemsList.size();
if (itemStartIndex >= 0 && itemStartIndex < itemsListSize)
{
for (int itemIndex = itemStartIndex; itemIndex >= 0; itemIndex--)
{
Item item = (Item) this.itemsList.get(itemIndex);
if (item.isInteractive())
{
focusChild(itemStartIndex + this.childStartIndex, item, Canvas.UP, false);
return true;
}
}
}
}
return false;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#focusClosestItem(int)
*/
public boolean focusClosestItem(int index) {
int itemStartIndex = index - this.childStartIndex;
int itemsListSize = this.itemsList.size();
if (itemStartIndex >= 0 && itemStartIndex < itemsListSize)
{
for (int itemIndex = itemStartIndex + 1; itemIndex < itemsListSize; itemIndex++)
{
Item item = (Item) this.itemsList.get(itemIndex);
if (item.isInteractive())
{
//TODO ok, now look UP if it's possibly closer...
focusChild(itemStartIndex + this.childStartIndex, item, Canvas.DOWN, false);
return true;
}
}
}
// okay, there was no item found in the current batch:
return false;
// TODO finish focusClosesItem
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#focusClosestItemAbove(int)
*/
public boolean focusClosestItemAbove(int index) {
// TODO Auto-generated method stub
return super.focusClosestItemAbove(index);
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#get(int)
*/
public Item get(int index) {
int itemIndex = index - this.childStartIndex;
int itemsListSize = this.itemsList.size();
if (itemIndex >= 0 && itemIndex < itemsListSize)
{
return (Item) this.itemsList.get(itemIndex);
}
Item item = (Item) this.backupItemStorage.get(index);
if (item != null)
{
return item;
}
item = this.itemSource.createItem(index);
item.parent = this;
item.relativeY = index * this.childRowHeight;
int cw = this.availContentWidth;
int ch = this.availContentHeight;
item.getItemHeight(cw, cw, ch);
this.backupItemStorage.put(itemIndex, item);
return item;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#getPosition(de.enough.polish.ui.Item)
*/
public int getPosition(Item item) {
int index = this.itemsList.indexOf(item);
if (index != -1)
{
index += this.childStartIndex;
}
else
{
int key = this.backupItemStorage.getKeyForValue(item);
if (key != Integer.MIN_VALUE)
{
index = key;
}
}
return index;
}
/*
* (non-Javadoc)
* @see de.enough.polish.ui.ItemConsumer#onItemsChanged(de.enough.polish.ui.ItemChangedEvent)
*/
public void onItemsChanged(ItemChangedEvent event)
{
int change = event.getChange();
if (change == ItemChangedEvent.CHANGE_COMPLETE_REFRESH)
{
synchronized (getSynchronizationLock())
{
this.isIgnoreYOffsetChange = true;
boolean refocus = (this.isFocused && this.focusedItem != null);
if (refocus || this.focusedItem != null)
{
focusChild(-1);
}
setScrollYOffset(0);
if (refocus)
{
focusChild(0);
}
this.isIgnoreYOffsetChange = false;
}
}
else if ((change == ItemChangedEvent.CHANGE_SET) && (event.getItemIndex() == this.focusedIndex))
{
synchronized (getSynchronizationLock())
{
int itemIndex = event.getItemIndex();
if ((itemIndex >= this.childStartIndex) && (itemIndex < this.childStartIndex + this.itemsList.size()))
{
Item affectedItem = event.getAffectedItem();
if (affectedItem == null)
{
affectedItem = (Item) this.itemsList.get(itemIndex - this.childStartIndex);
this.itemSource.populateItem(itemIndex, affectedItem);
}
this.isIgnoreYOffsetChange = true;
int offset = getScrollYOffset();
focusChild( -1 );
this.itemsList.set(itemIndex - this.childStartIndex, affectedItem );
focusChild(itemIndex);
setScrollYOffset(offset, false);
this.isIgnoreYOffsetChange = false;
}
}
}
requestInit();
}
private static class BackupItemStorage
extends IntHashMap
{
private final int maxSize;
BackupItemStorage(int maxSize)
{
this.maxSize = maxSize;
}
public Item extract(int index) {
Item item = (Item) super.remove(index);
return item;
}
}
}
| false | true | protected void onScrollYOffsetChanged(int offset)
{
if (this.isIgnoreYOffsetChange)
{
return;
}
int startIndex = Math.max( 0, (-offset)/this.childRowHeight - 5);
int count = this.itemSource.countItems();
int itemsListSize = this.itemsList.size();
if (count > itemsListSize)
{
startIndex = Math.min(count - itemsListSize, startIndex);
}
int delta = Math.abs(startIndex - this.childStartIndex);
if (delta != 0) {
synchronized (getSynchronizationLock())
{
itemsListSize = this.itemsList.size();
if (count > itemsListSize)
{
startIndex = Math.min(count - itemsListSize, startIndex);
}
delta = Math.abs(startIndex - this.childStartIndex);
if (delta >= itemsListSize)
{
//System.out.println("replacing all");
// all items need to be re=populated:
Object[] items = this.itemsList.getInternalArray();
for (int itemIndex=0; itemIndex<itemsListSize; itemIndex++)
{
int index = startIndex + itemIndex;
//System.out.println(".. current index: " + itemIndex + " / " + index + ", itemsListSize=" + itemsListSize + " / " + itemsList.size());
Item item = this.backupItemStorage.extract(index);
Item prevItem = (Item) items[itemIndex];
if (item != null)
{
item.showNotify();
prevItem.hideNotify();
//this.itemsList.set(itemIndex, item);
items[itemIndex] = item; // this works as we operate on the original array
}
else
{
item = prevItem;
if (item.isFocused) {
focusChild(-1);
}
}
item.setInitialized(false);
this.itemSource.populateItem(index, item);
item.relativeY = index * this.childRowHeight;
int cw = this.availContentWidth;
int ch = this.availContentHeight;
item.getItemHeight(cw, cw, ch);
}
}
else
{
// only some items need to be re-populated
if (startIndex > this.childStartIndex)
{
// scrolling down:
for (int itemIndex=0; itemIndex<delta; itemIndex++)
{
int index = startIndex + itemsListSize - delta + itemIndex;
Item item = this.backupItemStorage.extract(index);
Item prevItem = (Item) this.itemsList.remove(0);
if (prevItem.isFocused)
{
focusChild(-1);
}
if (item != null)
{
item.showNotify();
prevItem.hideNotify();
}
else
{
item = prevItem;
}
this.itemsList.add(item);
item.setInitialized(false);
this.itemSource.populateItem(index, item);
item.relativeY = index * this.childRowHeight;
int cw = this.availContentWidth;
int ch = this.availContentHeight;
item.getItemHeight(cw, cw, ch);
}
}
else
{
// scrolling up:
for (int itemIndex=0; itemIndex<delta; itemIndex++)
{
Item item = (Item) this.itemsList.remove(itemsListSize-1);
if (item.isFocused)
{
focusChild(-1);
}
this.itemsList.add(0, item);
int index = this.childStartIndex - itemIndex - 1;
item.setInitialized(false);
this.itemSource.populateItem(index, item);
item.relativeY = index * this.childRowHeight;
int cw = this.availContentWidth;
int ch = this.availContentHeight;
item.getItemHeight(cw, cw, ch);
}
}
}
this.childStartIndex = startIndex;
}
}
}
| protected void onScrollYOffsetChanged(int offset)
{
if (this.isIgnoreYOffsetChange)
{
return;
}
int count = this.itemSource.countItems();
int itemsListSize = this.itemsList.size();
if (count <= itemsListSize)
{
return;
}
int startIndex = Math.max( 0, (-offset)/this.childRowHeight - 5);
if (count > itemsListSize)
{
startIndex = Math.min(count - itemsListSize, startIndex);
}
int delta = Math.abs(startIndex - this.childStartIndex);
if (delta != 0) {
synchronized (getSynchronizationLock())
{
itemsListSize = this.itemsList.size();
if (count > itemsListSize)
{
startIndex = Math.min(count - itemsListSize, startIndex);
}
delta = Math.abs(startIndex - this.childStartIndex);
if (delta >= itemsListSize)
{
// all items need to be re=populated:
Object[] items = this.itemsList.getInternalArray();
for (int itemIndex=0; itemIndex<itemsListSize; itemIndex++)
{
int index = startIndex + itemIndex;
//System.out.println(".. current index: " + itemIndex + " / " + index + ", itemsListSize=" + itemsListSize + " / " + itemsList.size());
Item item = this.backupItemStorage.extract(index);
Item prevItem = (Item) items[itemIndex];
if (item != null)
{
item.showNotify();
prevItem.hideNotify();
//this.itemsList.set(itemIndex, item);
items[itemIndex] = item; // this works as we operate on the original array
}
else
{
item = prevItem;
if (item.isFocused) {
focusChild(-1);
}
}
item.setInitialized(false);
this.itemSource.populateItem(index, item);
item.relativeY = index * this.childRowHeight;
int cw = this.availContentWidth;
int ch = this.availContentHeight;
item.getItemHeight(cw, cw, ch);
}
}
else
{
// only some items need to be re-populated
if (startIndex > this.childStartIndex)
{
// scrolling down:
for (int itemIndex=0; itemIndex<delta; itemIndex++)
{
int index = startIndex + itemsListSize - delta + itemIndex;
Item item = this.backupItemStorage.extract(index);
Item prevItem = (Item) this.itemsList.remove(0);
if (prevItem.isFocused)
{
focusChild(-1);
}
if (item != null)
{
item.showNotify();
prevItem.hideNotify();
}
else
{
item = prevItem;
}
this.itemsList.add(item);
item.setInitialized(false);
this.itemSource.populateItem(index, item);
item.relativeY = index * this.childRowHeight;
int cw = this.availContentWidth;
int ch = this.availContentHeight;
item.getItemHeight(cw, cw, ch);
}
}
else
{
// scrolling up:
for (int itemIndex=0; itemIndex<delta; itemIndex++)
{
Item item = (Item) this.itemsList.remove(itemsListSize-1);
if (item.isFocused)
{
focusChild(-1);
}
this.itemsList.add(0, item);
int index = this.childStartIndex - itemIndex - 1;
item.setInitialized(false);
this.itemSource.populateItem(index, item);
item.relativeY = index * this.childRowHeight;
int cw = this.availContentWidth;
int ch = this.availContentHeight;
item.getItemHeight(cw, cw, ch);
}
}
}
this.childStartIndex = startIndex;
}
}
}
|
diff --git a/src/com/csipsimple/wizards/impl/Sipgate.java b/src/com/csipsimple/wizards/impl/Sipgate.java
index f2c7a541..afd475aa 100644
--- a/src/com/csipsimple/wizards/impl/Sipgate.java
+++ b/src/com/csipsimple/wizards/impl/Sipgate.java
@@ -1,247 +1,247 @@
/**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.wizards.impl;
import android.preference.EditTextPreference;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.csipsimple.R;
import com.csipsimple.api.SipConfigManager;
import com.csipsimple.api.SipProfile;
import com.csipsimple.utils.Base64;
import com.csipsimple.utils.Log;
import com.csipsimple.utils.PreferencesWrapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Sipgate extends AlternateServerImplementation {
protected static final String THIS_FILE = "SipgateW";
private static final String PROXY_KEY = "proxy_server";
private EditTextPreference accountProxy;
private LinearLayout customWizard;
private TextView customWizardText;
@Override
public void fillLayout(final SipProfile account) {
super.fillLayout(account);
//Override titles
accountDisplayName.setTitle(R.string.w_sipgate_display_name);
accountDisplayName.setDialogTitle(R.string.w_sipgate_display_name);
accountServer.setTitle(R.string.w_common_server);
accountServer.setDialogTitle(R.string.w_common_server);
accountUsername.setTitle(R.string.w_sipgate_username);
accountUsername.setDialogTitle(R.string.w_sipgate_username);
accountPassword.setTitle(R.string.w_sipgate_password);
accountPassword.setDialogTitle(R.string.w_sipgate_password);
// Add optional proxy
boolean recycle = true;
accountProxy = (EditTextPreference) findPreference(PROXY_KEY);
if(accountProxy == null) {
accountProxy = new EditTextPreference(parent);
accountProxy.setKey(PROXY_KEY);
accountProxy.setTitle(R.string.w_advanced_proxy);
accountProxy.setSummary(R.string.w_advanced_proxy_desc);
accountProxy.setDialogMessage(R.string.w_advanced_proxy_desc);
recycle = false;
}
if(!recycle) {
addPreference(accountProxy);
}
String currentProxy = account.getProxyAddress();
String currentServer = account.getSipDomain();
if(!TextUtils.isEmpty(currentProxy) && !TextUtils.isEmpty(currentServer)
- && !currentProxy.equalsIgnoreCase(currentProxy)) {
+ && !currentProxy.equalsIgnoreCase(currentServer)) {
accountProxy.setText(currentProxy);
}
if(TextUtils.isEmpty(account.getSipDomain())) {
accountServer.setText("sipgate.de");
}
//Get wizard specific row for balance
customWizardText = (TextView) parent.findViewById(R.id.custom_wizard_text);
customWizard = (LinearLayout) parent.findViewById(R.id.custom_wizard_row);
updateAccountInfos(account);
}
public SipProfile buildAccount(SipProfile account) {
account = super.buildAccount(account);
String nproxy = getText(accountProxy);
if(!TextUtils.isEmpty(nproxy)) {
account.proxies = new String[] {"sip:"+nproxy};
}
account.transport = SipProfile.TRANSPORT_UDP;
account.allow_contact_rewrite = false;
account.allow_via_rewrite = false;
return account;
}
@Override
public void setDefaultParams(PreferencesWrapper prefs) {
super.setDefaultParams(prefs);
// Add stun server
prefs.setPreferenceBooleanValue(SipConfigManager.ENABLE_STUN, true);
prefs.addStunServer("stun.sipgate.net:10000");
}
@Override
protected String getDefaultName() {
return "Sipgate";
}
@Override
public boolean needRestart() {
return true;
}
@Override
public String getDefaultFieldSummary(String fieldName) {
if(PROXY_KEY.equals(fieldName)) {
return parent.getString(R.string.w_advanced_proxy_desc);
}
return super.getDefaultFieldSummary(fieldName);
}
@Override
public void updateDescriptions() {
super.updateDescriptions();
setStringFieldSummary(PROXY_KEY);
}
// Balance consulting
private void updateAccountInfos(final SipProfile acc) {
if (acc != null && acc.id != SipProfile.INVALID_ID) {
customWizard.setVisibility(View.GONE);
accountBalanceHelper.launchRequest(acc);
} else {
// add a row to link
customWizard.setVisibility(View.GONE);
}
}
private AccountBalanceHelper accountBalanceHelper= new AccountBalance(this);
private static class AccountBalance extends AccountBalanceHelper {
WeakReference<Sipgate> w;
AccountBalance(Sipgate wizard){
w = new WeakReference<Sipgate>(wizard);
}
Pattern p = Pattern.compile("^.*TotalIncludingVat</name><value><double>(.*)</double>.*$");
/**
* {@inheritDoc}
*/
@Override
public String parseResponseLine(String line) {
Matcher matcher = p.matcher(line);
if(matcher.matches()) {
String strValue = matcher.group(1).trim();
try {
float value = Float.parseFloat(strValue.trim());
if(value >= 0) {
strValue = Double.toString( Math.round(value * 100.0)/100.0 );
}
}catch(NumberFormatException e) {
Log.d(THIS_FILE, "Can't parse float value in credit "+ strValue);
}
return "Creditos : " + strValue + " euros";
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public HttpRequestBase getRequest(SipProfile acc) throws IOException {
String requestURL = "https://samurai.sipgate.net/RPC2";
HttpPost httpPost = new HttpPost(requestURL);
// TODO : this is wrong ... we should use acc user/password instead of SIP ones, but we don't have it
String userpassword = acc.username + ":" + acc.data;
String encodedAuthorization = Base64.encodeBytes( userpassword.getBytes() );
httpPost.addHeader("Authorization", "Basic " + encodedAuthorization);
httpPost.addHeader("Content-Type", "text/xml");
// prepare POST body
String body = "<?xml version='1.0'?><methodCall><methodName>samurai.BalanceGet</methodName></methodCall>";
// set POST body
HttpEntity entity = new StringEntity(body);
httpPost.setEntity(entity);
return httpPost;
}
/**
* {@inheritDoc}
*/
@Override
public void applyResultError() {
Sipgate wizard = w.get();
if(wizard != null) {
wizard.customWizard.setVisibility(View.GONE);
}
}
/**
* {@inheritDoc}
*/
@Override
public void applyResultSuccess(String balanceText) {
Sipgate wizard = w.get();
if(wizard != null) {
wizard.customWizardText.setText(balanceText);
wizard.customWizard.setVisibility(View.VISIBLE);
}
}
};
}
| true | true | public void fillLayout(final SipProfile account) {
super.fillLayout(account);
//Override titles
accountDisplayName.setTitle(R.string.w_sipgate_display_name);
accountDisplayName.setDialogTitle(R.string.w_sipgate_display_name);
accountServer.setTitle(R.string.w_common_server);
accountServer.setDialogTitle(R.string.w_common_server);
accountUsername.setTitle(R.string.w_sipgate_username);
accountUsername.setDialogTitle(R.string.w_sipgate_username);
accountPassword.setTitle(R.string.w_sipgate_password);
accountPassword.setDialogTitle(R.string.w_sipgate_password);
// Add optional proxy
boolean recycle = true;
accountProxy = (EditTextPreference) findPreference(PROXY_KEY);
if(accountProxy == null) {
accountProxy = new EditTextPreference(parent);
accountProxy.setKey(PROXY_KEY);
accountProxy.setTitle(R.string.w_advanced_proxy);
accountProxy.setSummary(R.string.w_advanced_proxy_desc);
accountProxy.setDialogMessage(R.string.w_advanced_proxy_desc);
recycle = false;
}
if(!recycle) {
addPreference(accountProxy);
}
String currentProxy = account.getProxyAddress();
String currentServer = account.getSipDomain();
if(!TextUtils.isEmpty(currentProxy) && !TextUtils.isEmpty(currentServer)
&& !currentProxy.equalsIgnoreCase(currentProxy)) {
accountProxy.setText(currentProxy);
}
if(TextUtils.isEmpty(account.getSipDomain())) {
accountServer.setText("sipgate.de");
}
//Get wizard specific row for balance
customWizardText = (TextView) parent.findViewById(R.id.custom_wizard_text);
customWizard = (LinearLayout) parent.findViewById(R.id.custom_wizard_row);
updateAccountInfos(account);
}
| public void fillLayout(final SipProfile account) {
super.fillLayout(account);
//Override titles
accountDisplayName.setTitle(R.string.w_sipgate_display_name);
accountDisplayName.setDialogTitle(R.string.w_sipgate_display_name);
accountServer.setTitle(R.string.w_common_server);
accountServer.setDialogTitle(R.string.w_common_server);
accountUsername.setTitle(R.string.w_sipgate_username);
accountUsername.setDialogTitle(R.string.w_sipgate_username);
accountPassword.setTitle(R.string.w_sipgate_password);
accountPassword.setDialogTitle(R.string.w_sipgate_password);
// Add optional proxy
boolean recycle = true;
accountProxy = (EditTextPreference) findPreference(PROXY_KEY);
if(accountProxy == null) {
accountProxy = new EditTextPreference(parent);
accountProxy.setKey(PROXY_KEY);
accountProxy.setTitle(R.string.w_advanced_proxy);
accountProxy.setSummary(R.string.w_advanced_proxy_desc);
accountProxy.setDialogMessage(R.string.w_advanced_proxy_desc);
recycle = false;
}
if(!recycle) {
addPreference(accountProxy);
}
String currentProxy = account.getProxyAddress();
String currentServer = account.getSipDomain();
if(!TextUtils.isEmpty(currentProxy) && !TextUtils.isEmpty(currentServer)
&& !currentProxy.equalsIgnoreCase(currentServer)) {
accountProxy.setText(currentProxy);
}
if(TextUtils.isEmpty(account.getSipDomain())) {
accountServer.setText("sipgate.de");
}
//Get wizard specific row for balance
customWizardText = (TextView) parent.findViewById(R.id.custom_wizard_text);
customWizard = (LinearLayout) parent.findViewById(R.id.custom_wizard_row);
updateAccountInfos(account);
}
|
diff --git a/src/com/globalmesh/action/sale/SalesServlet.java b/src/com/globalmesh/action/sale/SalesServlet.java
index ef4000a..5d5cef3 100644
--- a/src/com/globalmesh/action/sale/SalesServlet.java
+++ b/src/com/globalmesh/action/sale/SalesServlet.java
@@ -1,185 +1,186 @@
package com.globalmesh.action.sale;
import java.io.IOException;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.globalmesh.dao.HallDAO;
import com.globalmesh.dao.MovieDetailDAO;
import com.globalmesh.dao.SaleDAO;
import com.globalmesh.dao.UserDAO;
import com.globalmesh.dto.Hall;
import com.globalmesh.dto.MovieDetail;
import com.globalmesh.dto.Sale;
import com.globalmesh.dto.User;
import com.globalmesh.util.Constants;
import com.globalmesh.util.RandomKeyGen;
import com.globalmesh.util.TicketPrinter;
import com.globalmesh.util.Utility;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
public class SalesServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String userEmail = (String) req.getSession().getAttribute("email");
if(userEmail == null) {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.LOGIN_NEED_MESSAGE));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
} else {
String hallName = Utility.chooseHall(req.getParameter("hallName"));
String showDate = req.getParameter("showDate");
String showTime = req.getParameter("showTime");
int numOfHalfTickets = Integer.parseInt(req.getParameter("halfTicket"));
int seatCount = Integer.parseInt(req.getParameter("seatCount"));
String seatSelection = req.getParameter("seatSelection");
DateFormat showFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
try {
Calendar show = Calendar.getInstance();
show.setTime(showFormat.parse(showDate + " " + showTime));
User u = UserDAO.INSTANCE.getUserByEmail(userEmail);
Hall h = HallDAO.INSTANCE.getHallById(hallName);
MovieDetail movie = MovieDetailDAO.INSTANCE.getNowShowingMovie(h.getHallId());
Sale sale = new Sale();
sale.setUserId(u.getUserId());
sale.setHall(h.getHallId());
sale.setMovie(movie.getMovieId());
sale.setSeatCount(seatCount);
sale.setNumOfHalfTickets(numOfHalfTickets);
sale.setSeats(seatSelection);
- sale.setFullTicketPrice(h.getOdcFull());
- sale.setHalfTicketPrice(h.getOdcHalf());
//if hall is 3D add the 3D price to the ticket price.
if(h.isThreeD()){
- sale.setFullTicketPrice(sale.getFullTicketPrice() + h.getPrice3D());
- sale.setFullTicketPrice(sale.getHalfTicketPrice() + h.getPrice3D());
+ sale.setFullTicketPrice(h.getOdcFull() + h.getPrice3D());
+ sale.setHalfTicketPrice(h.getOdcHalf() + h.getPrice3D());
+ } else {
+ sale.setFullTicketPrice(h.getOdcFull());
+ sale.setHalfTicketPrice(h.getOdcHalf());
}
int numOfFullTickets = (seatCount - numOfHalfTickets);
sale.setNumOfFullfTickets(numOfFullTickets);
double total = numOfFullTickets * h.getOdcFull() + numOfHalfTickets * h.getOdcHalf();
sale.setTotal(total);
sale.setShowDate(show.getTime());
sale.setTransactionDate(Calendar.getInstance().getTime());
Calendar today = Calendar.getInstance();
if(u.getUserType().compareTo(Utility.getCONFG().getProperty(Constants.USER_TYPE_ADMIN)) == 0) {
sale.setPaid(true);
sale.setOnline(false);
sale.setRedeem(true);
sale.setVeriFicationCode("NONE");
if(today.before(show)){
if(SaleDAO.INSTANCE.insertSale(sale)){
resp.setContentType("application/pdf");
Rectangle pagesize = new Rectangle(Utility.mmToPt(78), Utility.mmToPt(158));
Document ticket = new Document(pagesize, Utility.mmToPt(5), Utility.mmToPt(5),
Utility.mmToPt(5), Utility.mmToPt(5));
try {
PdfWriter writer = PdfWriter.getInstance(ticket, resp.getOutputStream());
ticket.open();
TicketPrinter.printTicket(sale, ticket, movie.getMovieName());
ticket.close();
} catch (DocumentException e) {
/*req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message",Utility.getCONFG().getProperty(Constants.SALE_FAIL));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);*/
}
} else {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message",Utility.getCONFG().getProperty(Constants.SALE_FAIL));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
}
} else {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.DATE_EXCEED));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
}
} else {
today.add(Calendar.MINUTE, 40);
/**
* Add 40 minutes to current time and check whether this new time is before the show time.
*/
if(today.before(show)){
sale.setOnline(true);
sale.setRedeem(false);
String verificationCode = RandomKeyGen.createId();
sale.setVeriFicationCode(verificationCode);
sale.setPaid(false);
HttpSession session = req.getSession();
Sale oldSale = (Sale) session.getAttribute("sale");
if(oldSale == null) {
session.setAttribute("sale", sale);
//TODO payment gateway send verification code to user
req.getRequestDispatcher("/afterP.do").forward(req, resp);
} else {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message",Utility.getCONFG().getProperty(Constants.SALE_FAIL));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
}
} else {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.DATE_EXCEED));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
| false | true | protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String userEmail = (String) req.getSession().getAttribute("email");
if(userEmail == null) {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.LOGIN_NEED_MESSAGE));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
} else {
String hallName = Utility.chooseHall(req.getParameter("hallName"));
String showDate = req.getParameter("showDate");
String showTime = req.getParameter("showTime");
int numOfHalfTickets = Integer.parseInt(req.getParameter("halfTicket"));
int seatCount = Integer.parseInt(req.getParameter("seatCount"));
String seatSelection = req.getParameter("seatSelection");
DateFormat showFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
try {
Calendar show = Calendar.getInstance();
show.setTime(showFormat.parse(showDate + " " + showTime));
User u = UserDAO.INSTANCE.getUserByEmail(userEmail);
Hall h = HallDAO.INSTANCE.getHallById(hallName);
MovieDetail movie = MovieDetailDAO.INSTANCE.getNowShowingMovie(h.getHallId());
Sale sale = new Sale();
sale.setUserId(u.getUserId());
sale.setHall(h.getHallId());
sale.setMovie(movie.getMovieId());
sale.setSeatCount(seatCount);
sale.setNumOfHalfTickets(numOfHalfTickets);
sale.setSeats(seatSelection);
sale.setFullTicketPrice(h.getOdcFull());
sale.setHalfTicketPrice(h.getOdcHalf());
//if hall is 3D add the 3D price to the ticket price.
if(h.isThreeD()){
sale.setFullTicketPrice(sale.getFullTicketPrice() + h.getPrice3D());
sale.setFullTicketPrice(sale.getHalfTicketPrice() + h.getPrice3D());
}
int numOfFullTickets = (seatCount - numOfHalfTickets);
sale.setNumOfFullfTickets(numOfFullTickets);
double total = numOfFullTickets * h.getOdcFull() + numOfHalfTickets * h.getOdcHalf();
sale.setTotal(total);
sale.setShowDate(show.getTime());
sale.setTransactionDate(Calendar.getInstance().getTime());
Calendar today = Calendar.getInstance();
if(u.getUserType().compareTo(Utility.getCONFG().getProperty(Constants.USER_TYPE_ADMIN)) == 0) {
sale.setPaid(true);
sale.setOnline(false);
sale.setRedeem(true);
sale.setVeriFicationCode("NONE");
if(today.before(show)){
if(SaleDAO.INSTANCE.insertSale(sale)){
resp.setContentType("application/pdf");
Rectangle pagesize = new Rectangle(Utility.mmToPt(78), Utility.mmToPt(158));
Document ticket = new Document(pagesize, Utility.mmToPt(5), Utility.mmToPt(5),
Utility.mmToPt(5), Utility.mmToPt(5));
try {
PdfWriter writer = PdfWriter.getInstance(ticket, resp.getOutputStream());
ticket.open();
TicketPrinter.printTicket(sale, ticket, movie.getMovieName());
ticket.close();
} catch (DocumentException e) {
/*req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message",Utility.getCONFG().getProperty(Constants.SALE_FAIL));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);*/
}
} else {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message",Utility.getCONFG().getProperty(Constants.SALE_FAIL));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
}
} else {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.DATE_EXCEED));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
}
} else {
today.add(Calendar.MINUTE, 40);
/**
* Add 40 minutes to current time and check whether this new time is before the show time.
*/
if(today.before(show)){
sale.setOnline(true);
sale.setRedeem(false);
String verificationCode = RandomKeyGen.createId();
sale.setVeriFicationCode(verificationCode);
sale.setPaid(false);
HttpSession session = req.getSession();
Sale oldSale = (Sale) session.getAttribute("sale");
if(oldSale == null) {
session.setAttribute("sale", sale);
//TODO payment gateway send verification code to user
req.getRequestDispatcher("/afterP.do").forward(req, resp);
} else {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message",Utility.getCONFG().getProperty(Constants.SALE_FAIL));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
}
} else {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.DATE_EXCEED));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String userEmail = (String) req.getSession().getAttribute("email");
if(userEmail == null) {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.LOGIN_NEED_MESSAGE));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
} else {
String hallName = Utility.chooseHall(req.getParameter("hallName"));
String showDate = req.getParameter("showDate");
String showTime = req.getParameter("showTime");
int numOfHalfTickets = Integer.parseInt(req.getParameter("halfTicket"));
int seatCount = Integer.parseInt(req.getParameter("seatCount"));
String seatSelection = req.getParameter("seatSelection");
DateFormat showFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
try {
Calendar show = Calendar.getInstance();
show.setTime(showFormat.parse(showDate + " " + showTime));
User u = UserDAO.INSTANCE.getUserByEmail(userEmail);
Hall h = HallDAO.INSTANCE.getHallById(hallName);
MovieDetail movie = MovieDetailDAO.INSTANCE.getNowShowingMovie(h.getHallId());
Sale sale = new Sale();
sale.setUserId(u.getUserId());
sale.setHall(h.getHallId());
sale.setMovie(movie.getMovieId());
sale.setSeatCount(seatCount);
sale.setNumOfHalfTickets(numOfHalfTickets);
sale.setSeats(seatSelection);
//if hall is 3D add the 3D price to the ticket price.
if(h.isThreeD()){
sale.setFullTicketPrice(h.getOdcFull() + h.getPrice3D());
sale.setHalfTicketPrice(h.getOdcHalf() + h.getPrice3D());
} else {
sale.setFullTicketPrice(h.getOdcFull());
sale.setHalfTicketPrice(h.getOdcHalf());
}
int numOfFullTickets = (seatCount - numOfHalfTickets);
sale.setNumOfFullfTickets(numOfFullTickets);
double total = numOfFullTickets * h.getOdcFull() + numOfHalfTickets * h.getOdcHalf();
sale.setTotal(total);
sale.setShowDate(show.getTime());
sale.setTransactionDate(Calendar.getInstance().getTime());
Calendar today = Calendar.getInstance();
if(u.getUserType().compareTo(Utility.getCONFG().getProperty(Constants.USER_TYPE_ADMIN)) == 0) {
sale.setPaid(true);
sale.setOnline(false);
sale.setRedeem(true);
sale.setVeriFicationCode("NONE");
if(today.before(show)){
if(SaleDAO.INSTANCE.insertSale(sale)){
resp.setContentType("application/pdf");
Rectangle pagesize = new Rectangle(Utility.mmToPt(78), Utility.mmToPt(158));
Document ticket = new Document(pagesize, Utility.mmToPt(5), Utility.mmToPt(5),
Utility.mmToPt(5), Utility.mmToPt(5));
try {
PdfWriter writer = PdfWriter.getInstance(ticket, resp.getOutputStream());
ticket.open();
TicketPrinter.printTicket(sale, ticket, movie.getMovieName());
ticket.close();
} catch (DocumentException e) {
/*req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message",Utility.getCONFG().getProperty(Constants.SALE_FAIL));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);*/
}
} else {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message",Utility.getCONFG().getProperty(Constants.SALE_FAIL));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
}
} else {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.DATE_EXCEED));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
}
} else {
today.add(Calendar.MINUTE, 40);
/**
* Add 40 minutes to current time and check whether this new time is before the show time.
*/
if(today.before(show)){
sale.setOnline(true);
sale.setRedeem(false);
String verificationCode = RandomKeyGen.createId();
sale.setVeriFicationCode(verificationCode);
sale.setPaid(false);
HttpSession session = req.getSession();
Sale oldSale = (Sale) session.getAttribute("sale");
if(oldSale == null) {
session.setAttribute("sale", sale);
//TODO payment gateway send verification code to user
req.getRequestDispatcher("/afterP.do").forward(req, resp);
} else {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message",Utility.getCONFG().getProperty(Constants.SALE_FAIL));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
}
} else {
req.setAttribute("msgClass", Constants.MSG_CSS_ERROR);
req.setAttribute("message", Utility.getCONFG().getProperty(Constants.DATE_EXCEED));
req.getRequestDispatcher("/messages.jsp").forward(req, resp);
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
diff --git a/src/uk/me/parabola/imgfmt/app/labelenc/Format6Encoder.java b/src/uk/me/parabola/imgfmt/app/labelenc/Format6Encoder.java
index 48347c74..77050d91 100644
--- a/src/uk/me/parabola/imgfmt/app/labelenc/Format6Encoder.java
+++ b/src/uk/me/parabola/imgfmt/app/labelenc/Format6Encoder.java
@@ -1,143 +1,143 @@
/*
* Copyright (C) 2007 Steve Ratcliffe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* Author: Steve Ratcliffe
* Create date: 14-Jan-2007
*/
package uk.me.parabola.imgfmt.app.labelenc;
import java.util.Locale;
/**
* Format according to the '6 bit' .img format. The text is first upper
* cased. Any letter with a diacritic or accent is replaced with its base
* letter.
*
* For example Körnerstraße would become KORNERSTRASSE,
* Řípovská would become RIPOVSKA etc.
*
* I believe that some Garmin units are only capable of showing uppercase
* ascii characters, so this will be the default.
*
* @author Steve Ratcliffe
* @see <a href="http://garmin-img.sf.net">Garmin IMG File Format</a>
*/
public class Format6Encoder extends BaseEncoder implements CharacterEncoder {
// This is 0x1b is the source document, but the accompanying code uses
// the value 0x1c, which seems to work.
private static final int SYMBOL_SHIFT = 0x1c;
public static final String LETTERS =
" ABCDEFGHIJKLMNO" + // 0x00-0x0F
"PQRSTUVWXYZxx " + // 0x10-0x1F
"0123456789xxxxxx"; // 0x20-0x2F
public static final String SYMBOLS =
"@!\"#$%&'()*+,-./" + // 0x00-0x0F
"xxxxxxxxxx:;<=>?" + // 0x10-0x1F
"xxxxxxxxxxx[\\]^_"; // 0x20-0x2F
/**
* Encode the text into the 6 bit format. See the class level notes.
*
* @param text The original text, which can contain non-ascii characters.
* @return Encoded form of the text. Only uppercase ascii characters and
* some escape sequences will be present.
*/
public EncodedText encodeText(String text) {
if (text == null || text.length() == 0)
return NO_TEXT;
String s = text.toUpperCase(Locale.ENGLISH);
byte[] buf = new byte[2 * s.length() + 1];
int off = 0;
for (char c : transliterate(s)) {
if (c == ' ') {
buf = put6(buf, off++, 0);
} else if (c >= 'A' && c <= 'Z') {
buf = put6(buf, off++, c - 'A' + 1);
} else if (c >= '0' && c <= '9') {
buf = put6(buf, off++, c - '0' + 0x20);
} else if (c >= 0x1d && c <= 0x1f) {
put6(buf, off++, c);
} else if (c >= 1 && c <= 6) {
// Highway shields
- put6(buf, off++, 0x2a + c);
+ put6(buf, off++, 0x29 + c);
} else {
off = shiftedSymbol(buf, off, c);
}
}
buf = put6(buf, off++, 0xff);
int len = ((off - 1) * 6) / 8 + 1;
return new EncodedText(buf, len);
}
/**
* Certain characters have to be represented by two 6byte quantities. This
* routine sorts these out.
*
* @param buf The buffer to write into.
* @param startOffset The offset to start writing to in the output buffer.
* @param c The character that we are decoding.
* @return The final offset. This will be unchanged if there was nothing
* written because the character does not have any representation.
*/
private int shiftedSymbol(byte[] buf, int startOffset, char c) {
int off = startOffset;
int ind = SYMBOLS.indexOf(c);
if (ind >= 0) {
put6(buf, off++, SYMBOL_SHIFT);
put6(buf, off++, ind);
}
return off;
}
/**
* Each character is packed into 6 bits. This keeps track of everything so
* that the character can be put into the right place in the byte array.
*
* @param buf The buffer to populate.
* @param off The character offset, that is the number of the six bit
* character.
* @param c The character to place.
*/
private byte[] put6(byte[] buf, int off, int c) {
int bitOff = off * 6;
// The byte offset
int byteOff = bitOff/8;
// The offset within the byte
int shift = bitOff - 8*byteOff;
int mask = 0xfc >> shift;
buf[byteOff] |= ((c << 2) >> shift) & mask;
// IF the shift is greater than two we have to put the rest in the
// next byte.
if (shift > 2) {
mask = 0xfc << (8 - shift);
buf[byteOff + 1] = (byte) (((c << 2) << (8 - shift)) & mask);
}
return buf;
}
}
| true | true | public EncodedText encodeText(String text) {
if (text == null || text.length() == 0)
return NO_TEXT;
String s = text.toUpperCase(Locale.ENGLISH);
byte[] buf = new byte[2 * s.length() + 1];
int off = 0;
for (char c : transliterate(s)) {
if (c == ' ') {
buf = put6(buf, off++, 0);
} else if (c >= 'A' && c <= 'Z') {
buf = put6(buf, off++, c - 'A' + 1);
} else if (c >= '0' && c <= '9') {
buf = put6(buf, off++, c - '0' + 0x20);
} else if (c >= 0x1d && c <= 0x1f) {
put6(buf, off++, c);
} else if (c >= 1 && c <= 6) {
// Highway shields
put6(buf, off++, 0x2a + c);
} else {
off = shiftedSymbol(buf, off, c);
}
}
buf = put6(buf, off++, 0xff);
int len = ((off - 1) * 6) / 8 + 1;
return new EncodedText(buf, len);
}
| public EncodedText encodeText(String text) {
if (text == null || text.length() == 0)
return NO_TEXT;
String s = text.toUpperCase(Locale.ENGLISH);
byte[] buf = new byte[2 * s.length() + 1];
int off = 0;
for (char c : transliterate(s)) {
if (c == ' ') {
buf = put6(buf, off++, 0);
} else if (c >= 'A' && c <= 'Z') {
buf = put6(buf, off++, c - 'A' + 1);
} else if (c >= '0' && c <= '9') {
buf = put6(buf, off++, c - '0' + 0x20);
} else if (c >= 0x1d && c <= 0x1f) {
put6(buf, off++, c);
} else if (c >= 1 && c <= 6) {
// Highway shields
put6(buf, off++, 0x29 + c);
} else {
off = shiftedSymbol(buf, off, c);
}
}
buf = put6(buf, off++, 0xff);
int len = ((off - 1) * 6) / 8 + 1;
return new EncodedText(buf, len);
}
|
diff --git a/src/main/java/com/edinarobotics/scouting/definitions/event/Event.java b/src/main/java/com/edinarobotics/scouting/definitions/event/Event.java
index a59afdf..3d0ff0a 100644
--- a/src/main/java/com/edinarobotics/scouting/definitions/event/Event.java
+++ b/src/main/java/com/edinarobotics/scouting/definitions/event/Event.java
@@ -1,39 +1,39 @@
package com.edinarobotics.scouting.definitions.event;
import java.util.UUID;
/**
* This class represents events used throughout the scouting system.
*/
public abstract class Event {
private final String id;
/**
* This constructor handles some default setup tasks for Events.
* For example, It assigns a randomly generated, unique ID value to each
* Event object.
*/
public Event(){
- this.id = UUID.randomUUID().toString().toLowerCase();
+ this.id = UUID.randomUUID().toString();
}
/**
* This constructor handles some default setup tasks for Events.
* It allows manually setting the id for {@link Event} objects.
* Use it carefully and at your own risk.
* @param id The {@link String} id value for this {@link Event} object.
*/
public Event(String id){
this.id = id;
}
/**
* Returns the random, unique ID value assigned to this event as a {@link String}.
* All {@link Event} objects have unique IDs associated to them.
* @return A {@link String} object representing the unique ID for this {@link Event}
* object.
*/
public final String getId(){
return id;
}
}
| true | true | public Event(){
this.id = UUID.randomUUID().toString().toLowerCase();
}
| public Event(){
this.id = UUID.randomUUID().toString();
}
|
diff --git a/src/com/jidesoft/plaf/office2003/Office2003WindowsUtils.java b/src/com/jidesoft/plaf/office2003/Office2003WindowsUtils.java
index bc1cf49c..84868868 100644
--- a/src/com/jidesoft/plaf/office2003/Office2003WindowsUtils.java
+++ b/src/com/jidesoft/plaf/office2003/Office2003WindowsUtils.java
@@ -1,305 +1,306 @@
/**
* @(#)Office2003WindowsUtils.java
*
* Copyright 2002 - 2004 JIDE Software. All rights reserved.
*/
package com.jidesoft.plaf.office2003;
import com.jidesoft.icons.IconsFactory;
import com.jidesoft.plaf.ExtWindowsDesktopProperty;
import com.jidesoft.plaf.LookAndFeelFactory;
import com.jidesoft.plaf.UIDefaultsLookup;
import com.jidesoft.plaf.WindowsDesktopProperty;
import com.jidesoft.plaf.basic.Painter;
import com.jidesoft.plaf.basic.ThemePainter;
import com.jidesoft.plaf.vsnet.ConvertListener;
import com.jidesoft.plaf.vsnet.HeaderCellBorder;
import com.jidesoft.plaf.vsnet.ResizeFrameBorder;
import com.jidesoft.plaf.vsnet.VsnetWindowsUtils;
import com.jidesoft.plaf.xerto.SlidingFrameBorder;
import com.jidesoft.plaf.xerto.StatusBarBorder;
import com.jidesoft.swing.JideSwingUtilities;
import com.jidesoft.swing.JideTabbedPane;
import com.jidesoft.utils.SecurityUtils;
import javax.swing.*;
import javax.swing.plaf.BorderUIResource;
import javax.swing.plaf.InsetsUIResource;
import java.awt.*;
/**
* WindowsLookAndFeel with Office2003 extension
*/
public class Office2003WindowsUtils extends VsnetWindowsUtils {
/**
* Initializes class defaults.
*
* @param table
* @param withMenu
*/
public static void initClassDefaults(UIDefaults table, boolean withMenu) {
if (withMenu) {
VsnetWindowsUtils.initClassDefaultsWithMenu(table);
table.put("PopupMenuSeparatorUI", "com.jidesoft.plaf.office2003.Office2003PopupMenuSeparatorUI");
}
else {
VsnetWindowsUtils.initClassDefaults(table);
}
int products = LookAndFeelFactory.getProductsUsed();
table.put("JideTabbedPaneUI", "com.jidesoft.plaf.office2003.Office2003JideTabbedPaneUI");
table.put("RangeSliderUI", "com.jidesoft.plaf.office2003.Office2003RangeSliderUI");
if ((products & PRODUCT_DOCK) != 0) {
table.put("SidePaneUI", "com.jidesoft.plaf.office2003.Office2003SidePaneUI");
}
if ((products & PRODUCT_COMPONENTS) != 0) {
table.put("CollapsiblePaneUI", "com.jidesoft.plaf.office2003.Office2003CollapsiblePaneUI");
table.put("StatusBarSeparatorUI", "com.jidesoft.plaf.office2003.Office2003StatusBarSeparatorUI");
}
if ((products & PRODUCT_ACTION) != 0) {
table.put("CommandBarSeparatorUI", "com.jidesoft.plaf.office2003.Office2003CommandBarSeparatorUI");
}
}
/**
* Initializes class defaults.
*
* @param table
*/
public static void initClassDefaults(UIDefaults table) {
initClassDefaults(table, true);
}
/**
* Initializes components defaults.
*
* @param table
*/
public static void initComponentDefaults(UIDefaults table) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
WindowsDesktopProperty defaultTextColor = new WindowsDesktopProperty("win.button.textColor", UIDefaultsLookup.get("controlText"), toolkit);
WindowsDesktopProperty defaultBackgroundColor = new WindowsDesktopProperty("win.3d.backgroundColor", UIDefaultsLookup.get("control"), toolkit);
WindowsDesktopProperty defaultLightColor = new WindowsDesktopProperty("win.3d.lightColor", UIDefaultsLookup.get("controlHighlight"), toolkit);
WindowsDesktopProperty defaultHighlightColor = new WindowsDesktopProperty("win.3d.highlightColor", UIDefaultsLookup.get("controlLtHighlight"), toolkit);
WindowsDesktopProperty defaultShadowColor = new WindowsDesktopProperty("win.3d.shadowColor", UIDefaultsLookup.get("controlShadow"), toolkit);
WindowsDesktopProperty defaultDarkShadowColor = new WindowsDesktopProperty("win.3d.darkShadowColor", UIDefaultsLookup.get("controlDkShadow"), toolkit);
Object toolbarFont = JideSwingUtilities.getMenuFont(toolkit, table);
Object boldFont = JideSwingUtilities.getBoldFont(toolkit, table);
Painter gripperPainter = new Painter() {
public void paint(JComponent c, Graphics g, Rectangle rect, int orientation, int state) {
Office2003Painter.getInstance().paintGripper(c, g, rect, orientation, state);
}
};
ImageIcon sliderHorizontalImage = IconsFactory.getImageIcon(Office2003WindowsUtils.class, "icons/slider_horizontal.gif");
ImageIcon sliderVerticalalImage = IconsFactory.getImageIcon(Office2003WindowsUtils.class, "icons/slider_vertical.gif");
Object uiDefaults[] = new Object[]{
"JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_OFFICE2003,
"JideTabbedPane.defaultTabColorTheme", JideTabbedPane.COLOR_THEME_OFFICE2003,
"JideTabbedPane.contentBorderInsets", new InsetsUIResource(3, 3, 3, 3),
"JideTabbedPane.gripperPainter", gripperPainter,
"JideTabbedPane.alwaysShowLineBorder", Boolean.FALSE,
"JideTabbedPane.showFocusIndicator", Boolean.TRUE,
"JideSplitPaneDivider.gripperPainter", gripperPainter,
"Gripper.size", 8,
"Gripper.painter", gripperPainter,
"Icon.floating", Boolean.FALSE,
"RangeSlider.lowerIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 0, 0, 9, 10),
"RangeSlider.upperIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 0, 10, 9, 10),
"RangeSlider.middleIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 0, 20, 9, 7),
"RangeSlider.lowerRIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 9, 0, 9, 10),
"RangeSlider.upperRIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 9, 10, 9, 10),
"RangeSlider.middleRIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 9, 20, 9, 7),
"RangeSlider.lowerVIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 0, 0, 10, 9),
"RangeSlider.upperVIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 10, 0, 10, 9),
"RangeSlider.middleVIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 20, 0, 7, 9),
"RangeSlider.lowerVRIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 0, 9, 10, 9),
"RangeSlider.upperVRIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 10, 9, 10, 9),
"RangeSlider.middleVRIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 20, 9, 7, 9),
"JideScrollPane.border", UIDefaultsLookup.getBorder("ScrollPane.border"),
"Menu.margin", new InsetsUIResource(2, 7, 3, 7),
"Menu.submenuPopupOffsetX", 1,
"Menu.submenuPopupOffsetY", 0,
"MenuBar.border", new BorderUIResource(BorderFactory.createEmptyBorder(1, 2, 1, 2)),
"PopupMenu.background", new UIDefaults.ActiveValue() {
public Object createValue(UIDefaults table) {
return Office2003Painter.getInstance().getMenuItemBackground();
}
},
};
table.putDefaults(uiDefaults);
int products = LookAndFeelFactory.getProductsUsed();
if ((products & PRODUCT_DOCK) != 0) {
boolean useShadowBorder = "true".equals(SecurityUtils.getProperty("jide.shadeSlidingBorder", "false"));
Object slidingEastFrameBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new SlidingFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(1, SlidingFrameBorder.SHADOW_SIZE + 5, 1, 1));
}
});
Object slidingWestFrameBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new SlidingFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(1, 1, 1, SlidingFrameBorder.SHADOW_SIZE + 5));
}
});
Object slidingNorthFrameBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new SlidingFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(1, 1, SlidingFrameBorder.SHADOW_SIZE + 5, 1));
}
});
Object slidingSouthFrameBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new SlidingFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(SlidingFrameBorder.SHADOW_SIZE + 5, 1, 1, 1));
}
});
Object slidingEastFrameBorder2 = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new ResizeFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(0, 4, 0, 0));
}
});
Object slidingWestFrameBorder2 = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new ResizeFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(0, 0, 0, 4));
}
});
Object slidingNorthFrameBorder2 = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new ResizeFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(0, 0, 4, 0));
}
});
Object slidingSouthFrameBorder2 = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new ResizeFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(4, 0, 0, 0));
}
});
uiDefaults = new Object[]{
// dock
"SidePane.foreground", defaultTextColor,
"SidePane.lineColor", new UIDefaults.ActiveValue() {
public Object createValue(UIDefaults table) {
return Office2003Painter.getInstance().getControlShadow();
}
},
"StatusBarItem.border", new BorderUIResource(BorderFactory.createEmptyBorder(0, 1, 0, 1)),
"StatusBar.border", new StatusBarBorder(),
"DockableFrame.titleBorder", new BorderUIResource(BorderFactory.createEmptyBorder(0, 0, 0, 0)),
"DockableFrameTitlePane.use3dButtons", Boolean.FALSE,
"DockableFrameTitlePane.gripperPainter", gripperPainter,
"DockableFrameTitlePane.margin", new InsetsUIResource(1, 6, 1, 6), // gap
+ "DockableFrameTitlePane.contentFilledButtons", true,
"DockableFrame.activeTitleForeground", UIDefaultsLookup.getColor("DockableFrame.inactiveTitleForeground"),
"DockableFrame.slidingEastBorder", useShadowBorder ? slidingEastFrameBorder : slidingEastFrameBorder2,
"DockableFrame.slidingWestBorder", useShadowBorder ? slidingWestFrameBorder : slidingWestFrameBorder2,
"DockableFrame.slidingNorthBorder", useShadowBorder ? slidingNorthFrameBorder : slidingNorthFrameBorder2,
"DockableFrame.slidingSouthBorder", useShadowBorder ? slidingSouthFrameBorder : slidingSouthFrameBorder2,
"FrameContainer.contentBorderInsets", new InsetsUIResource(3, 3, 3, 3),
};
table.putDefaults(uiDefaults);
}
if ((products & PRODUCT_ACTION) != 0) {
Object floatingBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.titleBarColor"},
new Object[]{UIDefaultsLookup.get("controlShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new BorderUIResource(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder((Color) obj[0], 2),
BorderFactory.createEmptyBorder(1, 1, 1, 1)));
}
});
uiDefaults = new Object[]{
// action
"CommandBar.font", toolbarFont,
"CommandBar.background", defaultBackgroundColor,
"CommandBar.foreground", defaultTextColor,
"CommandBar.shadow", defaultShadowColor,
"CommandBar.darkShadow", defaultDarkShadowColor,
"CommandBar.light", defaultLightColor,
"CommandBar.highlight", defaultHighlightColor,
"CommandBar.border", new BorderUIResource(BorderFactory.createEmptyBorder(1, 2, 2, 0)),
"CommandBar.borderVert", new BorderUIResource(BorderFactory.createEmptyBorder(2, 1, 0, 2)),
"CommandBar.borderFloating", new BorderUIResource(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(UIDefaultsLookup.getColor("activeCaption"), 2),
BorderFactory.createEmptyBorder(1, 1, 1, 1))),
"CommandBar.floatingBorder", floatingBorder,
"CommandBar.separatorSize", 5,
"CommandBar.titleBarSize", 17,
"CommandBar.titleBarButtonGap", 1,
"CommandBar.titleBarBackground", UIDefaultsLookup.getColor("activeCaption"),
"CommandBar.titleBarForeground", UIDefaultsLookup.getColor("activeCaptionText"),
"CommandBar.titleBarFont", boldFont,
"Chevron.size", 13,
"Chevron.alwaysVisible", Boolean.TRUE,
};
table.putDefaults(uiDefaults);
}
if ((products & PRODUCT_GRIDS) != 0) {
uiDefaults = new Object[]{
"AbstractComboBox.useJButton", Boolean.FALSE,
"NestedTableHeader.cellBorder", new HeaderCellBorder(),
"GroupList.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[]{
"TAB", "selectNextGroup",
"shift TAB", "selectPreviousGroup",
}),
};
table.putDefaults(uiDefaults);
}
UIDefaultsLookup.put(table, "Theme.painter", Office2003Painter.getInstance());
// since it used BasicPainter, make sure it is after Theme.Painter is set first.
Object popupMenuBorder = new ExtWindowsDesktopProperty(new String[]{"null"}, new Object[]{((ThemePainter) UIDefaultsLookup.get("Theme.painter")).getMenuItemBorderColor()}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new BorderUIResource(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder((Color) obj[0]), BorderFactory.createEmptyBorder(1, 1, 1, 1)));
}
});
table.put("PopupMenu.border", popupMenuBorder);
}
}
| true | true | public static void initComponentDefaults(UIDefaults table) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
WindowsDesktopProperty defaultTextColor = new WindowsDesktopProperty("win.button.textColor", UIDefaultsLookup.get("controlText"), toolkit);
WindowsDesktopProperty defaultBackgroundColor = new WindowsDesktopProperty("win.3d.backgroundColor", UIDefaultsLookup.get("control"), toolkit);
WindowsDesktopProperty defaultLightColor = new WindowsDesktopProperty("win.3d.lightColor", UIDefaultsLookup.get("controlHighlight"), toolkit);
WindowsDesktopProperty defaultHighlightColor = new WindowsDesktopProperty("win.3d.highlightColor", UIDefaultsLookup.get("controlLtHighlight"), toolkit);
WindowsDesktopProperty defaultShadowColor = new WindowsDesktopProperty("win.3d.shadowColor", UIDefaultsLookup.get("controlShadow"), toolkit);
WindowsDesktopProperty defaultDarkShadowColor = new WindowsDesktopProperty("win.3d.darkShadowColor", UIDefaultsLookup.get("controlDkShadow"), toolkit);
Object toolbarFont = JideSwingUtilities.getMenuFont(toolkit, table);
Object boldFont = JideSwingUtilities.getBoldFont(toolkit, table);
Painter gripperPainter = new Painter() {
public void paint(JComponent c, Graphics g, Rectangle rect, int orientation, int state) {
Office2003Painter.getInstance().paintGripper(c, g, rect, orientation, state);
}
};
ImageIcon sliderHorizontalImage = IconsFactory.getImageIcon(Office2003WindowsUtils.class, "icons/slider_horizontal.gif");
ImageIcon sliderVerticalalImage = IconsFactory.getImageIcon(Office2003WindowsUtils.class, "icons/slider_vertical.gif");
Object uiDefaults[] = new Object[]{
"JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_OFFICE2003,
"JideTabbedPane.defaultTabColorTheme", JideTabbedPane.COLOR_THEME_OFFICE2003,
"JideTabbedPane.contentBorderInsets", new InsetsUIResource(3, 3, 3, 3),
"JideTabbedPane.gripperPainter", gripperPainter,
"JideTabbedPane.alwaysShowLineBorder", Boolean.FALSE,
"JideTabbedPane.showFocusIndicator", Boolean.TRUE,
"JideSplitPaneDivider.gripperPainter", gripperPainter,
"Gripper.size", 8,
"Gripper.painter", gripperPainter,
"Icon.floating", Boolean.FALSE,
"RangeSlider.lowerIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 0, 0, 9, 10),
"RangeSlider.upperIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 0, 10, 9, 10),
"RangeSlider.middleIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 0, 20, 9, 7),
"RangeSlider.lowerRIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 9, 0, 9, 10),
"RangeSlider.upperRIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 9, 10, 9, 10),
"RangeSlider.middleRIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 9, 20, 9, 7),
"RangeSlider.lowerVIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 0, 0, 10, 9),
"RangeSlider.upperVIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 10, 0, 10, 9),
"RangeSlider.middleVIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 20, 0, 7, 9),
"RangeSlider.lowerVRIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 0, 9, 10, 9),
"RangeSlider.upperVRIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 10, 9, 10, 9),
"RangeSlider.middleVRIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 20, 9, 7, 9),
"JideScrollPane.border", UIDefaultsLookup.getBorder("ScrollPane.border"),
"Menu.margin", new InsetsUIResource(2, 7, 3, 7),
"Menu.submenuPopupOffsetX", 1,
"Menu.submenuPopupOffsetY", 0,
"MenuBar.border", new BorderUIResource(BorderFactory.createEmptyBorder(1, 2, 1, 2)),
"PopupMenu.background", new UIDefaults.ActiveValue() {
public Object createValue(UIDefaults table) {
return Office2003Painter.getInstance().getMenuItemBackground();
}
},
};
table.putDefaults(uiDefaults);
int products = LookAndFeelFactory.getProductsUsed();
if ((products & PRODUCT_DOCK) != 0) {
boolean useShadowBorder = "true".equals(SecurityUtils.getProperty("jide.shadeSlidingBorder", "false"));
Object slidingEastFrameBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new SlidingFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(1, SlidingFrameBorder.SHADOW_SIZE + 5, 1, 1));
}
});
Object slidingWestFrameBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new SlidingFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(1, 1, 1, SlidingFrameBorder.SHADOW_SIZE + 5));
}
});
Object slidingNorthFrameBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new SlidingFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(1, 1, SlidingFrameBorder.SHADOW_SIZE + 5, 1));
}
});
Object slidingSouthFrameBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new SlidingFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(SlidingFrameBorder.SHADOW_SIZE + 5, 1, 1, 1));
}
});
Object slidingEastFrameBorder2 = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new ResizeFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(0, 4, 0, 0));
}
});
Object slidingWestFrameBorder2 = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new ResizeFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(0, 0, 0, 4));
}
});
Object slidingNorthFrameBorder2 = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new ResizeFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(0, 0, 4, 0));
}
});
Object slidingSouthFrameBorder2 = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new ResizeFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(4, 0, 0, 0));
}
});
uiDefaults = new Object[]{
// dock
"SidePane.foreground", defaultTextColor,
"SidePane.lineColor", new UIDefaults.ActiveValue() {
public Object createValue(UIDefaults table) {
return Office2003Painter.getInstance().getControlShadow();
}
},
"StatusBarItem.border", new BorderUIResource(BorderFactory.createEmptyBorder(0, 1, 0, 1)),
"StatusBar.border", new StatusBarBorder(),
"DockableFrame.titleBorder", new BorderUIResource(BorderFactory.createEmptyBorder(0, 0, 0, 0)),
"DockableFrameTitlePane.use3dButtons", Boolean.FALSE,
"DockableFrameTitlePane.gripperPainter", gripperPainter,
"DockableFrameTitlePane.margin", new InsetsUIResource(1, 6, 1, 6), // gap
"DockableFrame.activeTitleForeground", UIDefaultsLookup.getColor("DockableFrame.inactiveTitleForeground"),
"DockableFrame.slidingEastBorder", useShadowBorder ? slidingEastFrameBorder : slidingEastFrameBorder2,
"DockableFrame.slidingWestBorder", useShadowBorder ? slidingWestFrameBorder : slidingWestFrameBorder2,
"DockableFrame.slidingNorthBorder", useShadowBorder ? slidingNorthFrameBorder : slidingNorthFrameBorder2,
"DockableFrame.slidingSouthBorder", useShadowBorder ? slidingSouthFrameBorder : slidingSouthFrameBorder2,
"FrameContainer.contentBorderInsets", new InsetsUIResource(3, 3, 3, 3),
};
table.putDefaults(uiDefaults);
}
if ((products & PRODUCT_ACTION) != 0) {
Object floatingBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.titleBarColor"},
new Object[]{UIDefaultsLookup.get("controlShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new BorderUIResource(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder((Color) obj[0], 2),
BorderFactory.createEmptyBorder(1, 1, 1, 1)));
}
});
uiDefaults = new Object[]{
// action
"CommandBar.font", toolbarFont,
"CommandBar.background", defaultBackgroundColor,
"CommandBar.foreground", defaultTextColor,
"CommandBar.shadow", defaultShadowColor,
"CommandBar.darkShadow", defaultDarkShadowColor,
"CommandBar.light", defaultLightColor,
"CommandBar.highlight", defaultHighlightColor,
"CommandBar.border", new BorderUIResource(BorderFactory.createEmptyBorder(1, 2, 2, 0)),
"CommandBar.borderVert", new BorderUIResource(BorderFactory.createEmptyBorder(2, 1, 0, 2)),
"CommandBar.borderFloating", new BorderUIResource(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(UIDefaultsLookup.getColor("activeCaption"), 2),
BorderFactory.createEmptyBorder(1, 1, 1, 1))),
"CommandBar.floatingBorder", floatingBorder,
"CommandBar.separatorSize", 5,
"CommandBar.titleBarSize", 17,
"CommandBar.titleBarButtonGap", 1,
"CommandBar.titleBarBackground", UIDefaultsLookup.getColor("activeCaption"),
"CommandBar.titleBarForeground", UIDefaultsLookup.getColor("activeCaptionText"),
"CommandBar.titleBarFont", boldFont,
"Chevron.size", 13,
"Chevron.alwaysVisible", Boolean.TRUE,
};
table.putDefaults(uiDefaults);
}
if ((products & PRODUCT_GRIDS) != 0) {
uiDefaults = new Object[]{
"AbstractComboBox.useJButton", Boolean.FALSE,
"NestedTableHeader.cellBorder", new HeaderCellBorder(),
"GroupList.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[]{
"TAB", "selectNextGroup",
"shift TAB", "selectPreviousGroup",
}),
};
table.putDefaults(uiDefaults);
}
UIDefaultsLookup.put(table, "Theme.painter", Office2003Painter.getInstance());
// since it used BasicPainter, make sure it is after Theme.Painter is set first.
Object popupMenuBorder = new ExtWindowsDesktopProperty(new String[]{"null"}, new Object[]{((ThemePainter) UIDefaultsLookup.get("Theme.painter")).getMenuItemBorderColor()}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new BorderUIResource(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder((Color) obj[0]), BorderFactory.createEmptyBorder(1, 1, 1, 1)));
}
});
table.put("PopupMenu.border", popupMenuBorder);
}
| public static void initComponentDefaults(UIDefaults table) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
WindowsDesktopProperty defaultTextColor = new WindowsDesktopProperty("win.button.textColor", UIDefaultsLookup.get("controlText"), toolkit);
WindowsDesktopProperty defaultBackgroundColor = new WindowsDesktopProperty("win.3d.backgroundColor", UIDefaultsLookup.get("control"), toolkit);
WindowsDesktopProperty defaultLightColor = new WindowsDesktopProperty("win.3d.lightColor", UIDefaultsLookup.get("controlHighlight"), toolkit);
WindowsDesktopProperty defaultHighlightColor = new WindowsDesktopProperty("win.3d.highlightColor", UIDefaultsLookup.get("controlLtHighlight"), toolkit);
WindowsDesktopProperty defaultShadowColor = new WindowsDesktopProperty("win.3d.shadowColor", UIDefaultsLookup.get("controlShadow"), toolkit);
WindowsDesktopProperty defaultDarkShadowColor = new WindowsDesktopProperty("win.3d.darkShadowColor", UIDefaultsLookup.get("controlDkShadow"), toolkit);
Object toolbarFont = JideSwingUtilities.getMenuFont(toolkit, table);
Object boldFont = JideSwingUtilities.getBoldFont(toolkit, table);
Painter gripperPainter = new Painter() {
public void paint(JComponent c, Graphics g, Rectangle rect, int orientation, int state) {
Office2003Painter.getInstance().paintGripper(c, g, rect, orientation, state);
}
};
ImageIcon sliderHorizontalImage = IconsFactory.getImageIcon(Office2003WindowsUtils.class, "icons/slider_horizontal.gif");
ImageIcon sliderVerticalalImage = IconsFactory.getImageIcon(Office2003WindowsUtils.class, "icons/slider_vertical.gif");
Object uiDefaults[] = new Object[]{
"JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_OFFICE2003,
"JideTabbedPane.defaultTabColorTheme", JideTabbedPane.COLOR_THEME_OFFICE2003,
"JideTabbedPane.contentBorderInsets", new InsetsUIResource(3, 3, 3, 3),
"JideTabbedPane.gripperPainter", gripperPainter,
"JideTabbedPane.alwaysShowLineBorder", Boolean.FALSE,
"JideTabbedPane.showFocusIndicator", Boolean.TRUE,
"JideSplitPaneDivider.gripperPainter", gripperPainter,
"Gripper.size", 8,
"Gripper.painter", gripperPainter,
"Icon.floating", Boolean.FALSE,
"RangeSlider.lowerIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 0, 0, 9, 10),
"RangeSlider.upperIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 0, 10, 9, 10),
"RangeSlider.middleIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 0, 20, 9, 7),
"RangeSlider.lowerRIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 9, 0, 9, 10),
"RangeSlider.upperRIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 9, 10, 9, 10),
"RangeSlider.middleRIcon", IconsFactory.getIcon(null, sliderHorizontalImage, 9, 20, 9, 7),
"RangeSlider.lowerVIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 0, 0, 10, 9),
"RangeSlider.upperVIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 10, 0, 10, 9),
"RangeSlider.middleVIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 20, 0, 7, 9),
"RangeSlider.lowerVRIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 0, 9, 10, 9),
"RangeSlider.upperVRIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 10, 9, 10, 9),
"RangeSlider.middleVRIcon", IconsFactory.getIcon(null, sliderVerticalalImage, 20, 9, 7, 9),
"JideScrollPane.border", UIDefaultsLookup.getBorder("ScrollPane.border"),
"Menu.margin", new InsetsUIResource(2, 7, 3, 7),
"Menu.submenuPopupOffsetX", 1,
"Menu.submenuPopupOffsetY", 0,
"MenuBar.border", new BorderUIResource(BorderFactory.createEmptyBorder(1, 2, 1, 2)),
"PopupMenu.background", new UIDefaults.ActiveValue() {
public Object createValue(UIDefaults table) {
return Office2003Painter.getInstance().getMenuItemBackground();
}
},
};
table.putDefaults(uiDefaults);
int products = LookAndFeelFactory.getProductsUsed();
if ((products & PRODUCT_DOCK) != 0) {
boolean useShadowBorder = "true".equals(SecurityUtils.getProperty("jide.shadeSlidingBorder", "false"));
Object slidingEastFrameBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new SlidingFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(1, SlidingFrameBorder.SHADOW_SIZE + 5, 1, 1));
}
});
Object slidingWestFrameBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new SlidingFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(1, 1, 1, SlidingFrameBorder.SHADOW_SIZE + 5));
}
});
Object slidingNorthFrameBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new SlidingFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(1, 1, SlidingFrameBorder.SHADOW_SIZE + 5, 1));
}
});
Object slidingSouthFrameBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new SlidingFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(SlidingFrameBorder.SHADOW_SIZE + 5, 1, 1, 1));
}
});
Object slidingEastFrameBorder2 = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new ResizeFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(0, 4, 0, 0));
}
});
Object slidingWestFrameBorder2 = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new ResizeFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(0, 0, 0, 4));
}
});
Object slidingNorthFrameBorder2 = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new ResizeFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(0, 0, 4, 0));
}
});
Object slidingSouthFrameBorder2 = new ExtWindowsDesktopProperty(new String[]{"win.3d.lightColor", "win.3d.highlightColor", "win.3d.shadowColor", "win.3d.darkShadowColor"},
new Object[]{UIDefaultsLookup.get("control"), UIDefaultsLookup.get("controlLtHighlight"), UIDefaultsLookup.get("controlShadow"), UIDefaultsLookup.get("controlDkShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new ResizeFrameBorder((Color) obj[0], (Color) obj[1], (Color) obj[2], (Color) obj[3],
new Insets(4, 0, 0, 0));
}
});
uiDefaults = new Object[]{
// dock
"SidePane.foreground", defaultTextColor,
"SidePane.lineColor", new UIDefaults.ActiveValue() {
public Object createValue(UIDefaults table) {
return Office2003Painter.getInstance().getControlShadow();
}
},
"StatusBarItem.border", new BorderUIResource(BorderFactory.createEmptyBorder(0, 1, 0, 1)),
"StatusBar.border", new StatusBarBorder(),
"DockableFrame.titleBorder", new BorderUIResource(BorderFactory.createEmptyBorder(0, 0, 0, 0)),
"DockableFrameTitlePane.use3dButtons", Boolean.FALSE,
"DockableFrameTitlePane.gripperPainter", gripperPainter,
"DockableFrameTitlePane.margin", new InsetsUIResource(1, 6, 1, 6), // gap
"DockableFrameTitlePane.contentFilledButtons", true,
"DockableFrame.activeTitleForeground", UIDefaultsLookup.getColor("DockableFrame.inactiveTitleForeground"),
"DockableFrame.slidingEastBorder", useShadowBorder ? slidingEastFrameBorder : slidingEastFrameBorder2,
"DockableFrame.slidingWestBorder", useShadowBorder ? slidingWestFrameBorder : slidingWestFrameBorder2,
"DockableFrame.slidingNorthBorder", useShadowBorder ? slidingNorthFrameBorder : slidingNorthFrameBorder2,
"DockableFrame.slidingSouthBorder", useShadowBorder ? slidingSouthFrameBorder : slidingSouthFrameBorder2,
"FrameContainer.contentBorderInsets", new InsetsUIResource(3, 3, 3, 3),
};
table.putDefaults(uiDefaults);
}
if ((products & PRODUCT_ACTION) != 0) {
Object floatingBorder = new ExtWindowsDesktopProperty(new String[]{"win.3d.titleBarColor"},
new Object[]{UIDefaultsLookup.get("controlShadow")}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new BorderUIResource(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder((Color) obj[0], 2),
BorderFactory.createEmptyBorder(1, 1, 1, 1)));
}
});
uiDefaults = new Object[]{
// action
"CommandBar.font", toolbarFont,
"CommandBar.background", defaultBackgroundColor,
"CommandBar.foreground", defaultTextColor,
"CommandBar.shadow", defaultShadowColor,
"CommandBar.darkShadow", defaultDarkShadowColor,
"CommandBar.light", defaultLightColor,
"CommandBar.highlight", defaultHighlightColor,
"CommandBar.border", new BorderUIResource(BorderFactory.createEmptyBorder(1, 2, 2, 0)),
"CommandBar.borderVert", new BorderUIResource(BorderFactory.createEmptyBorder(2, 1, 0, 2)),
"CommandBar.borderFloating", new BorderUIResource(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(UIDefaultsLookup.getColor("activeCaption"), 2),
BorderFactory.createEmptyBorder(1, 1, 1, 1))),
"CommandBar.floatingBorder", floatingBorder,
"CommandBar.separatorSize", 5,
"CommandBar.titleBarSize", 17,
"CommandBar.titleBarButtonGap", 1,
"CommandBar.titleBarBackground", UIDefaultsLookup.getColor("activeCaption"),
"CommandBar.titleBarForeground", UIDefaultsLookup.getColor("activeCaptionText"),
"CommandBar.titleBarFont", boldFont,
"Chevron.size", 13,
"Chevron.alwaysVisible", Boolean.TRUE,
};
table.putDefaults(uiDefaults);
}
if ((products & PRODUCT_GRIDS) != 0) {
uiDefaults = new Object[]{
"AbstractComboBox.useJButton", Boolean.FALSE,
"NestedTableHeader.cellBorder", new HeaderCellBorder(),
"GroupList.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[]{
"TAB", "selectNextGroup",
"shift TAB", "selectPreviousGroup",
}),
};
table.putDefaults(uiDefaults);
}
UIDefaultsLookup.put(table, "Theme.painter", Office2003Painter.getInstance());
// since it used BasicPainter, make sure it is after Theme.Painter is set first.
Object popupMenuBorder = new ExtWindowsDesktopProperty(new String[]{"null"}, new Object[]{((ThemePainter) UIDefaultsLookup.get("Theme.painter")).getMenuItemBorderColor()}, toolkit, new ConvertListener() {
public Object convert(Object[] obj) {
return new BorderUIResource(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder((Color) obj[0]), BorderFactory.createEmptyBorder(1, 1, 1, 1)));
}
});
table.put("PopupMenu.border", popupMenuBorder);
}
|
diff --git a/bobo-contrib/src/main/java/com/browseengine/bobo/geosearch/query/GeoQuery.java b/bobo-contrib/src/main/java/com/browseengine/bobo/geosearch/query/GeoQuery.java
index 1b97d50..7af82f3 100644
--- a/bobo-contrib/src/main/java/com/browseengine/bobo/geosearch/query/GeoQuery.java
+++ b/bobo-contrib/src/main/java/com/browseengine/bobo/geosearch/query/GeoQuery.java
@@ -1,99 +1,100 @@
/**
*
*/
package com.browseengine.bobo.geosearch.query;
import java.io.IOException;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.Weight;
import com.browseengine.bobo.geosearch.impl.GeoConverter;
import com.browseengine.bobo.geosearch.impl.GeoUtil;
import com.browseengine.bobo.geosearch.score.impl.Conversions;
/**
* @author Shane Detsch
* @author Ken McCracken
*
*/
public class GeoQuery extends Query {
/**
*
*/
private static final long serialVersionUID = 1L;
float rangeInKm;
GeoConverter geoConvertor;
private static final float MINIMUM_RANGE_IN_KM = 0.001f;
private static final float MAXIMUM_RANGE_IN_KM = 700f;
double longRadians;
double latRadians;
public GeoQuery(double centroidLatitude, double centroidLongitude, Float rangeInKm) {
latRadians = Conversions.d2r(centroidLatitude);
longRadians = Conversions.d2r(centroidLongitude);
+ this.rangeInKm = rangeInKm;
- if (!( null == rangeInKm)) {
+ if (null == rangeInKm) {
throw new RuntimeException("please specify rangeInKilometers");
}
if (this.rangeInKm < MINIMUM_RANGE_IN_KM || this.rangeInKm > MAXIMUM_RANGE_IN_KM) {
throw new RuntimeException("rangeInMiles out of range ["+MINIMUM_RANGE_IN_KM+", "+MAXIMUM_RANGE_IN_KM+"]: "+this.rangeInKm);
}
if(!GeoUtil.isValidLatitude(centroidLatitude) || !GeoUtil.isValidLongitude(centroidLongitude)) {
throw new RuntimeException("bad latitude or longitude: " + centroidLatitude + ", " + centroidLongitude );
}
}
/**
* @return the centroidX
*/
public double getCentroidLongitude() {
return longRadians;
}
/**
* @return the centroidX
*/
public double getCentroidLatitude() {
return latRadians;
}
public float getRangeInKm() {
return this.rangeInKm;
}
/**
* {@inheritDoc}
*/
@Override
public Weight createWeight(Searcher searcher) throws IOException {
return new GeoWeight(this);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "GeoQuery [centroidLatitude=" + latRadians + ", centroidLongitude=" + longRadians
+ ", rangeInKm =" + rangeInKm + "]";
}
/**
* {@inheritDoc}
*/
@Override
public String toString(String arg0) {
return toString();
}
}
| false | true | public GeoQuery(double centroidLatitude, double centroidLongitude, Float rangeInKm) {
latRadians = Conversions.d2r(centroidLatitude);
longRadians = Conversions.d2r(centroidLongitude);
if (!( null == rangeInKm)) {
throw new RuntimeException("please specify rangeInKilometers");
}
if (this.rangeInKm < MINIMUM_RANGE_IN_KM || this.rangeInKm > MAXIMUM_RANGE_IN_KM) {
throw new RuntimeException("rangeInMiles out of range ["+MINIMUM_RANGE_IN_KM+", "+MAXIMUM_RANGE_IN_KM+"]: "+this.rangeInKm);
}
if(!GeoUtil.isValidLatitude(centroidLatitude) || !GeoUtil.isValidLongitude(centroidLongitude)) {
throw new RuntimeException("bad latitude or longitude: " + centroidLatitude + ", " + centroidLongitude );
}
}
| public GeoQuery(double centroidLatitude, double centroidLongitude, Float rangeInKm) {
latRadians = Conversions.d2r(centroidLatitude);
longRadians = Conversions.d2r(centroidLongitude);
this.rangeInKm = rangeInKm;
if (null == rangeInKm) {
throw new RuntimeException("please specify rangeInKilometers");
}
if (this.rangeInKm < MINIMUM_RANGE_IN_KM || this.rangeInKm > MAXIMUM_RANGE_IN_KM) {
throw new RuntimeException("rangeInMiles out of range ["+MINIMUM_RANGE_IN_KM+", "+MAXIMUM_RANGE_IN_KM+"]: "+this.rangeInKm);
}
if(!GeoUtil.isValidLatitude(centroidLatitude) || !GeoUtil.isValidLongitude(centroidLongitude)) {
throw new RuntimeException("bad latitude or longitude: " + centroidLatitude + ", " + centroidLongitude );
}
}
|
diff --git a/freeplane/src/org/freeplane/view/swing/addins/BlinkingNodeHook.java b/freeplane/src/org/freeplane/view/swing/addins/BlinkingNodeHook.java
index 2e2af3f6f..fc4100085 100644
--- a/freeplane/src/org/freeplane/view/swing/addins/BlinkingNodeHook.java
+++ b/freeplane/src/org/freeplane/view/swing/addins/BlinkingNodeHook.java
@@ -1,195 +1,195 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file author is Christian Foltin
* It is modified by Dimitry Polivaev in 2008.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.view.swing.addins;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import javax.swing.SwingUtilities;
import org.freeplane.core.addins.NodeHookDescriptor;
import org.freeplane.core.addins.PersistentNodeHook;
import org.freeplane.core.controller.Controller;
import org.freeplane.core.controller.IMapLifeCycleListener;
import org.freeplane.core.controller.INodeViewVisitor;
import org.freeplane.core.extension.IExtension;
import org.freeplane.core.ui.ActionLocationDescriptor;
import org.freeplane.core.undo.IActor;
import org.freeplane.core.util.SysUtils;
import org.freeplane.features.common.map.IMapChangeListener;
import org.freeplane.features.common.map.INodeView;
import org.freeplane.features.common.map.MapChangeEvent;
import org.freeplane.features.common.map.MapController;
import org.freeplane.features.common.map.MapModel;
import org.freeplane.features.common.map.NodeModel;
import org.freeplane.n3.nanoxml.XMLElement;
import org.freeplane.view.swing.map.NodeView;
/**
*/
@NodeHookDescriptor(hookName = "accessories/plugins/BlinkingNodeHook.properties", onceForMap = false)
@ActionLocationDescriptor(locations = { "/menu_bar/format/nodes" })
public class BlinkingNodeHook extends PersistentNodeHook {
protected class TimerColorChanger extends TimerTask implements IExtension, IMapChangeListener,
IMapLifeCycleListener {
final private NodeModel node;
final private Timer timer;
TimerColorChanger(final NodeModel node) {
this.node = node;
final MapController mapController = Controller.getCurrentModeController().getMapController();
mapController.addMapChangeListener(this);
mapController.addMapLifeCycleListener(this);
timer = SysUtils.createTimer(getClass().getSimpleName());
timer.schedule(this, 500, 500);
BlinkingNodeHook.colors.clear();
BlinkingNodeHook.colors.add(Color.BLUE);
BlinkingNodeHook.colors.add(Color.RED);
BlinkingNodeHook.colors.add(Color.MAGENTA);
BlinkingNodeHook.colors.add(Color.CYAN);
}
public NodeModel getNode() {
return node;
}
public Timer getTimer() {
return timer;
}
/** TimerTask method to enable the selection after a given time. */
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (getNode() == null || Controller.getCurrentModeController().isBlocked()) {
return;
}
getNode().acceptViewVisitor(new INodeViewVisitor() {
public void visit(final INodeView nodeView) {
if(! (nodeView instanceof NodeView)){
return;
}
final Component container = ((NodeView)nodeView).getMainView();
- if (!container.isVisible()) {
+ if (container == null || !container.isVisible()) {
return;
}
final Color col = container.getForeground();
int index = -1;
if (col != null && BlinkingNodeHook.colors.contains(col)) {
index = BlinkingNodeHook.colors.indexOf(col);
}
index++;
if (index >= BlinkingNodeHook.colors.size()) {
index = 0;
}
container.setForeground(BlinkingNodeHook.colors.get(index));
}
});
}
});
}
public void mapChanged(final MapChangeEvent event) {
}
public void onNodeDeleted(final NodeModel parent, final NodeModel child, final int index) {
if (Controller.getCurrentModeController().isUndoAction() || !(node.equals(child) || node.isDescendantOf(child))) {
return;
}
final IActor actor = new IActor() {
public void act() {
EventQueue.invokeLater(new Runnable() {
public void run() {
remove(node, node.getExtension(TimerColorChanger.class));
}
});
}
public String getDescription() {
return "BlinkingNodeHook.timer";
}
public void undo() {
node.addExtension(new TimerColorChanger(node));
}
};
Controller.getCurrentModeController().execute(actor, node.getMap());
}
public void onNodeInserted(final NodeModel parent, final NodeModel child, final int newIndex) {
}
public void onNodeMoved(final NodeModel oldParent, final int oldIndex, final NodeModel newParent,
final NodeModel child, final int newIndex) {
}
public void onPreNodeDelete(final NodeModel oldParent, final NodeModel selectedNode, final int index) {
}
public void onPreNodeMoved(final NodeModel oldParent, final int oldIndex, final NodeModel newParent,
final NodeModel child, final int newIndex) {
}
public void onCreate(final MapModel map) {
}
public void onRemove(final MapModel map) {
if (node.getMap().equals(map)) {
timer.cancel();
}
}
}
static Vector<Color> colors = new Vector<Color>();
public BlinkingNodeHook() {
super();
}
@Override
protected IExtension createExtension(final NodeModel node, final XMLElement element) {
return new TimerColorChanger(node);
}
@Override
protected Class<TimerColorChanger> getExtensionClass() {
return TimerColorChanger.class;
}
/*
* (non-Javadoc)
* @see freeplane.extensions.MindMapHook#shutdownMapHook()
*/
@Override
public void remove(final NodeModel node, final IExtension extension) {
final TimerColorChanger timer = ((TimerColorChanger) extension);
timer.getTimer().cancel();
final MapController mapController = Controller.getCurrentModeController().getMapController();
mapController.removeMapChangeListener(timer);
mapController.removeMapLifeCycleListener(timer);
super.remove(node, extension);
}
}
| true | true | public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (getNode() == null || Controller.getCurrentModeController().isBlocked()) {
return;
}
getNode().acceptViewVisitor(new INodeViewVisitor() {
public void visit(final INodeView nodeView) {
if(! (nodeView instanceof NodeView)){
return;
}
final Component container = ((NodeView)nodeView).getMainView();
if (!container.isVisible()) {
return;
}
final Color col = container.getForeground();
int index = -1;
if (col != null && BlinkingNodeHook.colors.contains(col)) {
index = BlinkingNodeHook.colors.indexOf(col);
}
index++;
if (index >= BlinkingNodeHook.colors.size()) {
index = 0;
}
container.setForeground(BlinkingNodeHook.colors.get(index));
}
});
}
});
}
| public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (getNode() == null || Controller.getCurrentModeController().isBlocked()) {
return;
}
getNode().acceptViewVisitor(new INodeViewVisitor() {
public void visit(final INodeView nodeView) {
if(! (nodeView instanceof NodeView)){
return;
}
final Component container = ((NodeView)nodeView).getMainView();
if (container == null || !container.isVisible()) {
return;
}
final Color col = container.getForeground();
int index = -1;
if (col != null && BlinkingNodeHook.colors.contains(col)) {
index = BlinkingNodeHook.colors.indexOf(col);
}
index++;
if (index >= BlinkingNodeHook.colors.size()) {
index = 0;
}
container.setForeground(BlinkingNodeHook.colors.get(index));
}
});
}
});
}
|
diff --git a/src/net/sf/freecol/common/model/Building.java b/src/net/sf/freecol/common/model/Building.java
index c1555fa4c..7ba549d7a 100644
--- a/src/net/sf/freecol/common/model/Building.java
+++ b/src/net/sf/freecol/common/model/Building.java
@@ -1,982 +1,983 @@
package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.sf.freecol.FreeCol;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Represents a building in a colony.
*
* <br><br>
*
* Each <code>Building</code> has a type and a level.
* The levels are {@link #NOT_BUILT}, {@link #HOUSE},
* {@link #SHOP} and {@link #FACTORY}. The {@link #getName name}
* of a <code>Building</code> depends on both the type and
* the level:
*
* <br><br>Type {@link #STOCKADE}
* <br>Level {@link #NOT_BUILT}: <i>null</i>
* <br>Level {@link #HOUSE}: "Stockade"
* <br>Level {@link #SHOP}: "Fort"
* <br>Level {@link #FACTORY}: "Fortress"
*
*/
public final class Building extends FreeColGameObject implements WorkLocation, Ownable {
public static final String COPYRIGHT = "Copyright (C) 2003-2006 The FreeCol Team";
public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html";
public static final String REVISION = "$Revision$";
/**
* The maximum level.
*/
public static final int MAX_LEVEL = 3;
/** The type of a building. */
public static final int NONE = -1,
TOWN_HALL = 0,
CARPENTER = 1,
BLACKSMITH = 2,
TOBACCONIST = 3,
WEAVER = 4,
DISTILLER = 5,
FUR_TRADER = 6,
SCHOOLHOUSE = 7, //10
ARMORY = 8,
CHURCH = 9, //13
STOCKADE = 10, //7
WAREHOUSE = 11,
STABLES = 12,
DOCK = 13, //9
PRINTING_PRESS = 14,
CUSTOM_HOUSE = 15;
/** The maximum number of building types. */
public static final int NUMBER_OF_TYPES = FreeCol.specification.numberOfBuildingTypes();
/** The level of a building. */
public static final int NOT_BUILT = 0,
HOUSE = 1,
SHOP = 2,
FACTORY = 3;
/**
* Sets the maximum number of units in one building.
* This will become a non-constant later so always use
* the {@link #getMaxUnits()}.
*/
private static final int MAX_UNITS = 3;
/** The colony containing this building. */
private Colony colony;
/** The type of this building. */
private int type;
/**
* The level this building has. This should be on of:
* <ul>
* <li>{@link #NOT_BUILT}</li>
* <li>{@link #HOUSE}</li>
* <li>{@link #SHOP}</li>
* <li>{@link #FACTORY}</li>
* </ul>
*/
private int level;
/**
* List of the units which have this <code>Building</code>
* as it's {@link Unit#getLocation() location}.
*/
private List units = new ArrayList();
private final BuildingType buildingType;
/**
* Creates a new <code>Building</code>.
*
* @param game The <code>Game</code> this object belongs to.
* @param colony The colony in which this building is located.
* @param type The type of building.
* @param level The level of the building: {@link #NOT_BUILT},
* {@link #HOUSE}, {@link #SHOP} or {@link #FACTORY}.
*/
public Building(Game game, Colony colony, int type, int level) {
super(game);
this.colony = colony;
this.type = type;
this.level = level;
buildingType = FreeCol.specification.buildingType( type );
}
/**
* Initiates a new <code>Building</code> from an <code>Element</code>.
*
* @param game The <code>Game</code> this object belongs to.
* @param element The <code>Element</code> (in a DOM-parsed XML-tree)
* that describes this object.
*/
public Building(Game game, Element element) {
super(game, element);
readFromXMLElement(element);
buildingType = FreeCol.specification.buildingType( type );
}
/**
* Gets the owner of this <code>Ownable</code>.
*
* @return The <code>Player</code> controlling this
* {@link Ownable}.
*/
public Player getOwner() {
return colony.getOwner();
}
/**
* Gets the <code>Tile</code> where this <code>Building</code>
* is located.
*
* @return The <code>Tile</code>.
*/
public Tile getTile() {
return colony.getTile();
}
/**
* Gets the level of the building. One of {@link #NOT_BUILT},
* {@link #HOUSE}, {@link #SHOP} and {@link #FACTORY}.
*
* @return The current level.
*/
public int getLevel() {
return level;
}
/**
* Sets the level of the building.
*
* @param level The new level of the building. This should be
* one of {@link #NOT_BUILT}, {@link #HOUSE},
* {@link #SHOP} and {@link #FACTORY}.
*/
public void setLevel(int level) {
this.level = level;
}
/**
* Gets the name of a building.
*
* @return The name of the <code>Building</code> or
* <i>null</i> if the building has not been built.
*/
public String getName() {
return isBuilt() && (level - 1) < buildingType.numberOfLevels()
? buildingType.level(level - 1).name
: null;
}
/**
* Gets the name of the improved building of the same type.
* An improved building is a building of a higher level.
*
* @return The name of the improved building or <code>null</code>
* if the improvement does not exist.
*/
public String getNextName() {
if ( ! canBuildNext() ) {
return null;
}
return level < buildingType.numberOfLevels()
? buildingType.level(level).name
: null;
}
/**
* Gets the number of hammers required for the improved
* building of the same type.
*
* @return The number of hammers required for the improved
* building of the same type, or <code>-1</code> if
* the building does not exist.
*/
public int getNextHammers() {
if (!canBuildNext()) {
return -1;
}
return level < buildingType.numberOfLevels()
? buildingType.level(level).hammersRequired
: -1;
}
/**
* Gets the number of tools required for the improved
* building of the same type.
*
* @return The number of tools required for the improved
* building of the same type, or <code>-1</code> if
* the building does not exist.
*/
public int getNextTools() {
if (!canBuildNext()) {
return -1;
}
return level < buildingType.numberOfLevels()
? buildingType.level(level).toolsRequired
: -1;
}
/**
* Gets the colony population required for the improved
* building of the same type.
*
* @return The colony population required for the improved
* building of the same type, or <code>-1</code> if
* the building does not exist.
*/
public int getNextPop() {
if (!canBuildNext()) {
return -1;
}
return level < buildingType.numberOfLevels()
? buildingType.level(level).populationRequired
: -1;
}
/**
* Checks if this building can have a higher level.
*
* @return If this <code>Building</code> can have a
* higher level, that {@link FoundingFather Adam Smith}
* is present for manufactoring factory level buildings
* and that the <code>Colony</code> containing this
* <code>Building</code> has a sufficiently high
* population.
*/
public boolean canBuildNext() {
if (level >= MAX_LEVEL) {
return false;
}
if (getType() == CUSTOM_HOUSE) {
if (getColony().getOwner().hasFather(FoundingFather.PETER_STUYVESANT)) {
return true;
}
return false;
}
if (level+1 >= FACTORY && !getColony().getOwner().hasFather(FoundingFather.ADAM_SMITH)
&& (type == BLACKSMITH || type == TOBACCONIST || type == WEAVER
|| type == DISTILLER || type == FUR_TRADER || type == ARMORY)) {
return false;
}
BuildingType buildingType = FreeCol.specification.buildingType( type );
// if there are no more improvements available for this building type..
if ( buildingType.numberOfLevels() == level ) {
return false;
}
if (getType() == DOCK && getColony().isLandLocked()) {
return false;
}
if (buildingType.level(level).populationRequired > colony.getUnitCount()) {
return false;
}
return true;
}
/**
* Checks if the building has been built.
* @return The result.
*/
public boolean isBuilt() {
return 0 < level;
}
/**
* Gets a pointer to the colony containing this building.
* @return The <code>Colony</code>.
*/
public Colony getColony() {
return colony;
}
/**
* Gets the type of this building.
* @return The type.
*/
public int getType() {
return type;
}
/**
* Checks if this building is of a given type.
*
* @param type The type.
* @return <i>true</i> if the building is of the given type and <i>false</i> otherwise.
*/
public boolean isType(int type) {
return getType() == type;
}
/**
* Gets the maximum number of units allowed in this <code>Building</code>.
* @return The number.
*/
public int getMaxUnits() {
if (type == STOCKADE || type == DOCK || type == WAREHOUSE ||
type == STABLES || type == PRINTING_PRESS || type == CUSTOM_HOUSE) {
return 0;
} else if (type == SCHOOLHOUSE) {
return getLevel();
} else {
return MAX_UNITS;
}
}
/**
* Gets the amount of units at this <code>WorkLocation</code>.
* @return The amount of units at this {@link WorkLocation}.
*/
public int getUnitCount() {
return units.size();
}
/**
* Checks if the specified <code>Locatable</code> may be added to
* this <code>WorkLocation</code>.
*
* @param locatable the <code>Locatable</code>.
* @return <i>true</i> if the <i>Unit</i> may be added and
* <i>false</i> otherwise.
*/
public boolean canAdd(Locatable locatable) {
if (getUnitCount() >= getMaxUnits()) {
return false;
}
if (!(locatable instanceof Unit)) {
return false;
}
if (!((Unit) locatable).isColonist() && ((Unit) locatable).getType() != Unit.INDIAN_CONVERT) {
return false;
}
if (getType() == SCHOOLHOUSE && (getLevel() < Unit.getSkillLevel(((Unit) locatable).getType())
|| ((Unit) locatable).getType() == Unit.INDIAN_CONVERT
|| ((Unit) locatable).getType() == Unit.FREE_COLONIST
|| ((Unit) locatable).getType() == Unit.INDENTURED_SERVANT
|| ((Unit) locatable).getType() == Unit.PETTY_CRIMINAL)) {
return false;
}
return true;
}
/**
* Adds the specified <code>Locatable</code> to this
* <code>WorkLocation</code>.
*
* @param locatable The <code>Locatable</code> that shall
* be added to this <code>WorkLocation</code>.
*/
public void add(Locatable locatable) {
if (!canAdd(locatable)) {
throw new IllegalStateException();
}
Unit unit = (Unit) locatable;
if (unit.isArmed()) {
unit.setArmed(false);
}
if (unit.isMounted()) {
unit.setMounted(false);
}
if (unit.isMissionary()) {
unit.setMissionary(false);
}
if (unit.getNumberOfTools() > 0) {
unit.setNumberOfTools(0);
}
units.add(unit);
getColony().updatePopulation();
}
/**
* Returns the unit type being an expert in this <code>Building</code>.
*
* @return The {@link Unit#getType unit type}.
* @see Unit#getExpertWorkType
* @see ColonyTile#getExpertForProducing
*/
public int getExpertUnitType() {
switch (getType()) {
case TOWN_HALL: return Unit.ELDER_STATESMAN;
case CARPENTER: return Unit.MASTER_CARPENTER;
case BLACKSMITH: return Unit.MASTER_BLACKSMITH;
case TOBACCONIST: return Unit.MASTER_TOBACCONIST;
case WEAVER: return Unit.MASTER_WEAVER;
case DISTILLER: return Unit.MASTER_DISTILLER;
case FUR_TRADER: return Unit.MASTER_FUR_TRADER;
case ARMORY: return Unit.MASTER_GUNSMITH;
case CHURCH: return Unit.FIREBRAND_PREACHER;
default: return -1;
}
}
/**
* Removes the specified <code>Locatable</code> from
* this <code>WorkLocation</code>.
*
* @param locatable The <code>Locatable</code> that shall
* be removed from this <code>WorkLocation</code>.
*/
public void remove(Locatable locatable) {
if (!(locatable instanceof Unit)) {
throw new IllegalStateException();
}
int index = units.indexOf(locatable);
if (index != -1) {
units.remove(index);
getColony().updatePopulation();
}
}
/**
* Checks if this <code>Building</code> contains the specified
* <code>Locatable</code>.
*
* @param locatable The <code>Locatable</code> to test the
* presence of.
* @return <ul>
* <li><code>>true</code>if the specified
* <code>Locatable</code> is in this
* <code>Building</code> and</li>
* <li><code>false</code> otherwise.</li>
* </ul>
*/
public boolean contains(Locatable locatable) {
if (locatable instanceof Unit) {
int index = units.indexOf(locatable);
return (index != -1) ? true:false;
}
return false;
}
/**
* Gets the first unit in this building.
* @return The <code>Unit</code>.
*/
public Unit getFirstUnit() {
if (units.size() > 0) {
return (Unit) units.get(0);
}
return null;
}
/**
* Gets the last unit in this building.
* @return The <code>Unit</code>.
*/
public Unit getLastUnit() {
if (units.size() > 0) {
return (Unit) units.get(units.size()-1);
}
return null;
}
/**
* Gets an <code>Iterator</code> of every <code>Unit</code>
* directly located on this <code>Building</code>.
*
* @return The <code>Iterator</code>.
*/
public Iterator getUnitIterator() {
return units.iterator();
}
/**
* Gets the best unit to train for the given unit type.
*
* @param unitType The unit type to train for.
* @return The <code>Unit</code>.
*/
private Unit getUnitToTrain(int unitType) {
Unit bestUnit = null;
int bestScore = 0;
Iterator i = colony.getUnitIterator();
while (i.hasNext()) {
Unit unit = (Unit) i.next();
if (unit.getTrainingType() != -1 && unit.getNeededTurnsOfTraining() <= unit.getTurnsOfTraining()) {
continue;
}
if (unit.getType() == Unit.FREE_COLONIST && unit.getTrainingType() == unitType) {
if (bestUnit == null || unit.getTurnsOfTraining() > bestUnit.getTurnsOfTraining()) {
bestUnit = unit;
bestScore = 5;
}
} else if (unit.getType() == Unit.FREE_COLONIST && unit.getTurnsOfTraining() == 0) {
if (bestScore < 4) {
bestUnit = unit;
bestScore = 4;
}
} else if (unit.getType() == Unit.INDENTURED_SERVANT) {
if (bestScore < 3) {
bestUnit = unit;
bestScore = 3;
}
} else if (unit.getType() == Unit.PETTY_CRIMINAL) {
if (bestScore < 2) {
bestUnit = unit;
bestScore = 2;
}
} else if (unit.getType() == Unit.FREE_COLONIST && getTeacher(unitType) == null) {
if (bestScore < 1) {
bestUnit = unit;
bestScore = 1;
}
}
}
return bestUnit;
}
/**
* Gets this <code>Location</code>'s <code>GoodsContainer</code>.
* @return <code>null</code>.
*/
public GoodsContainer getGoodsContainer() {
return null;
}
/**
* Gets a teacher for the given unit type.
*
* @param unitType The type of unit to find a teacher for.
* @return The teacher or <code>null</code> if no teacher
* can be found for the given unit type.
*/
private Unit getTeacher(int unitType) {
Iterator i = colony.getUnitIterator();
while (i.hasNext()) {
Unit unit = (Unit) i.next();
if (unit.getType() == unitType) {
return unit;
}
}
return null;
}
/**
* Prepares this <code>Building</code> for a new turn.
*/
public void newTurn() {
if ((level == NOT_BUILT) && (type != CHURCH)) return; // Don't do anything if the building does not exist.
if (type == SCHOOLHOUSE) {
Iterator i = getUnitIterator();
while (i.hasNext()) {
Unit teacher = (Unit) i.next();
Unit student = getUnitToTrain(teacher.getType());
if (student != null) {
if (student.getTrainingType() != teacher.getType() && student.getTrainingType() != Unit.FREE_COLONIST) {
student.setTrainingType(teacher.getType());
student.setTurnsOfTraining(0);
}
student.setTurnsOfTraining(student.getTurnsOfTraining() + ((colony.getSoL() == 100) ? 2 : 1));
if (student.getTurnsOfTraining() >= student.getNeededTurnsOfTraining()) {
String oldName = student.getName();
if (student.getType() == Unit.INDENTURED_SERVANT) {
student.setType(Unit.FREE_COLONIST);
} else if (student.getType() == Unit.PETTY_CRIMINAL) {
student.setType(Unit.INDENTURED_SERVANT);
} else {
student.setType(student.getTrainingType());
}
student.setTrainingType(-1);
student.setTurnsOfTraining(0);
addModelMessage(this, "model.unit.unitImproved",
new String[][] {{"%oldName%", oldName},
- {"%newName%", student.getName()}},
+ {"%newName%", student.getName()},
+ {"%nation%", getOwner().getName()}},
ModelMessage.UNIT_IMPROVED);
}
} else {
addModelMessage(this, "model.building.noStudent",
new String[][] {{"%teacher%", teacher.getName()},
{"%colony%", colony.getName()}},
ModelMessage.WARNING);
}
}
} else if (getGoodsOutputType() != -1) {
int goodsInput = getGoodsInput();
int goodsOutput = getProduction();
int goodsInputType = getGoodsInputType();
int goodsOutputType = getGoodsOutputType();
if (getGoodsInput() == 0 && getMaximumGoodsInput() > 0) {
addModelMessage(this, "model.building.notEnoughInput",
new String[][] {{"%inputGoods%", Goods.getName(goodsInputType)},
{"%building%", getName()},
{"%colony%", colony.getName()}},
ModelMessage.WARNING);
}
if (goodsOutput <= 0) return;
// Actually produce the goods:
if (goodsOutputType == Goods.CROSSES) {
colony.getOwner().incrementCrosses(goodsOutput);
} else if (goodsOutputType == Goods.BELLS) {
colony.getOwner().incrementBells(goodsOutput);
colony.addBells(goodsOutput);
} else {
colony.removeGoods(goodsInputType, goodsInput);
if (goodsOutputType == Goods.HAMMERS) {
colony.addHammers(goodsOutput);
return;
}
colony.addGoods(goodsOutputType, goodsOutput);
}
}
}
/**
* Returns the type of goods this <code>Building</code>
* produces.
*
* @return The type of goods this <code>Building</code>
* produces or <code>-1</code> if there is no
* goods production by this <code>Building</code>.
*/
public int getGoodsOutputType() {
switch(type) {
case BLACKSMITH: return Goods.TOOLS;
case TOBACCONIST: return Goods.CIGARS;
case WEAVER: return Goods.CLOTH;
case DISTILLER: return Goods.RUM;
case FUR_TRADER: return Goods.COATS;
case ARMORY: return Goods.MUSKETS;
case CHURCH: return Goods.CROSSES;
case TOWN_HALL: return Goods.BELLS;
case CARPENTER: return Goods.HAMMERS;
default: return -1;
}
}
/**
* Returns the type of goods this building needs for
* input.
*
* @return The type of goods this <code>Building</code>
* requires as input in order to produce it's
* {@link #getGoodsOutputType output}.
*/
public int getGoodsInputType() {
switch(type) {
case BLACKSMITH:
return Goods.ORE;
case TOBACCONIST:
return Goods.TOBACCO;
case WEAVER:
return Goods.COTTON;
case DISTILLER:
return Goods.SUGAR;
case FUR_TRADER:
return Goods.FURS;
case ARMORY:
return Goods.TOOLS;
case CARPENTER:
return Goods.LUMBER;
default:
return -1;
}
}
/**
* Returns the amount of goods needed to have
* a full production.
*
* @return The maximum level of goods needed in
* order to have the maximum possible
* production with the current configuration
* of workers and improvements. This is actually
* the {@link #getGoodsInput input} being
* used this turn, provided that the amount of goods in
* the <code>Colony</code> is either larger or
* the same as the value returned by this method.
* @see #getGoodsInput
* @see #getProduction
*/
public int getMaximumGoodsInput() {
int goodsInput = getMaximumProduction();
if (level > SHOP) {
goodsInput = (goodsInput * 2) / 3; // Factories don't need the extra 3 units.
}
return goodsInput;
}
/**
* Returns the amount of goods beeing used to
* get the current {@link #getProduction production}.
*
* @return The actual amount of goods that is being used
* to support the current production.
* @see #getMaximumGoodsInput
* @see #getProduction
*/
public int getGoodsInput() {
if ((getGoodsInputType() > -1) && (colony.getGoodsCount(getGoodsInputType()) < getMaximumGoodsInput())) { // Not enough goods to do this?
return colony.getGoodsCount(getGoodsInputType());
}
return getMaximumGoodsInput();
}
/**
* Returns the actual production of this building.
*
* @return The amount of goods being produced by this
* <code>Building</code> the current turn.
* The type of goods being produced is given by
* {@link #getGoodsOutputType}.
* @see #getProductionNextTurn
* @see #getMaximumProduction
*/
public int getProduction() {
if (getGoodsOutputType() == -1) {
return 0;
}
int goodsOutput = getMaximumProduction();
if ((getGoodsInputType() > -1) && (colony.getGoodsCount(getGoodsInputType()) < goodsOutput)) { // Not enough goods to do this?
int goodsInput = colony.getGoodsCount(getGoodsInputType());
if (level < FACTORY) {
goodsOutput = goodsInput;
} else {
goodsOutput = (goodsInput * 3) / 2;
}
}
return goodsOutput;
}
/**
* Returns the actual production of this building for next turn.
*
* @return The production of this building the next turn.
* @see #getProduction
*/
public int getProductionNextTurn() {
if (getGoodsOutputType() == -1) {
return 0;
}
int goodsOutput = getMaximumProduction();
if (getGoodsInputType() > -1) {
int goodsInput = colony.getGoodsCount(getGoodsInputType()) + colony.getProductionOf(getGoodsInputType());
if (goodsInput < goodsOutput) {
if (level < FACTORY) {
goodsOutput = goodsInput;
} else {
goodsOutput = (goodsInput * 3) / 2;
}
}
}
return goodsOutput;
}
/**
* Returns the production of the given type of goods.
*
* @param goodsType The type of goods to get the
* production for.
* @return the production og the given goods this turn.
* This method will return the same as
* {@link #getProduction} if the given type of
* goods is the same as {@link #getGoodsOutputType}
* and <code>0</code> otherwise.
*/
public int getProductionOf(int goodsType) {
if (goodsType == getGoodsOutputType()) {
return getProduction();
}
return 0;
}
/**
* Returns the maximum production of this building.
*
* @return The production of this building, with the
* current amount of workers, when there is
* enough "input goods".
*/
public int getMaximumProduction() {
if (getGoodsOutputType() == -1) {
return 0;
}
int goodsOutput = 0;
int goodsOutputType = getGoodsOutputType();
Player player = colony.getOwner();
if (getType() == CHURCH || getType() == TOWN_HALL) {
goodsOutput = 1;
}
Iterator unitIterator = getUnitIterator();
while (unitIterator.hasNext()) {
int productivity = ((Unit) unitIterator.next()).getProducedAmount(goodsOutputType);
if (productivity > 0) {
productivity += colony.getProductionBonus();
if (productivity < 1) productivity = 1;
}
goodsOutput += productivity;
}
goodsOutput *= (type == CHURCH) ? level + 1 : level;
if (goodsOutputType == Goods.BELLS) {
goodsOutput += goodsOutput * colony.getBuilding(Building.PRINTING_PRESS).getLevel();
if (player.hasFather(FoundingFather.THOMAS_JEFFERSON) ||
player.hasFather(FoundingFather.THOMAS_PAINE)) {
goodsOutput = (goodsOutput * (100 + player.getBellsBonus()))/100;
}
}
if (goodsOutputType == Goods.CROSSES && player.hasFather(FoundingFather.WILLIAM_PENN)) {
goodsOutput += goodsOutput/2;
}
return goodsOutput;
}
/**
* Disposes this building. All units that currently has
* this <code>Building as it's location will be disposed</code>.
*/
public void dispose() {
for (int i=0; i<units.size(); i++) {
((Unit) units.get(i)).dispose();
}
super.dispose();
}
/**
* Makes an XML-representation of this object.
*
* @param document The document to use when creating new
* componenets.
* @return The DOM-element ("Document Object Model") made to
* represent this "Building".
*/
public Element toXMLElement(Player player, Document document, boolean showAll, boolean toSavedGame) {
Element buildingElement = document.createElement(getXMLElementTagName());
buildingElement.setAttribute("ID", getID());
buildingElement.setAttribute("colony", colony.getID());
buildingElement.setAttribute("type", Integer.toString(type));
buildingElement.setAttribute("level", Integer.toString(level));
Iterator unitIterator = getUnitIterator();
while (unitIterator.hasNext()) {
buildingElement.appendChild(((FreeColGameObject) unitIterator.next()).toXMLElement(player, document, showAll, toSavedGame));
}
return buildingElement;
}
/**
* Initializes this object from an XML-representation of this object.
* @param buildingElement The DOM-element ("Document Object Model")
* made to represent this "Building".
*/
public void readFromXMLElement(Element buildingElement) {
setID(buildingElement.getAttribute("ID"));
colony = (Colony) getGame().getFreeColGameObject(buildingElement.getAttribute("colony"));
type = Integer.parseInt(buildingElement.getAttribute("type"));
level = Integer.parseInt(buildingElement.getAttribute("level"));
units.clear();
NodeList unitNodeList = buildingElement.getChildNodes();
for (int i=0; i<unitNodeList.getLength(); i++) {
Node node = unitNodeList.item(i);
if (!(node instanceof Element)) {
continue;
}
Element unitElement = (Element) node;
Unit unit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID"));
if (unit != null) {
unit.readFromXMLElement(unitElement);
if (!units.contains(unit)) {
units.add(unit);
}
} else {
unit = new Unit(getGame(), unitElement);
units.add(unit);
}
}
}
/**
* Gets the tag name of the root element representing this object.
* @return the tag name.
*/
public static String getXMLElementTagName() {
return "building";
}
}
| true | true | public void newTurn() {
if ((level == NOT_BUILT) && (type != CHURCH)) return; // Don't do anything if the building does not exist.
if (type == SCHOOLHOUSE) {
Iterator i = getUnitIterator();
while (i.hasNext()) {
Unit teacher = (Unit) i.next();
Unit student = getUnitToTrain(teacher.getType());
if (student != null) {
if (student.getTrainingType() != teacher.getType() && student.getTrainingType() != Unit.FREE_COLONIST) {
student.setTrainingType(teacher.getType());
student.setTurnsOfTraining(0);
}
student.setTurnsOfTraining(student.getTurnsOfTraining() + ((colony.getSoL() == 100) ? 2 : 1));
if (student.getTurnsOfTraining() >= student.getNeededTurnsOfTraining()) {
String oldName = student.getName();
if (student.getType() == Unit.INDENTURED_SERVANT) {
student.setType(Unit.FREE_COLONIST);
} else if (student.getType() == Unit.PETTY_CRIMINAL) {
student.setType(Unit.INDENTURED_SERVANT);
} else {
student.setType(student.getTrainingType());
}
student.setTrainingType(-1);
student.setTurnsOfTraining(0);
addModelMessage(this, "model.unit.unitImproved",
new String[][] {{"%oldName%", oldName},
{"%newName%", student.getName()}},
ModelMessage.UNIT_IMPROVED);
}
} else {
addModelMessage(this, "model.building.noStudent",
new String[][] {{"%teacher%", teacher.getName()},
{"%colony%", colony.getName()}},
ModelMessage.WARNING);
}
}
} else if (getGoodsOutputType() != -1) {
int goodsInput = getGoodsInput();
int goodsOutput = getProduction();
int goodsInputType = getGoodsInputType();
int goodsOutputType = getGoodsOutputType();
if (getGoodsInput() == 0 && getMaximumGoodsInput() > 0) {
addModelMessage(this, "model.building.notEnoughInput",
new String[][] {{"%inputGoods%", Goods.getName(goodsInputType)},
{"%building%", getName()},
{"%colony%", colony.getName()}},
ModelMessage.WARNING);
}
if (goodsOutput <= 0) return;
// Actually produce the goods:
if (goodsOutputType == Goods.CROSSES) {
colony.getOwner().incrementCrosses(goodsOutput);
} else if (goodsOutputType == Goods.BELLS) {
colony.getOwner().incrementBells(goodsOutput);
colony.addBells(goodsOutput);
} else {
colony.removeGoods(goodsInputType, goodsInput);
if (goodsOutputType == Goods.HAMMERS) {
colony.addHammers(goodsOutput);
return;
}
colony.addGoods(goodsOutputType, goodsOutput);
}
}
}
| public void newTurn() {
if ((level == NOT_BUILT) && (type != CHURCH)) return; // Don't do anything if the building does not exist.
if (type == SCHOOLHOUSE) {
Iterator i = getUnitIterator();
while (i.hasNext()) {
Unit teacher = (Unit) i.next();
Unit student = getUnitToTrain(teacher.getType());
if (student != null) {
if (student.getTrainingType() != teacher.getType() && student.getTrainingType() != Unit.FREE_COLONIST) {
student.setTrainingType(teacher.getType());
student.setTurnsOfTraining(0);
}
student.setTurnsOfTraining(student.getTurnsOfTraining() + ((colony.getSoL() == 100) ? 2 : 1));
if (student.getTurnsOfTraining() >= student.getNeededTurnsOfTraining()) {
String oldName = student.getName();
if (student.getType() == Unit.INDENTURED_SERVANT) {
student.setType(Unit.FREE_COLONIST);
} else if (student.getType() == Unit.PETTY_CRIMINAL) {
student.setType(Unit.INDENTURED_SERVANT);
} else {
student.setType(student.getTrainingType());
}
student.setTrainingType(-1);
student.setTurnsOfTraining(0);
addModelMessage(this, "model.unit.unitImproved",
new String[][] {{"%oldName%", oldName},
{"%newName%", student.getName()},
{"%nation%", getOwner().getName()}},
ModelMessage.UNIT_IMPROVED);
}
} else {
addModelMessage(this, "model.building.noStudent",
new String[][] {{"%teacher%", teacher.getName()},
{"%colony%", colony.getName()}},
ModelMessage.WARNING);
}
}
} else if (getGoodsOutputType() != -1) {
int goodsInput = getGoodsInput();
int goodsOutput = getProduction();
int goodsInputType = getGoodsInputType();
int goodsOutputType = getGoodsOutputType();
if (getGoodsInput() == 0 && getMaximumGoodsInput() > 0) {
addModelMessage(this, "model.building.notEnoughInput",
new String[][] {{"%inputGoods%", Goods.getName(goodsInputType)},
{"%building%", getName()},
{"%colony%", colony.getName()}},
ModelMessage.WARNING);
}
if (goodsOutput <= 0) return;
// Actually produce the goods:
if (goodsOutputType == Goods.CROSSES) {
colony.getOwner().incrementCrosses(goodsOutput);
} else if (goodsOutputType == Goods.BELLS) {
colony.getOwner().incrementBells(goodsOutput);
colony.addBells(goodsOutput);
} else {
colony.removeGoods(goodsInputType, goodsInput);
if (goodsOutputType == Goods.HAMMERS) {
colony.addHammers(goodsOutput);
return;
}
colony.addGoods(goodsOutputType, goodsOutput);
}
}
}
|
diff --git a/com/core/util/TimerThread.java b/com/core/util/TimerThread.java
index 6d5c989..ff22da1 100644
--- a/com/core/util/TimerThread.java
+++ b/com/core/util/TimerThread.java
@@ -1,102 +1,105 @@
package com.core.util;
/**
* TimerThread.java
* Copyright (c) 2002 by Dr. Herong Yang
*/
import java.util.*;
import java.text.*;
public class TimerThread extends Thread {
public static final int NORMAL_CLOCK = 1;
public static final int COUNT_DOWN = 2;
public static final int STOP_WATCH = 3;
private int type; // type of clock
private int c_millisecond, c_second, c_minute, c_hour;
private static int remaining_seconds = 2;
private static int clock_interval = 100; // in milliseconds < 1000
public TimerThread(int t) {
type = t;
if (type==NORMAL_CLOCK) {
GregorianCalendar c = new GregorianCalendar();
c_hour = c.get(Calendar.HOUR_OF_DAY);
c_minute = c.get(Calendar.MINUTE);
c_second = c.get(Calendar.SECOND);
c_millisecond = c.get(Calendar.MILLISECOND);
} else if (type==COUNT_DOWN) {
c_hour = remaining_seconds/60/60;
c_minute = (remaining_seconds%(60*60))/60;
c_second = remaining_seconds%60;
c_millisecond = 0;
} else {
c_hour = 0;
c_minute = 0;
c_second = 0;
c_millisecond = 0;
}
}
public void setRemainingMinutes(int mins) {
remaining_seconds = mins * 60;
c_minute = mins%60;
}
public void setRemainingSeconds(int secs) {
remaining_seconds = secs;
c_minute = secs/60;
c_second = secs % 60;
}
public void run() {
while (!isInterrupted()) {
try {
sleep(clock_interval);
} catch (InterruptedException e) {
break; // the main thread wants this thread to end
}
if (type==NORMAL_CLOCK || type==STOP_WATCH)
c_millisecond +=clock_interval;
else c_millisecond -= clock_interval;
if (c_millisecond>=1000) {
c_second += c_millisecond/1000;
c_millisecond = c_millisecond%1000;
}
if (c_second>=60) {
c_minute += c_second/60;
c_second = c_second%60;
}
if (c_minute>=60) {
c_hour += c_minute/60;
c_minute = c_minute%60;
}
if (c_millisecond<0) {
c_second--;
c_millisecond += 1000;
}
if (c_second<0) {
c_minute--;
c_second += 60;
}
if (c_minute<0) {
c_hour--;
c_minute += 60;
}
if (c_hour<0) {
c_hour = 0;
+ // fix 59:59
+ c_minute = 0;
+ c_second = 0;
break; // end this thread
}
}
}
public String getClock() {
// returning the clock as a string of HH:mm:ss format
GregorianCalendar c = new GregorianCalendar();
c.set(Calendar.HOUR_OF_DAY,c_hour);
c.set(Calendar.MINUTE,c_minute);
c.set(Calendar.SECOND,c_second);
c.set(Calendar.MILLISECOND,c_millisecond);
//SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss");
SimpleDateFormat f = new SimpleDateFormat("mm:ss");
return f.format(c.getTime());
}
}
| true | true | public void run() {
while (!isInterrupted()) {
try {
sleep(clock_interval);
} catch (InterruptedException e) {
break; // the main thread wants this thread to end
}
if (type==NORMAL_CLOCK || type==STOP_WATCH)
c_millisecond +=clock_interval;
else c_millisecond -= clock_interval;
if (c_millisecond>=1000) {
c_second += c_millisecond/1000;
c_millisecond = c_millisecond%1000;
}
if (c_second>=60) {
c_minute += c_second/60;
c_second = c_second%60;
}
if (c_minute>=60) {
c_hour += c_minute/60;
c_minute = c_minute%60;
}
if (c_millisecond<0) {
c_second--;
c_millisecond += 1000;
}
if (c_second<0) {
c_minute--;
c_second += 60;
}
if (c_minute<0) {
c_hour--;
c_minute += 60;
}
if (c_hour<0) {
c_hour = 0;
break; // end this thread
}
}
}
| public void run() {
while (!isInterrupted()) {
try {
sleep(clock_interval);
} catch (InterruptedException e) {
break; // the main thread wants this thread to end
}
if (type==NORMAL_CLOCK || type==STOP_WATCH)
c_millisecond +=clock_interval;
else c_millisecond -= clock_interval;
if (c_millisecond>=1000) {
c_second += c_millisecond/1000;
c_millisecond = c_millisecond%1000;
}
if (c_second>=60) {
c_minute += c_second/60;
c_second = c_second%60;
}
if (c_minute>=60) {
c_hour += c_minute/60;
c_minute = c_minute%60;
}
if (c_millisecond<0) {
c_second--;
c_millisecond += 1000;
}
if (c_second<0) {
c_minute--;
c_second += 60;
}
if (c_minute<0) {
c_hour--;
c_minute += 60;
}
if (c_hour<0) {
c_hour = 0;
// fix 59:59
c_minute = 0;
c_second = 0;
break; // end this thread
}
}
}
|
diff --git a/src/com/android/browser/provider/BrowserProvider2.java b/src/com/android/browser/provider/BrowserProvider2.java
index 1b90cb3d..358ee2d9 100644
--- a/src/com/android/browser/provider/BrowserProvider2.java
+++ b/src/com/android/browser/provider/BrowserProvider2.java
@@ -1,1599 +1,1604 @@
/*
* Copyright (C) 2010 he 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.browser.provider;
import com.android.browser.BookmarkUtils;
import com.android.browser.BrowserBookmarksPage;
import com.android.browser.R;
import com.android.common.content.SyncStateContentProviderHelper;
import android.accounts.Account;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.AbstractCursor;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.provider.Browser;
import android.provider.Browser.BookmarkColumns;
import android.provider.BrowserContract;
import android.provider.BrowserContract.Accounts;
import android.provider.BrowserContract.Bookmarks;
import android.provider.BrowserContract.ChromeSyncColumns;
import android.provider.BrowserContract.Combined;
import android.provider.BrowserContract.History;
import android.provider.BrowserContract.Images;
import android.provider.BrowserContract.Searches;
import android.provider.BrowserContract.Settings;
import android.provider.BrowserContract.SyncState;
import android.provider.ContactsContract.RawContacts;
import android.provider.SyncStateContract;
import android.text.TextUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
public class BrowserProvider2 extends SQLiteContentProvider {
static final String LEGACY_AUTHORITY = "browser";
static final Uri LEGACY_AUTHORITY_URI = new Uri.Builder().authority(LEGACY_AUTHORITY).build();
static final String TABLE_BOOKMARKS = "bookmarks";
static final String TABLE_HISTORY = "history";
static final String TABLE_IMAGES = "images";
static final String TABLE_SEARCHES = "searches";
static final String TABLE_SYNC_STATE = "syncstate";
static final String TABLE_SETTINGS = "settings";
static final String TABLE_BOOKMARKS_JOIN_IMAGES = "bookmarks LEFT OUTER JOIN images " +
"ON bookmarks.url = images." + Images.URL;
static final String TABLE_HISTORY_JOIN_IMAGES = "history LEFT OUTER JOIN images " +
"ON history.url = images." + Images.URL;
static final String FORMAT_COMBINED_JOIN_SUBQUERY_JOIN_IMAGES =
"history LEFT OUTER JOIN (%s) bookmarks " +
"ON history.url = bookmarks.url LEFT OUTER JOIN images " +
"ON history.url = images.url_key";
static final String DEFAULT_SORT_HISTORY = History.DATE_LAST_VISITED + " DESC";
private static final String[] SUGGEST_PROJECTION = new String[] {
Bookmarks._ID,
Bookmarks.URL,
Bookmarks.TITLE};
private static final String SUGGEST_SELECTION =
"url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ?"
+ " OR title LIKE ?";
private static final String IMAGE_PRUNE =
"url_key NOT IN (SELECT url FROM bookmarks " +
"WHERE url IS NOT NULL AND deleted == 0) AND url_key NOT IN " +
"(SELECT url FROM history WHERE url IS NOT NULL)";
static final int BOOKMARKS = 1000;
static final int BOOKMARKS_ID = 1001;
static final int BOOKMARKS_FOLDER = 1002;
static final int BOOKMARKS_FOLDER_ID = 1003;
static final int BOOKMARKS_SUGGESTIONS = 1004;
static final int HISTORY = 2000;
static final int HISTORY_ID = 2001;
static final int SEARCHES = 3000;
static final int SEARCHES_ID = 3001;
static final int SYNCSTATE = 4000;
static final int SYNCSTATE_ID = 4001;
static final int IMAGES = 5000;
static final int COMBINED = 6000;
static final int COMBINED_ID = 6001;
static final int ACCOUNTS = 7000;
static final int SETTINGS = 8000;
static final int LEGACY = 9000;
static final int LEGACY_ID = 9001;
public static final long FIXED_ID_ROOT = 1;
// Default sort order for unsync'd bookmarks
static final String DEFAULT_BOOKMARKS_SORT_ORDER =
Bookmarks.IS_FOLDER + " DESC, position ASC, _id ASC";
// Default sort order for sync'd bookmarks
static final String DEFAULT_BOOKMARKS_SORT_ORDER_SYNC = "position ASC, _id ASC";
static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
static final HashMap<String, String> ACCOUNTS_PROJECTION_MAP = new HashMap<String, String>();
static final HashMap<String, String> BOOKMARKS_PROJECTION_MAP = new HashMap<String, String>();
static final HashMap<String, String> OTHER_BOOKMARKS_PROJECTION_MAP =
new HashMap<String, String>();
static final HashMap<String, String> HISTORY_PROJECTION_MAP = new HashMap<String, String>();
static final HashMap<String, String> SYNC_STATE_PROJECTION_MAP = new HashMap<String, String>();
static final HashMap<String, String> IMAGES_PROJECTION_MAP = new HashMap<String, String>();
static final HashMap<String, String> COMBINED_HISTORY_PROJECTION_MAP = new HashMap<String, String>();
static final HashMap<String, String> COMBINED_BOOKMARK_PROJECTION_MAP = new HashMap<String, String>();
static final HashMap<String, String> SEARCHES_PROJECTION_MAP = new HashMap<String, String>();
static final HashMap<String, String> SETTINGS_PROJECTION_MAP = new HashMap<String, String>();
static {
final UriMatcher matcher = URI_MATCHER;
final String authority = BrowserContract.AUTHORITY;
matcher.addURI(authority, "accounts", ACCOUNTS);
matcher.addURI(authority, "bookmarks", BOOKMARKS);
matcher.addURI(authority, "bookmarks/#", BOOKMARKS_ID);
matcher.addURI(authority, "bookmarks/folder", BOOKMARKS_FOLDER);
matcher.addURI(authority, "bookmarks/folder/#", BOOKMARKS_FOLDER_ID);
matcher.addURI(authority,
SearchManager.SUGGEST_URI_PATH_QUERY,
BOOKMARKS_SUGGESTIONS);
matcher.addURI(authority,
"bookmarks/" + SearchManager.SUGGEST_URI_PATH_QUERY,
BOOKMARKS_SUGGESTIONS);
matcher.addURI(authority, "history", HISTORY);
matcher.addURI(authority, "history/#", HISTORY_ID);
matcher.addURI(authority, "searches", SEARCHES);
matcher.addURI(authority, "searches/#", SEARCHES_ID);
matcher.addURI(authority, "syncstate", SYNCSTATE);
matcher.addURI(authority, "syncstate/#", SYNCSTATE_ID);
matcher.addURI(authority, "images", IMAGES);
matcher.addURI(authority, "combined", COMBINED);
matcher.addURI(authority, "combined/#", COMBINED_ID);
matcher.addURI(authority, "settings", SETTINGS);
// Legacy
matcher.addURI(LEGACY_AUTHORITY, "searches", SEARCHES);
matcher.addURI(LEGACY_AUTHORITY, "searches/#", SEARCHES_ID);
matcher.addURI(LEGACY_AUTHORITY, "bookmarks", LEGACY);
matcher.addURI(LEGACY_AUTHORITY, "bookmarks/#", LEGACY_ID);
matcher.addURI(LEGACY_AUTHORITY,
SearchManager.SUGGEST_URI_PATH_QUERY,
BOOKMARKS_SUGGESTIONS);
matcher.addURI(LEGACY_AUTHORITY,
"bookmarks/" + SearchManager.SUGGEST_URI_PATH_QUERY,
BOOKMARKS_SUGGESTIONS);
// Projection maps
HashMap<String, String> map;
// Accounts
map = ACCOUNTS_PROJECTION_MAP;
map.put(Accounts.ACCOUNT_TYPE, Accounts.ACCOUNT_TYPE);
map.put(Accounts.ACCOUNT_NAME, Accounts.ACCOUNT_NAME);
// Bookmarks
map = BOOKMARKS_PROJECTION_MAP;
map.put(Bookmarks._ID, qualifyColumn(TABLE_BOOKMARKS, Bookmarks._ID));
map.put(Bookmarks.TITLE, Bookmarks.TITLE);
map.put(Bookmarks.URL, Bookmarks.URL);
map.put(Bookmarks.FAVICON, Bookmarks.FAVICON);
map.put(Bookmarks.THUMBNAIL, Bookmarks.THUMBNAIL);
map.put(Bookmarks.TOUCH_ICON, Bookmarks.TOUCH_ICON);
map.put(Bookmarks.IS_FOLDER, Bookmarks.IS_FOLDER);
map.put(Bookmarks.PARENT, Bookmarks.PARENT);
map.put(Bookmarks.POSITION, Bookmarks.POSITION);
map.put(Bookmarks.INSERT_AFTER, Bookmarks.INSERT_AFTER);
map.put(Bookmarks.IS_DELETED, Bookmarks.IS_DELETED);
map.put(Bookmarks.ACCOUNT_NAME, Bookmarks.ACCOUNT_NAME);
map.put(Bookmarks.ACCOUNT_TYPE, Bookmarks.ACCOUNT_TYPE);
map.put(Bookmarks.SOURCE_ID, Bookmarks.SOURCE_ID);
map.put(Bookmarks.VERSION, Bookmarks.VERSION);
map.put(Bookmarks.DATE_CREATED, Bookmarks.DATE_CREATED);
map.put(Bookmarks.DATE_MODIFIED, Bookmarks.DATE_MODIFIED);
map.put(Bookmarks.DIRTY, Bookmarks.DIRTY);
map.put(Bookmarks.SYNC1, Bookmarks.SYNC1);
map.put(Bookmarks.SYNC2, Bookmarks.SYNC2);
map.put(Bookmarks.SYNC3, Bookmarks.SYNC3);
map.put(Bookmarks.SYNC4, Bookmarks.SYNC4);
map.put(Bookmarks.SYNC5, Bookmarks.SYNC5);
map.put(Bookmarks.PARENT_SOURCE_ID, "(SELECT " + Bookmarks.SOURCE_ID +
" FROM " + TABLE_BOOKMARKS + " A WHERE " +
"A." + Bookmarks._ID + "=" + TABLE_BOOKMARKS + "." + Bookmarks.PARENT +
") AS " + Bookmarks.PARENT_SOURCE_ID);
map.put(Bookmarks.INSERT_AFTER_SOURCE_ID, "(SELECT " + Bookmarks.SOURCE_ID +
" FROM " + TABLE_BOOKMARKS + " A WHERE " +
"A." + Bookmarks._ID + "=" + TABLE_BOOKMARKS + "." + Bookmarks.INSERT_AFTER +
") AS " + Bookmarks.INSERT_AFTER_SOURCE_ID);
// Other bookmarks
OTHER_BOOKMARKS_PROJECTION_MAP.putAll(BOOKMARKS_PROJECTION_MAP);
OTHER_BOOKMARKS_PROJECTION_MAP.put(Bookmarks.POSITION,
Long.toString(Long.MAX_VALUE) + " AS " + Bookmarks.POSITION);
// History
map = HISTORY_PROJECTION_MAP;
map.put(History._ID, qualifyColumn(TABLE_HISTORY, History._ID));
map.put(History.TITLE, History.TITLE);
map.put(History.URL, History.URL);
map.put(History.FAVICON, History.FAVICON);
map.put(History.THUMBNAIL, History.THUMBNAIL);
map.put(History.TOUCH_ICON, History.TOUCH_ICON);
map.put(History.DATE_CREATED, History.DATE_CREATED);
map.put(History.DATE_LAST_VISITED, History.DATE_LAST_VISITED);
map.put(History.VISITS, History.VISITS);
map.put(History.USER_ENTERED, History.USER_ENTERED);
// Sync state
map = SYNC_STATE_PROJECTION_MAP;
map.put(SyncState._ID, SyncState._ID);
map.put(SyncState.ACCOUNT_NAME, SyncState.ACCOUNT_NAME);
map.put(SyncState.ACCOUNT_TYPE, SyncState.ACCOUNT_TYPE);
map.put(SyncState.DATA, SyncState.DATA);
// Images
map = IMAGES_PROJECTION_MAP;
map.put(Images.URL, Images.URL);
map.put(Images.FAVICON, Images.FAVICON);
map.put(Images.THUMBNAIL, Images.THUMBNAIL);
map.put(Images.TOUCH_ICON, Images.TOUCH_ICON);
// Combined history half
map = COMBINED_HISTORY_PROJECTION_MAP;
map.put(Combined._ID, bookmarkOrHistoryColumn(Combined._ID));
map.put(Combined.TITLE, bookmarkOrHistoryColumn(Combined.TITLE));
map.put(Combined.URL, qualifyColumn(TABLE_HISTORY, Combined.URL));
map.put(Combined.DATE_CREATED, qualifyColumn(TABLE_HISTORY, Combined.DATE_CREATED));
map.put(Combined.DATE_LAST_VISITED, Combined.DATE_LAST_VISITED);
map.put(Combined.IS_BOOKMARK, "CASE WHEN " +
TABLE_BOOKMARKS + "." + Bookmarks._ID +
" IS NOT NULL THEN 1 ELSE 0 END AS " + Combined.IS_BOOKMARK);
map.put(Combined.VISITS, Combined.VISITS);
map.put(Combined.FAVICON, Combined.FAVICON);
map.put(Combined.THUMBNAIL, Combined.THUMBNAIL);
map.put(Combined.TOUCH_ICON, Combined.TOUCH_ICON);
map.put(Combined.USER_ENTERED, "NULL AS " + Combined.USER_ENTERED);
// Combined bookmark half
map = COMBINED_BOOKMARK_PROJECTION_MAP;
map.put(Combined._ID, Combined._ID);
map.put(Combined.TITLE, Combined.TITLE);
map.put(Combined.URL, Combined.URL);
map.put(Combined.DATE_CREATED, Combined.DATE_CREATED);
map.put(Combined.DATE_LAST_VISITED, "NULL AS " + Combined.DATE_LAST_VISITED);
map.put(Combined.IS_BOOKMARK, "1 AS " + Combined.IS_BOOKMARK);
map.put(Combined.VISITS, "0 AS " + Combined.VISITS);
map.put(Combined.FAVICON, Combined.FAVICON);
map.put(Combined.THUMBNAIL, Combined.THUMBNAIL);
map.put(Combined.TOUCH_ICON, Combined.TOUCH_ICON);
map.put(Combined.USER_ENTERED, "NULL AS " + Combined.USER_ENTERED);
// Searches
map = SEARCHES_PROJECTION_MAP;
map.put(Searches._ID, Searches._ID);
map.put(Searches.SEARCH, Searches.SEARCH);
map.put(Searches.DATE, Searches.DATE);
// Settings
map = SETTINGS_PROJECTION_MAP;
map.put(Settings.KEY, Settings.KEY);
map.put(Settings.VALUE, Settings.VALUE);
}
static final String bookmarkOrHistoryColumn(String column) {
return "CASE WHEN bookmarks." + column + " IS NOT NULL THEN " +
"bookmarks." + column + " ELSE history." + column + " END AS " + column;
}
static final String qualifyColumn(String table, String column) {
return table + "." + column + " AS " + column;
}
DatabaseHelper mOpenHelper;
SyncStateContentProviderHelper mSyncHelper = new SyncStateContentProviderHelper();
final class DatabaseHelper extends SQLiteOpenHelper {
static final String DATABASE_NAME = "browser2.db";
static final int DATABASE_VERSION = 26;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_BOOKMARKS + "(" +
Bookmarks._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
Bookmarks.TITLE + " TEXT," +
Bookmarks.URL + " TEXT," +
Bookmarks.IS_FOLDER + " INTEGER NOT NULL DEFAULT 0," +
Bookmarks.PARENT + " INTEGER," +
Bookmarks.POSITION + " INTEGER NOT NULL," +
Bookmarks.INSERT_AFTER + " INTEGER," +
Bookmarks.IS_DELETED + " INTEGER NOT NULL DEFAULT 0," +
Bookmarks.ACCOUNT_NAME + " TEXT," +
Bookmarks.ACCOUNT_TYPE + " TEXT," +
Bookmarks.SOURCE_ID + " TEXT," +
Bookmarks.VERSION + " INTEGER NOT NULL DEFAULT 1," +
Bookmarks.DATE_CREATED + " INTEGER," +
Bookmarks.DATE_MODIFIED + " INTEGER," +
Bookmarks.DIRTY + " INTEGER NOT NULL DEFAULT 0," +
Bookmarks.SYNC1 + " TEXT," +
Bookmarks.SYNC2 + " TEXT," +
Bookmarks.SYNC3 + " TEXT," +
Bookmarks.SYNC4 + " TEXT," +
Bookmarks.SYNC5 + " TEXT" +
");");
// TODO indices
db.execSQL("CREATE TABLE " + TABLE_HISTORY + "(" +
History._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
History.TITLE + " TEXT," +
History.URL + " TEXT NOT NULL," +
History.DATE_CREATED + " INTEGER," +
History.DATE_LAST_VISITED + " INTEGER," +
History.VISITS + " INTEGER NOT NULL DEFAULT 0," +
History.USER_ENTERED + " INTEGER" +
");");
db.execSQL("CREATE TABLE " + TABLE_IMAGES + " (" +
Images.URL + " TEXT UNIQUE NOT NULL," +
Images.FAVICON + " BLOB," +
Images.THUMBNAIL + " BLOB," +
Images.TOUCH_ICON + " BLOB" +
");");
db.execSQL("CREATE INDEX imagesUrlIndex ON " + TABLE_IMAGES +
"(" + Images.URL + ")");
db.execSQL("CREATE TABLE " + TABLE_SEARCHES + " (" +
Searches._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
Searches.SEARCH + " TEXT," +
Searches.DATE + " LONG" +
");");
db.execSQL("CREATE TABLE " + TABLE_SETTINGS + " (" +
Settings.KEY + " TEXT PRIMARY KEY," +
Settings.VALUE + " TEXT NOT NULL" +
");");
mSyncHelper.createDatabase(db);
createDefaultBookmarks(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO write upgrade logic
db.execSQL("DROP VIEW IF EXISTS combined");
if (oldVersion < 25) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOKMARKS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SEARCHES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_IMAGES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTINGS);
mSyncHelper.onAccountsChanged(db, new Account[] {}); // remove all sync info
onCreate(db);
}
}
@Override
public void onOpen(SQLiteDatabase db) {
mSyncHelper.onDatabaseOpened(db);
}
private void createDefaultBookmarks(SQLiteDatabase db) {
ContentValues values = new ContentValues();
// TODO figure out how to deal with localization for the defaults
// Bookmarks folder
values.put(Bookmarks._ID, FIXED_ID_ROOT);
values.put(ChromeSyncColumns.SERVER_UNIQUE, ChromeSyncColumns.FOLDER_NAME_BOOKMARKS);
values.put(Bookmarks.TITLE, "Bookmarks");
values.putNull(Bookmarks.PARENT);
values.put(Bookmarks.POSITION, 0);
values.put(Bookmarks.IS_FOLDER, true);
values.put(Bookmarks.DIRTY, true);
db.insertOrThrow(TABLE_BOOKMARKS, null, values);
addDefaultBookmarks(db, FIXED_ID_ROOT);
}
private void addDefaultBookmarks(SQLiteDatabase db, long parentId) {
Resources res = getContext().getResources();
final CharSequence[] bookmarks = res.getTextArray(
R.array.bookmarks);
int size = bookmarks.length;
TypedArray preloads = res.obtainTypedArray(R.array.bookmark_preloads);
try {
String parent = Long.toString(parentId);
String now = Long.toString(System.currentTimeMillis());
for (int i = 0; i < size; i = i + 2) {
CharSequence bookmarkDestination = replaceSystemPropertyInString(getContext(),
bookmarks[i + 1]);
db.execSQL("INSERT INTO bookmarks (" +
Bookmarks.TITLE + ", " +
Bookmarks.URL + ", " +
Bookmarks.IS_FOLDER + "," +
Bookmarks.PARENT + "," +
Bookmarks.POSITION + "," +
Bookmarks.DATE_CREATED +
") VALUES (" +
"'" + bookmarks[i] + "', " +
"'" + bookmarkDestination + "', " +
"0," +
parent + "," +
Integer.toString(i) + "," +
now +
");");
int faviconId = preloads.getResourceId(i, 0);
int thumbId = preloads.getResourceId(i + 1, 0);
byte[] thumb = null, favicon = null;
try {
thumb = readRaw(res, thumbId);
} catch (IOException e) {
}
try {
favicon = readRaw(res, faviconId);
} catch (IOException e) {
}
if (thumb != null || favicon != null) {
ContentValues imageValues = new ContentValues();
imageValues.put(Images.URL, bookmarkDestination.toString());
if (favicon != null) {
imageValues.put(Images.FAVICON, favicon);
}
if (thumb != null) {
imageValues.put(Images.THUMBNAIL, thumb);
}
db.insert(TABLE_IMAGES, Images.FAVICON, imageValues);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
}
}
private byte[] readRaw(Resources res, int id) throws IOException {
InputStream is = res.openRawResource(id);
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
int read;
while ((read = is.read(buf)) > 0) {
bos.write(buf, 0, read);
}
bos.flush();
return bos.toByteArray();
} finally {
is.close();
}
}
// XXX: This is a major hack to remove our dependency on gsf constants and
// its content provider. http://b/issue?id=2425179
private String getClientId(ContentResolver cr) {
String ret = "android-google";
Cursor c = null;
try {
c = cr.query(Uri.parse("content://com.google.settings/partner"),
new String[] { "value" }, "name='client_id'", null, null);
if (c != null && c.moveToNext()) {
ret = c.getString(0);
}
} catch (RuntimeException ex) {
// fall through to return the default
} finally {
if (c != null) {
c.close();
}
}
return ret;
}
private CharSequence replaceSystemPropertyInString(Context context, CharSequence srcString) {
StringBuffer sb = new StringBuffer();
int lastCharLoc = 0;
final String client_id = getClientId(context.getContentResolver());
for (int i = 0; i < srcString.length(); ++i) {
char c = srcString.charAt(i);
if (c == '{') {
sb.append(srcString.subSequence(lastCharLoc, i));
lastCharLoc = i;
inner:
for (int j = i; j < srcString.length(); ++j) {
char k = srcString.charAt(j);
if (k == '}') {
String propertyKeyValue = srcString.subSequence(i + 1, j).toString();
if (propertyKeyValue.equals("CLIENT_ID")) {
sb.append(client_id);
} else {
sb.append("unknown");
}
lastCharLoc = j + 1;
i = j;
break inner;
}
}
}
}
if (srcString.length() - lastCharLoc > 0) {
// Put on the tail, if there is one
sb.append(srcString.subSequence(lastCharLoc, srcString.length()));
}
return sb;
}
}
@Override
public SQLiteOpenHelper getDatabaseHelper(Context context) {
synchronized (this) {
if (mOpenHelper == null) {
mOpenHelper = new DatabaseHelper(context);
}
return mOpenHelper;
}
}
@Override
public boolean isCallerSyncAdapter(Uri uri) {
return uri.getBooleanQueryParameter(BrowserContract.CALLER_IS_SYNCADAPTER, false);
}
@Override
public void notifyChange(boolean callerIsSyncAdapter) {
ContentResolver resolver = getContext().getContentResolver();
resolver.notifyChange(BrowserContract.AUTHORITY_URI, null, !callerIsSyncAdapter);
resolver.notifyChange(LEGACY_AUTHORITY_URI, null, !callerIsSyncAdapter);
}
@Override
public String getType(Uri uri) {
final int match = URI_MATCHER.match(uri);
switch (match) {
case LEGACY:
case BOOKMARKS:
return Bookmarks.CONTENT_TYPE;
case LEGACY_ID:
case BOOKMARKS_ID:
return Bookmarks.CONTENT_ITEM_TYPE;
case HISTORY:
return History.CONTENT_TYPE;
case HISTORY_ID:
return History.CONTENT_ITEM_TYPE;
case SEARCHES:
return Searches.CONTENT_TYPE;
case SEARCHES_ID:
return Searches.CONTENT_ITEM_TYPE;
}
return null;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final int match = URI_MATCHER.match(uri);
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String limit = uri.getQueryParameter(BrowserContract.PARAM_LIMIT);
switch (match) {
case ACCOUNTS: {
qb.setTables(TABLE_BOOKMARKS);
qb.setProjectionMap(ACCOUNTS_PROJECTION_MAP);
qb.setDistinct(true);
qb.appendWhere(Bookmarks.ACCOUNT_NAME + " IS NOT NULL");
break;
}
case BOOKMARKS_FOLDER_ID:
case BOOKMARKS_ID:
case BOOKMARKS: {
// Only show deleted bookmarks if requested to do so
if (!uri.getBooleanQueryParameter(Bookmarks.QUERY_PARAMETER_SHOW_DELETED, false)) {
selection = DatabaseUtils.concatenateWhere(
Bookmarks.IS_DELETED + "=0", selection);
}
if (match == BOOKMARKS_ID) {
// Tack on the ID of the specific bookmark requested
selection = DatabaseUtils.concatenateWhere(selection,
TABLE_BOOKMARKS + "." + Bookmarks._ID + "=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
} else if (match == BOOKMARKS_FOLDER_ID) {
// Tack on the ID of the specific folder requested
selection = DatabaseUtils.concatenateWhere(selection,
TABLE_BOOKMARKS + "." + Bookmarks.PARENT + "=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
}
// Look for account info
String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE);
String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME);
- if (!TextUtils.isEmpty(accountType) && !TextUtils.isEmpty(accountName)) {
- selection = DatabaseUtils.concatenateWhere(selection,
- Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=? ");
- selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
- new String[] { accountType, accountName });
- } else {
- selection = DatabaseUtils.concatenateWhere(selection,
- Bookmarks.ACCOUNT_TYPE + " IS NULL AND " +
- Bookmarks.ACCOUNT_NAME + " IS NULL ");
+ // Only add it if it isn't already in the selection
+ if (selection == null ||
+ (!selection.contains(Bookmarks.ACCOUNT_NAME)
+ && !selection.contains(Bookmarks.ACCOUNT_TYPE))) {
+ if (!TextUtils.isEmpty(accountType) && !TextUtils.isEmpty(accountName)) {
+ selection = DatabaseUtils.concatenateWhere(selection,
+ Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=? ");
+ selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
+ new String[] { accountType, accountName });
+ } else {
+ selection = DatabaseUtils.concatenateWhere(selection,
+ Bookmarks.ACCOUNT_TYPE + " IS NULL AND " +
+ Bookmarks.ACCOUNT_NAME + " IS NULL ");
+ }
}
// Set a default sort order if one isn't specified
if (TextUtils.isEmpty(sortOrder)) {
if (!TextUtils.isEmpty(accountType)
&& !TextUtils.isEmpty(accountName)) {
sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER_SYNC;
} else {
sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER;
}
}
qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP);
qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES);
break;
}
case BOOKMARKS_FOLDER: {
// Look for an account
boolean useAccount = false;
String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE);
String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME);
if (!TextUtils.isEmpty(accountType) && !TextUtils.isEmpty(accountName)) {
useAccount = true;
}
qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES);
String[] args;
String query;
// Set a default sort order if one isn't specified
if (TextUtils.isEmpty(sortOrder)) {
if (useAccount) {
sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER_SYNC;
} else {
sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER;
}
}
if (!useAccount) {
qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP);
String where = Bookmarks.PARENT + "=? AND " + Bookmarks.IS_DELETED + "=0";
where = DatabaseUtils.concatenateWhere(where, selection);
args = new String[] { Long.toString(FIXED_ID_ROOT) };
if (selectionArgs != null) {
args = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
}
query = qb.buildQuery(projection, where, null, null, sortOrder, null);
} else {
qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP);
String where = Bookmarks.ACCOUNT_TYPE + "=? AND " +
Bookmarks.ACCOUNT_NAME + "=? " +
"AND parent = " +
"(SELECT _id FROM " + TABLE_BOOKMARKS + " WHERE " +
ChromeSyncColumns.SERVER_UNIQUE + "=" +
"'" + ChromeSyncColumns.FOLDER_NAME_BOOKMARKS_BAR + "' " +
"AND account_type = ? AND account_name = ?) " +
"AND " + Bookmarks.IS_DELETED + "=0";
where = DatabaseUtils.concatenateWhere(where, selection);
String bookmarksBarQuery = qb.buildQuery(projection,
where, null, null, null, null);
args = new String[] {accountType, accountName,
accountType, accountName};
if (selectionArgs != null) {
args = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
}
where = Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=?" +
" AND " + ChromeSyncColumns.SERVER_UNIQUE + "=?";
where = DatabaseUtils.concatenateWhere(where, selection);
qb.setProjectionMap(OTHER_BOOKMARKS_PROJECTION_MAP);
String otherBookmarksQuery = qb.buildQuery(projection,
where, null, null, null, null);
query = qb.buildUnionQuery(
new String[] { bookmarksBarQuery, otherBookmarksQuery },
sortOrder, limit);
args = DatabaseUtils.appendSelectionArgs(args, new String[] {
accountType, accountName, ChromeSyncColumns.FOLDER_NAME_OTHER_BOOKMARKS,
});
if (selectionArgs != null) {
args = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
}
}
Cursor cursor = db.rawQuery(query, args);
if (cursor != null) {
cursor.setNotificationUri(getContext().getContentResolver(),
BrowserContract.AUTHORITY_URI);
}
return cursor;
}
case BOOKMARKS_SUGGESTIONS: {
return doSuggestQuery(selection, selectionArgs, limit);
}
case HISTORY_ID: {
selection = DatabaseUtils.concatenateWhere(selection, TABLE_HISTORY + "._id=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case HISTORY: {
filterSearchClient(selectionArgs);
if (sortOrder == null) {
sortOrder = DEFAULT_SORT_HISTORY;
}
qb.setProjectionMap(HISTORY_PROJECTION_MAP);
qb.setTables(TABLE_HISTORY_JOIN_IMAGES);
break;
}
case SEARCHES_ID: {
selection = DatabaseUtils.concatenateWhere(selection, TABLE_SEARCHES + "._id=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case SEARCHES: {
qb.setTables(TABLE_SEARCHES);
qb.setProjectionMap(SEARCHES_PROJECTION_MAP);
break;
}
case SYNCSTATE: {
return mSyncHelper.query(db, projection, selection, selectionArgs, sortOrder);
}
case SYNCSTATE_ID: {
selection = appendAccountToSelection(uri, selection);
String selectionWithId =
(SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ")
+ (selection == null ? "" : " AND (" + selection + ")");
return mSyncHelper.query(db, projection, selectionWithId, selectionArgs, sortOrder);
}
case IMAGES: {
qb.setTables(TABLE_IMAGES);
qb.setProjectionMap(IMAGES_PROJECTION_MAP);
break;
}
case LEGACY_ID:
case COMBINED_ID: {
selection = DatabaseUtils.concatenateWhere(
selection, Combined._ID + " = CAST(? AS INTEGER)");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case LEGACY:
case COMBINED: {
if ((match == LEGACY || match == LEGACY_ID)
&& projection == null) {
projection = Browser.HISTORY_PROJECTION;
}
String[] args = createCombinedQuery(uri, projection, qb);
if (selectionArgs == null) {
selectionArgs = args;
} else {
selectionArgs = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
}
break;
}
case SETTINGS: {
qb.setTables(TABLE_SETTINGS);
qb.setProjectionMap(SETTINGS_PROJECTION_MAP);
break;
}
default: {
throw new UnsupportedOperationException("Unknown URL " + uri.toString());
}
}
Cursor cursor = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder,
limit);
cursor.setNotificationUri(getContext().getContentResolver(), BrowserContract.AUTHORITY_URI);
return cursor;
}
private Cursor doSuggestQuery(String selection, String[] selectionArgs, String limit) {
if (selectionArgs[0] == null) {
return null;
} else {
String like = selectionArgs[0] + "%";
if (selectionArgs[0].startsWith("http")
|| selectionArgs[0].startsWith("file")) {
selectionArgs[0] = like;
} else {
selectionArgs = new String[5];
selectionArgs[0] = "http://" + like;
selectionArgs[1] = "http://www." + like;
selectionArgs[2] = "https://" + like;
selectionArgs[3] = "https://www." + like;
// To match against titles.
selectionArgs[4] = like;
selection = SUGGEST_SELECTION;
}
}
selection = DatabaseUtils.concatenateWhere(selection,
Bookmarks.IS_DELETED + "=0 AND " + Bookmarks.IS_FOLDER + "=0");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
String accountType = prefs.getString(BrowserBookmarksPage.PREF_ACCOUNT_TYPE, null);
String accountName = prefs.getString(BrowserBookmarksPage.PREF_ACCOUNT_NAME, null);
if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
selection = DatabaseUtils.concatenateWhere(selection,
Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=? ");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { accountType, accountName });
} else {
selection = DatabaseUtils.concatenateWhere(selection,
Bookmarks.ACCOUNT_TYPE + " IS NULL AND " +
Bookmarks.ACCOUNT_NAME + " IS NULL ");
}
Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_BOOKMARKS,
SUGGEST_PROJECTION, selection, selectionArgs, null, null,
DEFAULT_BOOKMARKS_SORT_ORDER, null);
return new SuggestionsCursor(c);
}
private String[] createCombinedQuery(
Uri uri, String[] projection, SQLiteQueryBuilder qb) {
String[] args = null;
// Look for account info
String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE);
String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME);
StringBuilder whereBuilder = new StringBuilder(128);
whereBuilder.append(Bookmarks.IS_DELETED);
whereBuilder.append(" = 0 AND ");
if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
whereBuilder.append(Bookmarks.ACCOUNT_NAME);
whereBuilder.append("=? AND ");
whereBuilder.append(Bookmarks.ACCOUNT_TYPE);
whereBuilder.append("=?");
// We use this where twice
args = new String[] { accountName, accountType,
accountName, accountType};
} else {
whereBuilder.append(Bookmarks.ACCOUNT_NAME);
whereBuilder.append(" IS NULL AND ");
whereBuilder.append(Bookmarks.ACCOUNT_TYPE);
whereBuilder.append(" IS NULL");
}
String where = whereBuilder.toString();
// Build the bookmark subquery for history union subquery
qb.setTables(TABLE_BOOKMARKS);
String subQuery = qb.buildQuery(null, where, null, null, null, null);
// Build the history union subquery
qb.setTables(String.format(FORMAT_COMBINED_JOIN_SUBQUERY_JOIN_IMAGES, subQuery));
qb.setProjectionMap(COMBINED_HISTORY_PROJECTION_MAP);
String historySubQuery = qb.buildQuery(null,
null, null, null, null, null);
// Build the bookmark union subquery
qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES);
qb.setProjectionMap(COMBINED_BOOKMARK_PROJECTION_MAP);
where += String.format(" AND %s NOT IN (SELECT %s FROM %s)",
Combined.URL, History.URL, TABLE_HISTORY);
String bookmarksSubQuery = qb.buildQuery(null, where,
null, null, null, null);
// Put it all together
String query = qb.buildUnionQuery(
new String[] {historySubQuery, bookmarksSubQuery},
null, null);
qb.setTables("(" + query + ")");
qb.setProjectionMap(null);
return args;
}
int deleteBookmarks(Uri uri, String selection, String[] selectionArgs,
boolean callerIsSyncAdapter) {
//TODO cascade deletes down from folders
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
// Look for account info
String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE);
String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME);
if (!TextUtils.isEmpty(accountType) && !TextUtils.isEmpty(accountName)) {
selection = DatabaseUtils.concatenateWhere(selection,
Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=? ");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { accountType, accountName });
} else {
selection = DatabaseUtils.concatenateWhere(selection,
Bookmarks.ACCOUNT_TYPE + " IS NULL AND " +
Bookmarks.ACCOUNT_NAME + " IS NULL ");
}
if (callerIsSyncAdapter) {
return db.delete(TABLE_BOOKMARKS, selection, selectionArgs);
}
ContentValues values = new ContentValues();
values.put(Bookmarks.DATE_MODIFIED, System.currentTimeMillis());
values.put(Bookmarks.IS_DELETED, 1);
return updateInTransaction(Bookmarks.CONTENT_URI, values,
selection, selectionArgs, callerIsSyncAdapter);
}
@Override
public int deleteInTransaction(Uri uri, String selection, String[] selectionArgs,
boolean callerIsSyncAdapter) {
final int match = URI_MATCHER.match(uri);
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
switch (match) {
case BOOKMARKS_ID: {
selection = DatabaseUtils.concatenateWhere(selection,
TABLE_BOOKMARKS + "._id=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case BOOKMARKS: {
int deleted = deleteBookmarks(uri, selection, selectionArgs, callerIsSyncAdapter);
pruneImages();
return deleted;
}
case HISTORY_ID: {
selection = DatabaseUtils.concatenateWhere(selection, TABLE_HISTORY + "._id=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case HISTORY: {
filterSearchClient(selectionArgs);
int deleted = db.delete(TABLE_HISTORY, selection, selectionArgs);
pruneImages();
return deleted;
}
case SEARCHES_ID: {
selection = DatabaseUtils.concatenateWhere(selection, TABLE_SEARCHES + "._id=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case SEARCHES: {
return db.delete(TABLE_SEARCHES, selection, selectionArgs);
}
case SYNCSTATE: {
return mSyncHelper.delete(db, selection, selectionArgs);
}
case SYNCSTATE_ID: {
String selectionWithId =
(SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ")
+ (selection == null ? "" : " AND (" + selection + ")");
return mSyncHelper.delete(db, selectionWithId, selectionArgs);
}
case LEGACY_ID: {
selection = DatabaseUtils.concatenateWhere(
selection, Combined._ID + " = CAST(? AS INTEGER)");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case LEGACY: {
String[] projection = new String[] { Combined._ID,
Combined.IS_BOOKMARK, Combined.URL };
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
uri = BookmarkUtils.addAccountInfo(getContext(), uri.buildUpon())
.build();
String[] args = createCombinedQuery(uri, projection, qb);
if (selectionArgs == null) {
selectionArgs = args;
} else {
selectionArgs = DatabaseUtils.appendSelectionArgs(
args, selectionArgs);
}
Cursor c = qb.query(db, projection, selection, selectionArgs,
null, null, null);
int deleted = 0;
while (c.moveToNext()) {
long id = c.getLong(0);
boolean isBookmark = c.getInt(1) != 0;
String url = c.getString(2);
if (isBookmark) {
deleted += deleteBookmarks(uri, Bookmarks._ID + "=?",
new String[] { Long.toString(id) },
callerIsSyncAdapter);
db.delete(TABLE_HISTORY, History.URL + "=?",
new String[] { url });
} else {
deleted += db.delete(TABLE_HISTORY,
Bookmarks._ID + "=?",
new String[] { Long.toString(id) });
}
}
return deleted;
}
}
throw new UnsupportedOperationException("Unknown update URI " + uri);
}
long queryDefaultFolderId(String accountName, String accountType) {
if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Cursor c = db.query(TABLE_BOOKMARKS, new String[] { Bookmarks._ID },
ChromeSyncColumns.SERVER_UNIQUE + " = ?" +
" AND account_type = ? AND account_name = ?",
new String[] { ChromeSyncColumns.FOLDER_NAME_BOOKMARKS_BAR,
accountType, accountName }, null, null, null);
if (c.moveToFirst()) {
return c.getLong(0);
}
}
return FIXED_ID_ROOT;
}
@Override
public Uri insertInTransaction(Uri uri, ContentValues values, boolean callerIsSyncAdapter) {
int match = URI_MATCHER.match(uri);
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
long id = -1;
if (match == LEGACY) {
// Intercept and route to the correct table
Integer bookmark = values.getAsInteger(BookmarkColumns.BOOKMARK);
values.remove(BookmarkColumns.BOOKMARK);
if (bookmark == null || bookmark == 0) {
match = HISTORY;
} else {
match = BOOKMARKS;
values.remove(BookmarkColumns.DATE);
values.remove(BookmarkColumns.VISITS);
values.remove(BookmarkColumns.USER_ENTERED);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getContext());
String accountType = prefs.getString(
BrowserBookmarksPage.PREF_ACCOUNT_TYPE, null);
String accountName = prefs.getString(
BrowserBookmarksPage.PREF_ACCOUNT_NAME, null);
values.put(Bookmarks.ACCOUNT_TYPE, accountType);
values.put(Bookmarks.ACCOUNT_NAME, accountName);
values.put(Bookmarks.IS_FOLDER, 0);
}
}
switch (match) {
case BOOKMARKS: {
// Mark rows dirty if they're not coming from a sync adapter
if (!callerIsSyncAdapter) {
long now = System.currentTimeMillis();
values.put(Bookmarks.DATE_CREATED, now);
values.put(Bookmarks.DATE_MODIFIED, now);
values.put(Bookmarks.DIRTY, 1);
// If no parent is set default to the "Bookmarks Bar" folder
if (!values.containsKey(Bookmarks.PARENT)) {
String accountType = values
.getAsString(Bookmarks.ACCOUNT_TYPE);
String accountName = values
.getAsString(Bookmarks.ACCOUNT_NAME);
values.put(Bookmarks.PARENT,
queryDefaultFolderId(accountName, accountType));
}
}
// If no position is requested put the bookmark at the beginning of the list
if (!values.containsKey(Bookmarks.POSITION)) {
values.put(Bookmarks.POSITION, Long.toString(Long.MIN_VALUE));
}
// Extract out the image values so they can be inserted into the images table
String url = values.getAsString(Bookmarks.URL);
ContentValues imageValues = extractImageValues(values, url);
Boolean isFolder = values.getAsBoolean(Bookmarks.IS_FOLDER);
if ((isFolder == null || !isFolder)
&& imageValues != null && !TextUtils.isEmpty(url)) {
int count = db.update(TABLE_IMAGES, imageValues, Images.URL + "=?",
new String[] { url });
if (count == 0) {
db.insertOrThrow(TABLE_IMAGES, Images.FAVICON, imageValues);
}
}
id = db.insertOrThrow(TABLE_BOOKMARKS, Bookmarks.DIRTY, values);
break;
}
case HISTORY: {
// If no created time is specified set it to now
if (!values.containsKey(History.DATE_CREATED)) {
values.put(History.DATE_CREATED, System.currentTimeMillis());
}
String url = values.getAsString(History.URL);
url = filterSearchClient(url);
values.put(History.URL, url);
// Extract out the image values so they can be inserted into the images table
ContentValues imageValues = extractImageValues(values,
values.getAsString(History.URL));
if (imageValues != null) {
db.insertOrThrow(TABLE_IMAGES, Images.FAVICON, imageValues);
}
id = db.insertOrThrow(TABLE_HISTORY, History.VISITS, values);
break;
}
case SEARCHES: {
id = insertSearchesInTransaction(db, values);
break;
}
case SYNCSTATE: {
id = mSyncHelper.insert(db, values);
break;
}
case SETTINGS: {
id = 0;
insertSettingsInTransaction(db, values);
break;
}
default: {
throw new UnsupportedOperationException("Unknown insert URI " + uri);
}
}
if (id >= 0) {
return ContentUris.withAppendedId(uri, id);
} else {
return null;
}
}
private void filterSearchClient(String[] selectionArgs) {
if (selectionArgs != null) {
for (int i = 0; i < selectionArgs.length; i++) {
selectionArgs[i] = filterSearchClient(selectionArgs[i]);
}
}
}
// Filters out the client=ms- param for search urls
private String filterSearchClient(String url) {
// remove "client" before updating it to the history so that it wont
// show up in the auto-complete list.
int index = url.indexOf("client=ms-");
if (index > 0 && url.contains(".google.")) {
int end = url.indexOf('&', index);
if (end > 0) {
url = url.substring(0, index)
.concat(url.substring(end + 1));
} else {
// the url.charAt(index-1) should be either '?' or '&'
url = url.substring(0, index-1);
}
}
return url;
}
/**
* Searches are unique, so perform an UPSERT manually since SQLite doesn't support them.
*/
private long insertSearchesInTransaction(SQLiteDatabase db, ContentValues values) {
String search = values.getAsString(Searches.SEARCH);
if (TextUtils.isEmpty(search)) {
throw new IllegalArgumentException("Must include the SEARCH field");
}
Cursor cursor = null;
try {
cursor = db.query(TABLE_SEARCHES, new String[] { Searches._ID },
Searches.SEARCH + "=?", new String[] { search }, null, null, null);
if (cursor.moveToNext()) {
long id = cursor.getLong(0);
db.update(TABLE_SEARCHES, values, Searches._ID + "=?",
new String[] { Long.toString(id) });
return id;
} else {
return db.insertOrThrow(TABLE_SEARCHES, Searches.SEARCH, values);
}
} finally {
if (cursor != null) cursor.close();
}
}
/**
* Settings are unique, so perform an UPSERT manually since SQLite doesn't support them.
*/
private long insertSettingsInTransaction(SQLiteDatabase db, ContentValues values) {
String key = values.getAsString(Settings.KEY);
if (TextUtils.isEmpty(key)) {
throw new IllegalArgumentException("Must include the KEY field");
}
String[] keyArray = new String[] { key };
Cursor cursor = null;
try {
cursor = db.query(TABLE_SETTINGS, new String[] { Settings.KEY },
Settings.KEY + "=?", keyArray, null, null, null);
if (cursor.moveToNext()) {
long id = cursor.getLong(0);
db.update(TABLE_SETTINGS, values, Settings.KEY + "=?", keyArray);
return id;
} else {
return db.insertOrThrow(TABLE_SETTINGS, Settings.VALUE, values);
}
} finally {
if (cursor != null) cursor.close();
}
}
@Override
public int updateInTransaction(Uri uri, ContentValues values, String selection,
String[] selectionArgs, boolean callerIsSyncAdapter) {
int match = URI_MATCHER.match(uri);
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
if (match == LEGACY || match == LEGACY_ID) {
// Intercept and route to the correct table
Integer bookmark = values.getAsInteger(BookmarkColumns.BOOKMARK);
values.remove(BookmarkColumns.BOOKMARK);
if (bookmark == null || bookmark == 0) {
if (match == LEGACY) {
match = HISTORY;
} else {
match = HISTORY_ID;
}
} else {
if (match == LEGACY) {
match = BOOKMARKS;
} else {
match = BOOKMARKS_ID;
}
values.remove(BookmarkColumns.DATE);
values.remove(BookmarkColumns.VISITS);
values.remove(BookmarkColumns.USER_ENTERED);
}
}
switch (match) {
case BOOKMARKS_ID: {
selection = DatabaseUtils.concatenateWhere(selection,
TABLE_BOOKMARKS + "._id=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case BOOKMARKS: {
int updated = updateBookmarksInTransaction(values, selection, selectionArgs,
callerIsSyncAdapter);
pruneImages();
return updated;
}
case HISTORY_ID: {
selection = DatabaseUtils.concatenateWhere(selection, TABLE_HISTORY + "._id=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case HISTORY: {
int updated = updateHistoryInTransaction(values, selection, selectionArgs);
pruneImages();
return updated;
}
case SYNCSTATE: {
return mSyncHelper.update(mDb, values,
appendAccountToSelection(uri, selection), selectionArgs);
}
case SYNCSTATE_ID: {
selection = appendAccountToSelection(uri, selection);
String selectionWithId =
(SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ")
+ (selection == null ? "" : " AND (" + selection + ")");
return mSyncHelper.update(mDb, values,
selectionWithId, selectionArgs);
}
case IMAGES: {
String url = values.getAsString(Images.URL);
if (TextUtils.isEmpty(url)) {
throw new IllegalArgumentException("Images.URL is required");
}
int count = db.update(TABLE_IMAGES, values, Images.URL + "=?",
new String[] { url });
if (count == 0) {
db.insertOrThrow(TABLE_IMAGES, Images.FAVICON, values);
count = 1;
}
return count;
}
case SEARCHES: {
return db.update(TABLE_SEARCHES, values, selection, selectionArgs);
}
}
throw new UnsupportedOperationException("Unknown update URI " + uri);
}
/**
* Does a query to find the matching bookmarks and updates each one with the provided values.
*/
int updateBookmarksInTransaction(ContentValues values, String selection,
String[] selectionArgs, boolean callerIsSyncAdapter) {
int count = 0;
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Cursor cursor = query(Bookmarks.CONTENT_URI,
new String[] { Bookmarks._ID, Bookmarks.VERSION, Bookmarks.URL },
selection, selectionArgs, null);
try {
String[] args = new String[1];
// Mark the bookmark dirty if the caller isn't a sync adapter
if (!callerIsSyncAdapter) {
values.put(Bookmarks.DATE_MODIFIED, System.currentTimeMillis());
values.put(Bookmarks.DIRTY, 1);
}
boolean updatingUrl = values.containsKey(Bookmarks.URL);
String url = null;
if (updatingUrl) {
url = values.getAsString(Bookmarks.URL);
}
ContentValues imageValues = extractImageValues(values, url);
while (cursor.moveToNext()) {
args[0] = cursor.getString(0);
if (!callerIsSyncAdapter) {
// increase the local version for non-sync changes
values.put(Bookmarks.VERSION, cursor.getLong(1) + 1);
}
count += db.update(TABLE_BOOKMARKS, values, "_id=?", args);
// Update the images over in their table
if (imageValues != null) {
if (!updatingUrl) {
url = cursor.getString(2);
imageValues.put(Images.URL, url);
}
if (!TextUtils.isEmpty(url)) {
args[0] = url;
if (db.update(TABLE_IMAGES, imageValues, Images.URL + "=?", args) == 0) {
db.insert(TABLE_IMAGES, Images.FAVICON, imageValues);
}
}
}
}
} finally {
if (cursor != null) cursor.close();
}
return count;
}
/**
* Does a query to find the matching bookmarks and updates each one with the provided values.
*/
int updateHistoryInTransaction(ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
filterSearchClient(selectionArgs);
Cursor cursor = query(History.CONTENT_URI,
new String[] { History._ID, History.URL },
selection, selectionArgs, null);
try {
String[] args = new String[1];
boolean updatingUrl = values.containsKey(History.URL);
String url = null;
if (updatingUrl) {
url = filterSearchClient(values.getAsString(History.URL));
values.put(History.URL, url);
}
ContentValues imageValues = extractImageValues(values, url);
while (cursor.moveToNext()) {
args[0] = cursor.getString(0);
count += db.update(TABLE_HISTORY, values, "_id=?", args);
// Update the images over in their table
if (imageValues != null) {
if (!updatingUrl) {
url = cursor.getString(1);
imageValues.put(Images.URL, url);
}
args[0] = url;
if (db.update(TABLE_IMAGES, imageValues, Images.URL + "=?", args) == 0) {
db.insert(TABLE_IMAGES, Images.FAVICON, imageValues);
}
}
}
} finally {
if (cursor != null) cursor.close();
}
return count;
}
String appendAccountToSelection(Uri uri, String selection) {
final String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
final String accountType = uri.getQueryParameter(RawContacts.ACCOUNT_TYPE);
final boolean partialUri = TextUtils.isEmpty(accountName) ^ TextUtils.isEmpty(accountType);
if (partialUri) {
// Throw when either account is incomplete
throw new IllegalArgumentException(
"Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE for " + uri);
}
// Accounts are valid by only checking one parameter, since we've
// already ruled out partial accounts.
final boolean validAccount = !TextUtils.isEmpty(accountName);
if (validAccount) {
StringBuilder selectionSb = new StringBuilder(RawContacts.ACCOUNT_NAME + "="
+ DatabaseUtils.sqlEscapeString(accountName) + " AND "
+ RawContacts.ACCOUNT_TYPE + "="
+ DatabaseUtils.sqlEscapeString(accountType));
if (!TextUtils.isEmpty(selection)) {
selectionSb.append(" AND (");
selectionSb.append(selection);
selectionSb.append(')');
}
return selectionSb.toString();
} else {
return selection;
}
}
ContentValues extractImageValues(ContentValues values, String url) {
ContentValues imageValues = null;
// favicon
if (values.containsKey(Bookmarks.FAVICON)) {
imageValues = new ContentValues();
imageValues.put(Images.FAVICON, values.getAsByteArray(Bookmarks.FAVICON));
values.remove(Bookmarks.FAVICON);
}
// thumbnail
if (values.containsKey(Bookmarks.THUMBNAIL)) {
if (imageValues == null) {
imageValues = new ContentValues();
}
imageValues.put(Images.THUMBNAIL, values.getAsByteArray(Bookmarks.THUMBNAIL));
values.remove(Bookmarks.THUMBNAIL);
}
// touch icon
if (values.containsKey(Bookmarks.TOUCH_ICON)) {
if (imageValues == null) {
imageValues = new ContentValues();
}
imageValues.put(Images.TOUCH_ICON, values.getAsByteArray(Bookmarks.TOUCH_ICON));
values.remove(Bookmarks.TOUCH_ICON);
}
if (imageValues != null) {
imageValues.put(Images.URL, url);
}
return imageValues;
}
void pruneImages() {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.delete(TABLE_IMAGES, IMAGE_PRUNE, null);
}
static class SuggestionsCursor extends AbstractCursor {
private static final int ID_INDEX = 0;
private static final int URL_INDEX = 1;
private static final int TITLE_INDEX = 2;
// shared suggestion array index, make sure to match COLUMNS
private static final int SUGGEST_COLUMN_INTENT_ACTION_ID = 1;
private static final int SUGGEST_COLUMN_INTENT_DATA_ID = 2;
private static final int SUGGEST_COLUMN_TEXT_1_ID = 3;
private static final int SUGGEST_COLUMN_TEXT_2_TEXT_ID = 4;
private static final int SUGGEST_COLUMN_TEXT_2_URL_ID = 5;
private static final int SUGGEST_COLUMN_ICON_1_ID = 6;
// shared suggestion columns
private static final String[] COLUMNS = new String[] {
BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
SearchManager.SUGGEST_COLUMN_INTENT_DATA,
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_TEXT_2,
SearchManager.SUGGEST_COLUMN_TEXT_2_URL,
SearchManager.SUGGEST_COLUMN_ICON_1};
private Cursor mSource;
public SuggestionsCursor(Cursor cursor) {
mSource = cursor;
}
@Override
public String[] getColumnNames() {
return COLUMNS;
}
@Override
public String getString(int columnIndex) {
switch (columnIndex) {
case ID_INDEX:
return mSource.getString(columnIndex);
case SUGGEST_COLUMN_INTENT_ACTION_ID:
return Intent.ACTION_VIEW;
case SUGGEST_COLUMN_INTENT_DATA_ID:
case SUGGEST_COLUMN_TEXT_2_TEXT_ID:
case SUGGEST_COLUMN_TEXT_2_URL_ID:
return mSource.getString(URL_INDEX);
case SUGGEST_COLUMN_TEXT_1_ID:
return mSource.getString(TITLE_INDEX);
case SUGGEST_COLUMN_ICON_1_ID:
return Integer.toString(R.drawable.ic_favorite_off_normal);
}
return null;
}
@Override
public int getCount() {
return mSource.getCount();
}
@Override
public double getDouble(int column) {
throw new UnsupportedOperationException();
}
@Override
public float getFloat(int column) {
throw new UnsupportedOperationException();
}
@Override
public int getInt(int column) {
throw new UnsupportedOperationException();
}
@Override
public long getLong(int column) {
switch (column) {
case ID_INDEX:
return mSource.getLong(ID_INDEX);
}
throw new UnsupportedOperationException();
}
@Override
public short getShort(int column) {
throw new UnsupportedOperationException();
}
@Override
public boolean isNull(int column) {
return mSource.isNull(column);
}
@Override
public boolean onMove(int oldPosition, int newPosition) {
return mSource.moveToPosition(newPosition);
}
}
}
| true | true | public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final int match = URI_MATCHER.match(uri);
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String limit = uri.getQueryParameter(BrowserContract.PARAM_LIMIT);
switch (match) {
case ACCOUNTS: {
qb.setTables(TABLE_BOOKMARKS);
qb.setProjectionMap(ACCOUNTS_PROJECTION_MAP);
qb.setDistinct(true);
qb.appendWhere(Bookmarks.ACCOUNT_NAME + " IS NOT NULL");
break;
}
case BOOKMARKS_FOLDER_ID:
case BOOKMARKS_ID:
case BOOKMARKS: {
// Only show deleted bookmarks if requested to do so
if (!uri.getBooleanQueryParameter(Bookmarks.QUERY_PARAMETER_SHOW_DELETED, false)) {
selection = DatabaseUtils.concatenateWhere(
Bookmarks.IS_DELETED + "=0", selection);
}
if (match == BOOKMARKS_ID) {
// Tack on the ID of the specific bookmark requested
selection = DatabaseUtils.concatenateWhere(selection,
TABLE_BOOKMARKS + "." + Bookmarks._ID + "=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
} else if (match == BOOKMARKS_FOLDER_ID) {
// Tack on the ID of the specific folder requested
selection = DatabaseUtils.concatenateWhere(selection,
TABLE_BOOKMARKS + "." + Bookmarks.PARENT + "=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
}
// Look for account info
String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE);
String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME);
if (!TextUtils.isEmpty(accountType) && !TextUtils.isEmpty(accountName)) {
selection = DatabaseUtils.concatenateWhere(selection,
Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=? ");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { accountType, accountName });
} else {
selection = DatabaseUtils.concatenateWhere(selection,
Bookmarks.ACCOUNT_TYPE + " IS NULL AND " +
Bookmarks.ACCOUNT_NAME + " IS NULL ");
}
// Set a default sort order if one isn't specified
if (TextUtils.isEmpty(sortOrder)) {
if (!TextUtils.isEmpty(accountType)
&& !TextUtils.isEmpty(accountName)) {
sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER_SYNC;
} else {
sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER;
}
}
qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP);
qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES);
break;
}
case BOOKMARKS_FOLDER: {
// Look for an account
boolean useAccount = false;
String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE);
String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME);
if (!TextUtils.isEmpty(accountType) && !TextUtils.isEmpty(accountName)) {
useAccount = true;
}
qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES);
String[] args;
String query;
// Set a default sort order if one isn't specified
if (TextUtils.isEmpty(sortOrder)) {
if (useAccount) {
sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER_SYNC;
} else {
sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER;
}
}
if (!useAccount) {
qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP);
String where = Bookmarks.PARENT + "=? AND " + Bookmarks.IS_DELETED + "=0";
where = DatabaseUtils.concatenateWhere(where, selection);
args = new String[] { Long.toString(FIXED_ID_ROOT) };
if (selectionArgs != null) {
args = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
}
query = qb.buildQuery(projection, where, null, null, sortOrder, null);
} else {
qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP);
String where = Bookmarks.ACCOUNT_TYPE + "=? AND " +
Bookmarks.ACCOUNT_NAME + "=? " +
"AND parent = " +
"(SELECT _id FROM " + TABLE_BOOKMARKS + " WHERE " +
ChromeSyncColumns.SERVER_UNIQUE + "=" +
"'" + ChromeSyncColumns.FOLDER_NAME_BOOKMARKS_BAR + "' " +
"AND account_type = ? AND account_name = ?) " +
"AND " + Bookmarks.IS_DELETED + "=0";
where = DatabaseUtils.concatenateWhere(where, selection);
String bookmarksBarQuery = qb.buildQuery(projection,
where, null, null, null, null);
args = new String[] {accountType, accountName,
accountType, accountName};
if (selectionArgs != null) {
args = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
}
where = Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=?" +
" AND " + ChromeSyncColumns.SERVER_UNIQUE + "=?";
where = DatabaseUtils.concatenateWhere(where, selection);
qb.setProjectionMap(OTHER_BOOKMARKS_PROJECTION_MAP);
String otherBookmarksQuery = qb.buildQuery(projection,
where, null, null, null, null);
query = qb.buildUnionQuery(
new String[] { bookmarksBarQuery, otherBookmarksQuery },
sortOrder, limit);
args = DatabaseUtils.appendSelectionArgs(args, new String[] {
accountType, accountName, ChromeSyncColumns.FOLDER_NAME_OTHER_BOOKMARKS,
});
if (selectionArgs != null) {
args = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
}
}
Cursor cursor = db.rawQuery(query, args);
if (cursor != null) {
cursor.setNotificationUri(getContext().getContentResolver(),
BrowserContract.AUTHORITY_URI);
}
return cursor;
}
case BOOKMARKS_SUGGESTIONS: {
return doSuggestQuery(selection, selectionArgs, limit);
}
case HISTORY_ID: {
selection = DatabaseUtils.concatenateWhere(selection, TABLE_HISTORY + "._id=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case HISTORY: {
filterSearchClient(selectionArgs);
if (sortOrder == null) {
sortOrder = DEFAULT_SORT_HISTORY;
}
qb.setProjectionMap(HISTORY_PROJECTION_MAP);
qb.setTables(TABLE_HISTORY_JOIN_IMAGES);
break;
}
case SEARCHES_ID: {
selection = DatabaseUtils.concatenateWhere(selection, TABLE_SEARCHES + "._id=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case SEARCHES: {
qb.setTables(TABLE_SEARCHES);
qb.setProjectionMap(SEARCHES_PROJECTION_MAP);
break;
}
case SYNCSTATE: {
return mSyncHelper.query(db, projection, selection, selectionArgs, sortOrder);
}
case SYNCSTATE_ID: {
selection = appendAccountToSelection(uri, selection);
String selectionWithId =
(SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ")
+ (selection == null ? "" : " AND (" + selection + ")");
return mSyncHelper.query(db, projection, selectionWithId, selectionArgs, sortOrder);
}
case IMAGES: {
qb.setTables(TABLE_IMAGES);
qb.setProjectionMap(IMAGES_PROJECTION_MAP);
break;
}
case LEGACY_ID:
case COMBINED_ID: {
selection = DatabaseUtils.concatenateWhere(
selection, Combined._ID + " = CAST(? AS INTEGER)");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case LEGACY:
case COMBINED: {
if ((match == LEGACY || match == LEGACY_ID)
&& projection == null) {
projection = Browser.HISTORY_PROJECTION;
}
String[] args = createCombinedQuery(uri, projection, qb);
if (selectionArgs == null) {
selectionArgs = args;
} else {
selectionArgs = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
}
break;
}
case SETTINGS: {
qb.setTables(TABLE_SETTINGS);
qb.setProjectionMap(SETTINGS_PROJECTION_MAP);
break;
}
default: {
throw new UnsupportedOperationException("Unknown URL " + uri.toString());
}
}
Cursor cursor = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder,
limit);
cursor.setNotificationUri(getContext().getContentResolver(), BrowserContract.AUTHORITY_URI);
return cursor;
}
| public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final int match = URI_MATCHER.match(uri);
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String limit = uri.getQueryParameter(BrowserContract.PARAM_LIMIT);
switch (match) {
case ACCOUNTS: {
qb.setTables(TABLE_BOOKMARKS);
qb.setProjectionMap(ACCOUNTS_PROJECTION_MAP);
qb.setDistinct(true);
qb.appendWhere(Bookmarks.ACCOUNT_NAME + " IS NOT NULL");
break;
}
case BOOKMARKS_FOLDER_ID:
case BOOKMARKS_ID:
case BOOKMARKS: {
// Only show deleted bookmarks if requested to do so
if (!uri.getBooleanQueryParameter(Bookmarks.QUERY_PARAMETER_SHOW_DELETED, false)) {
selection = DatabaseUtils.concatenateWhere(
Bookmarks.IS_DELETED + "=0", selection);
}
if (match == BOOKMARKS_ID) {
// Tack on the ID of the specific bookmark requested
selection = DatabaseUtils.concatenateWhere(selection,
TABLE_BOOKMARKS + "." + Bookmarks._ID + "=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
} else if (match == BOOKMARKS_FOLDER_ID) {
// Tack on the ID of the specific folder requested
selection = DatabaseUtils.concatenateWhere(selection,
TABLE_BOOKMARKS + "." + Bookmarks.PARENT + "=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
}
// Look for account info
String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE);
String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME);
// Only add it if it isn't already in the selection
if (selection == null ||
(!selection.contains(Bookmarks.ACCOUNT_NAME)
&& !selection.contains(Bookmarks.ACCOUNT_TYPE))) {
if (!TextUtils.isEmpty(accountType) && !TextUtils.isEmpty(accountName)) {
selection = DatabaseUtils.concatenateWhere(selection,
Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=? ");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { accountType, accountName });
} else {
selection = DatabaseUtils.concatenateWhere(selection,
Bookmarks.ACCOUNT_TYPE + " IS NULL AND " +
Bookmarks.ACCOUNT_NAME + " IS NULL ");
}
}
// Set a default sort order if one isn't specified
if (TextUtils.isEmpty(sortOrder)) {
if (!TextUtils.isEmpty(accountType)
&& !TextUtils.isEmpty(accountName)) {
sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER_SYNC;
} else {
sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER;
}
}
qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP);
qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES);
break;
}
case BOOKMARKS_FOLDER: {
// Look for an account
boolean useAccount = false;
String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE);
String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME);
if (!TextUtils.isEmpty(accountType) && !TextUtils.isEmpty(accountName)) {
useAccount = true;
}
qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES);
String[] args;
String query;
// Set a default sort order if one isn't specified
if (TextUtils.isEmpty(sortOrder)) {
if (useAccount) {
sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER_SYNC;
} else {
sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER;
}
}
if (!useAccount) {
qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP);
String where = Bookmarks.PARENT + "=? AND " + Bookmarks.IS_DELETED + "=0";
where = DatabaseUtils.concatenateWhere(where, selection);
args = new String[] { Long.toString(FIXED_ID_ROOT) };
if (selectionArgs != null) {
args = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
}
query = qb.buildQuery(projection, where, null, null, sortOrder, null);
} else {
qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP);
String where = Bookmarks.ACCOUNT_TYPE + "=? AND " +
Bookmarks.ACCOUNT_NAME + "=? " +
"AND parent = " +
"(SELECT _id FROM " + TABLE_BOOKMARKS + " WHERE " +
ChromeSyncColumns.SERVER_UNIQUE + "=" +
"'" + ChromeSyncColumns.FOLDER_NAME_BOOKMARKS_BAR + "' " +
"AND account_type = ? AND account_name = ?) " +
"AND " + Bookmarks.IS_DELETED + "=0";
where = DatabaseUtils.concatenateWhere(where, selection);
String bookmarksBarQuery = qb.buildQuery(projection,
where, null, null, null, null);
args = new String[] {accountType, accountName,
accountType, accountName};
if (selectionArgs != null) {
args = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
}
where = Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=?" +
" AND " + ChromeSyncColumns.SERVER_UNIQUE + "=?";
where = DatabaseUtils.concatenateWhere(where, selection);
qb.setProjectionMap(OTHER_BOOKMARKS_PROJECTION_MAP);
String otherBookmarksQuery = qb.buildQuery(projection,
where, null, null, null, null);
query = qb.buildUnionQuery(
new String[] { bookmarksBarQuery, otherBookmarksQuery },
sortOrder, limit);
args = DatabaseUtils.appendSelectionArgs(args, new String[] {
accountType, accountName, ChromeSyncColumns.FOLDER_NAME_OTHER_BOOKMARKS,
});
if (selectionArgs != null) {
args = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
}
}
Cursor cursor = db.rawQuery(query, args);
if (cursor != null) {
cursor.setNotificationUri(getContext().getContentResolver(),
BrowserContract.AUTHORITY_URI);
}
return cursor;
}
case BOOKMARKS_SUGGESTIONS: {
return doSuggestQuery(selection, selectionArgs, limit);
}
case HISTORY_ID: {
selection = DatabaseUtils.concatenateWhere(selection, TABLE_HISTORY + "._id=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case HISTORY: {
filterSearchClient(selectionArgs);
if (sortOrder == null) {
sortOrder = DEFAULT_SORT_HISTORY;
}
qb.setProjectionMap(HISTORY_PROJECTION_MAP);
qb.setTables(TABLE_HISTORY_JOIN_IMAGES);
break;
}
case SEARCHES_ID: {
selection = DatabaseUtils.concatenateWhere(selection, TABLE_SEARCHES + "._id=?");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case SEARCHES: {
qb.setTables(TABLE_SEARCHES);
qb.setProjectionMap(SEARCHES_PROJECTION_MAP);
break;
}
case SYNCSTATE: {
return mSyncHelper.query(db, projection, selection, selectionArgs, sortOrder);
}
case SYNCSTATE_ID: {
selection = appendAccountToSelection(uri, selection);
String selectionWithId =
(SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ")
+ (selection == null ? "" : " AND (" + selection + ")");
return mSyncHelper.query(db, projection, selectionWithId, selectionArgs, sortOrder);
}
case IMAGES: {
qb.setTables(TABLE_IMAGES);
qb.setProjectionMap(IMAGES_PROJECTION_MAP);
break;
}
case LEGACY_ID:
case COMBINED_ID: {
selection = DatabaseUtils.concatenateWhere(
selection, Combined._ID + " = CAST(? AS INTEGER)");
selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
new String[] { Long.toString(ContentUris.parseId(uri)) });
// fall through
}
case LEGACY:
case COMBINED: {
if ((match == LEGACY || match == LEGACY_ID)
&& projection == null) {
projection = Browser.HISTORY_PROJECTION;
}
String[] args = createCombinedQuery(uri, projection, qb);
if (selectionArgs == null) {
selectionArgs = args;
} else {
selectionArgs = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
}
break;
}
case SETTINGS: {
qb.setTables(TABLE_SETTINGS);
qb.setProjectionMap(SETTINGS_PROJECTION_MAP);
break;
}
default: {
throw new UnsupportedOperationException("Unknown URL " + uri.toString());
}
}
Cursor cursor = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder,
limit);
cursor.setNotificationUri(getContext().getContentResolver(), BrowserContract.AUTHORITY_URI);
return cursor;
}
|
diff --git a/src/main/java/org/apache/commons/digester3/CallMethodRule.java b/src/main/java/org/apache/commons/digester3/CallMethodRule.java
index 66fec2cc..c656bf2d 100644
--- a/src/main/java/org/apache/commons/digester3/CallMethodRule.java
+++ b/src/main/java/org/apache/commons/digester3/CallMethodRule.java
@@ -1,565 +1,566 @@
package org.apache.commons.digester3;
/*
* 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 static java.lang.String.format;
import static org.apache.commons.beanutils.ConvertUtils.convert;
import static org.apache.commons.beanutils.MethodUtils.invokeExactMethod;
import static org.apache.commons.beanutils.MethodUtils.invokeMethod;
import java.util.Formatter;
import org.apache.commons.beanutils.MethodUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* <p>
* Rule implementation that calls a method on an object on the stack (normally the top/parent object), passing arguments
* collected from subsequent <code>CallParamRule</code> rules or from the body of this element.
* </p>
* <p>
* By using {@link #CallMethodRule(String methodName)} a method call can be made to a method which accepts no arguments.
* </p>
* <p>
* Incompatible method parameter types are converted using <code>org.apache.commons.beanutils.ConvertUtils</code>.
* </p>
* <p>
* This rule now uses {@link MethodUtils#invokeMethod} by default. This increases the kinds of methods successfully and
* allows primitives to be matched by passing in wrapper classes. There are rare cases when
* {@link MethodUtils#invokeExactMethod} (the old default) is required. This method is much stricter in it's reflection.
* Setting the <code>UseExactMatch</code> to true reverts to the use of this method.
* </p>
* <p>
* Note that the target method is invoked when the <i>end</i> of the tag the CallMethodRule fired on is encountered,
* <i>not</i> when the last parameter becomes available. This implies that rules which fire on tags nested within the
* one associated with the CallMethodRule will fire before the CallMethodRule invokes the target method. This behavior
* is not configurable.
* </p>
* <p>
* Note also that if a CallMethodRule is expecting exactly one parameter and that parameter is not available (eg
* CallParamRule is used with an attribute name but the attribute does not exist) then the method will not be invoked.
* If a CallMethodRule is expecting more than one parameter, then it is always invoked, regardless of whether the
* parameters were available or not; missing parameters are converted to the appropriate target type by calling
* ConvertUtils.convert. Note that the default ConvertUtils converters for the String type returns a null when passed a
* null, meaning that CallMethodRule will passed null for all String parameters for which there is no parameter info
* available from the XML. However parameters of type Float and Integer will be passed a real object containing a zero
* value as that is the output of the default ConvertUtils converters for those types when passed a null. You can
* register custom converters to change this behavior; see the BeanUtils library documentation for more info.
* </p>
* <p>
* Note that when a constructor is used with paramCount=0, indicating that the body of the element is to be passed to
* the target method, an empty element will cause an <i>empty string</i> to be passed to the target method, not null.
* And if automatic type conversion is being applied (ie if the target function takes something other than a string as a
* parameter) then the conversion will fail if the converter class does not accept an empty string as valid input.
* </p>
* <p>
* CallMethodRule has a design flaw which can cause it to fail under certain rule configurations. All CallMethodRule
* instances share a single parameter stack, and all CallParamRule instances simply store their data into the
* parameter-info structure that is on the top of the stack. This means that two CallMethodRule instances cannot be
* associated with the same pattern without getting scrambled parameter data. This same issue also applies when a
* CallMethodRule matches some element X, a different CallMethodRule matches a child element Y and some of the
* CallParamRules associated with the first CallMethodRule match element Y or one of its child elements. This issue has
* been present since the very first release of Digester. Note, however, that this configuration of CallMethodRule
* instances is not commonly required.
* </p>
*/
public class CallMethodRule
extends Rule
{
// ----------------------------------------------------------- Constructors
/**
* Construct a "call method" rule with the specified method name. The parameter types (if any) default to
* java.lang.String.
*
* @param methodName Method name of the parent method to call
* @param paramCount The number of parameters to collect, or zero for a single argument from the body of this
* element.
*/
public CallMethodRule( String methodName, int paramCount )
{
this( 0, methodName, paramCount );
}
/**
* Construct a "call method" rule with the specified method name. The parameter types (if any) default to
* java.lang.String.
*
* @param targetOffset location of the target object. Positive numbers are relative to the top of the digester
* object stack. Negative numbers are relative to the bottom of the stack. Zero implies the top object on
* the stack.
* @param methodName Method name of the parent method to call
* @param paramCount The number of parameters to collect, or zero for a single argument from the body of this
* element.
*/
public CallMethodRule( int targetOffset, String methodName, int paramCount )
{
this.targetOffset = targetOffset;
this.methodName = methodName;
this.paramCount = paramCount;
if ( paramCount == 0 )
{
this.paramTypes = new Class[] { String.class };
}
else
{
this.paramTypes = new Class[paramCount];
for ( int i = 0; i < this.paramTypes.length; i++ )
{
this.paramTypes[i] = String.class;
}
}
}
/**
* Construct a "call method" rule with the specified method name. The method should accept no parameters.
*
* @param methodName Method name of the parent method to call
*/
public CallMethodRule( String methodName )
{
this( 0, methodName, 0, (Class[]) null );
}
/**
* Construct a "call method" rule with the specified method name. The method should accept no parameters.
*
* @param targetOffset location of the target object. Positive numbers are relative to the top of the digester
* object stack. Negative numbers are relative to the bottom of the stack. Zero implies the top object on
* the stack.
* @param methodName Method name of the parent method to call
*/
public CallMethodRule( int targetOffset, String methodName )
{
this( targetOffset, methodName, 0, (Class[]) null );
}
/**
* Construct a "call method" rule with the specified method name and parameter types. If <code>paramCount</code> is
* set to zero the rule will use the body of this element as the single argument of the method, unless
* <code>paramTypes</code> is null or empty, in this case the rule will call the specified method with no arguments.
*
* @param methodName Method name of the parent method to call
* @param paramCount The number of parameters to collect, or zero for a single argument from the body of ths element
* @param paramTypes The Java class names of the arguments (if you wish to use a primitive type, specify the
* corresonding Java wrapper class instead, such as <code>java.lang.Boolean</code> for a
* <code>boolean</code> parameter)
*/
public CallMethodRule( String methodName, int paramCount, String paramTypes[] )
{
this( 0, methodName, paramCount, paramTypes );
}
/**
* Construct a "call method" rule with the specified method name and parameter types. If <code>paramCount</code> is
* set to zero the rule will use the body of this element as the single argument of the method, unless
* <code>paramTypes</code> is null or empty, in this case the rule will call the specified method with no arguments.
*
* @param targetOffset location of the target object. Positive numbers are relative to the top of the digester
* object stack. Negative numbers are relative to the bottom of the stack. Zero implies the top object on
* the stack.
* @param methodName Method name of the parent method to call
* @param paramCount The number of parameters to collect, or zero for a single argument from the body of the element
* @param paramTypes The Java class names of the arguments (if you wish to use a primitive type, specify the
* corresponding Java wrapper class instead, such as <code>java.lang.Boolean</code> for a
* <code>boolean</code> parameter)
*/
public CallMethodRule( int targetOffset, String methodName, int paramCount, String paramTypes[] )
{
this.targetOffset = targetOffset;
this.methodName = methodName;
this.paramCount = paramCount;
if ( paramTypes == null )
{
this.paramTypes = new Class[paramCount];
for ( int i = 0; i < this.paramTypes.length; i++ )
{
this.paramTypes[i] = String.class;
}
}
else
{
// copy the parameter class names into an array
// the classes will be loaded when the digester is set
this.paramClassNames = new String[paramTypes.length];
for ( int i = 0; i < this.paramClassNames.length; i++ )
{
this.paramClassNames[i] = paramTypes[i];
}
}
}
/**
* Construct a "call method" rule with the specified method name and parameter types. If <code>paramCount</code> is
* set to zero the rule will use the body of this element as the single argument of the method, unless
* <code>paramTypes</code> is null or empty, in this case the rule will call the specified method with no arguments.
*
* @param methodName Method name of the parent method to call
* @param paramCount The number of parameters to collect, or zero for a single argument from the body of the element
* @param paramTypes The Java classes that represent the parameter types of the method arguments (if you wish to use
* a primitive type, specify the corresponding Java wrapper class instead, such as
* <code>java.lang.Boolean.TYPE</code> for a <code>boolean</code> parameter)
*/
public CallMethodRule( String methodName, int paramCount, Class<?> paramTypes[] )
{
this( 0, methodName, paramCount, paramTypes );
}
/**
* Construct a "call method" rule with the specified method name and parameter types. If <code>paramCount</code> is
* set to zero the rule will use the body of this element as the single argument of the method, unless
* <code>paramTypes</code> is null or empty, in this case the rule will call the specified method with no arguments.
*
* @param targetOffset location of the target object. Positive numbers are relative to the top of the digester
* object stack. Negative numbers are relative to the bottom of the stack. Zero implies the top object on
* the stack.
* @param methodName Method name of the parent method to call
* @param paramCount The number of parameters to collect, or zero for a single argument from the body of the element
* @param paramTypes The Java classes that represent the parameter types of the method arguments (if you wish to use
* a primitive type, specify the corresponding Java wrapper class instead, such as
* <code>java.lang.Boolean.TYPE</code> for a <code>boolean</code> parameter)
*/
public CallMethodRule( int targetOffset, String methodName, int paramCount, Class<?> paramTypes[] )
{
this.targetOffset = targetOffset;
this.methodName = methodName;
this.paramCount = paramCount;
if ( paramTypes == null )
{
this.paramTypes = new Class[paramCount];
for ( int i = 0; i < this.paramTypes.length; i++ )
{
this.paramTypes[i] = String.class;
}
}
else
{
this.paramTypes = new Class[paramTypes.length];
for ( int i = 0; i < this.paramTypes.length; i++ )
{
this.paramTypes[i] = paramTypes[i];
}
}
}
// ----------------------------------------------------- Instance Variables
/**
* The body text collected from this element.
*/
protected String bodyText = null;
/**
* location of the target object for the call, relative to the top of the digester object stack. The default value
* of zero means the target object is the one on top of the stack.
*/
protected int targetOffset = 0;
/**
* The method name to call on the parent object.
*/
protected String methodName = null;
/**
* The number of parameters to collect from <code>MethodParam</code> rules. If this value is zero, a single
* parameter will be collected from the body of this element.
*/
protected int paramCount = 0;
/**
* The parameter types of the parameters to be collected.
*/
protected Class<?> paramTypes[] = null;
/**
* The names of the classes of the parameters to be collected. This attribute allows creation of the classes to be
* postponed until the digester is set.
*/
private String paramClassNames[] = null;
/**
* Should <code>MethodUtils.invokeExactMethod</code> be used for reflection.
*/
private boolean useExactMatch = false;
// --------------------------------------------------------- Public Methods
/**
* Should <code>MethodUtils.invokeExactMethod</code> be used for the reflection.
*
* @return true, if <code>MethodUtils.invokeExactMethod</code> Should be used for the reflection,
* false otherwise
*/
public boolean getUseExactMatch()
{
return useExactMatch;
}
/**
* Set whether <code>MethodUtils.invokeExactMethod</code> should be used for the reflection.
*
* @param useExactMatch The <code>MethodUtils.invokeExactMethod</code> flag
*/
public void setUseExactMatch( boolean useExactMatch )
{
this.useExactMatch = useExactMatch;
}
/**
* {@inheritDoc}
*/
@Override
public void setDigester( Digester digester )
{
// call superclass
super.setDigester( digester );
// if necessary, load parameter classes
if ( this.paramClassNames != null )
{
this.paramTypes = new Class[paramClassNames.length];
for ( int i = 0; i < this.paramClassNames.length; i++ )
{
try
{
this.paramTypes[i] = digester.getClassLoader().loadClass( this.paramClassNames[i] );
}
catch ( ClassNotFoundException e )
{
String errorMessage = format( "[CallMethodRule] Cannot load class %s at position %s",
this.paramClassNames[i], i );
// use the digester log
digester.getLogger().error( errorMessage, e );
throw new RuntimeException( errorMessage, e );
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void begin( String namespace, String name, Attributes attributes )
throws Exception
{
// Push an array to capture the parameter values if necessary
if ( paramCount > 0 )
{
Object parameters[] = new Object[paramCount];
for ( int i = 0; i < parameters.length; i++ )
{
parameters[i] = null;
}
getDigester().pushParams( parameters );
}
}
/**
* {@inheritDoc}
*/
@Override
public void body( String namespace, String name, String text )
throws Exception
{
if ( paramCount == 0 )
{
this.bodyText = text.trim();
}
}
/**
* {@inheritDoc}
*/
@Override
public void end( String namespace, String name )
throws Exception
{
// Retrieve or construct the parameter values array
- Object parameters[] = null;
+ Object[] parameters;
if ( paramCount > 0 )
{
parameters = getDigester().popParams();
if ( getDigester().getLogger().isTraceEnabled() )
{
for ( int i = 0, size = parameters.length; i < size; i++ )
{
getDigester().getLogger().trace( format( "[CallMethodRule]{%s} parameters[%s]=%s",
getDigester().getMatch(),
i,
parameters[i] ) );
}
}
// In the case where the target method takes a single parameter
// and that parameter does not exist (the CallParamRule never
// executed or the CallParamRule was intended to set the parameter
// from an attribute but the attribute wasn't present etc) then
// skip the method call.
//
// This is useful when a class has a "default" value that should
// only be overridden if data is present in the XML. I don't
// know why this should only apply to methods taking *one*
// parameter, but it always has been so we can't change it now.
if ( paramCount == 1 && parameters[0] == null )
{
return;
}
}
else if ( paramTypes != null && paramTypes.length != 0 )
{
// Having paramCount == 0 and paramTypes.length == 1 indicates
// that we have the special case where the target method has one
// parameter being the body text of the current element.
// There is no body text included in the source XML file,
// so skip the method call
if ( bodyText == null )
{
return;
}
parameters = new Object[] { bodyText };
if ( paramTypes.length == 0 )
{
paramTypes = new Class[] { String.class };
}
}
else
{
// When paramCount is zero and paramTypes.length is zero it
// means that we truly are calling a method with no parameters.
// Nothing special needs to be done here.
+ parameters = new Object[0];
}
// Construct the parameter values array we will need
// We only do the conversion if the param value is a String and
// the specified paramType is not String.
Object[] paramValues = new Object[paramTypes.length];
for ( int i = 0; i < paramTypes.length; i++ )
{
// convert nulls and convert stringy parameters
// for non-stringy param types
if ( parameters[i] == null
|| ( parameters[i] instanceof String && !String.class.isAssignableFrom( paramTypes[i] ) ) )
{
paramValues[i] = convert( (String) parameters[i], paramTypes[i] );
}
else
{
paramValues[i] = parameters[i];
}
}
// Determine the target object for the method call
Object target;
if ( targetOffset >= 0 )
{
target = getDigester().peek( targetOffset );
}
else
{
target = getDigester().peek( getDigester().getCount() + targetOffset );
}
if ( target == null )
{
throw new SAXException( format( "[CallMethodRule]{%s} Call target is null (targetOffset=%s, stackdepth=%s)",
getDigester().getMatch(), targetOffset, getDigester().getCount() ) );
}
// Invoke the required method on the top object
if ( getDigester().getLogger().isDebugEnabled() )
{
Formatter formatter =
new Formatter().format( "[CallMethodRule]{%s} Call %s.%s(",
getDigester().getMatch(),
target.getClass().getName(),
methodName );
for ( int i = 0; i < paramValues.length; i++ )
{
formatter.format( "%s%s/%s", ( i > 0 ? ", " : "" ), paramValues[i], paramTypes[i].getName() );
}
formatter.format( ")" );
getDigester().getLogger().debug( formatter.toString() );
}
Object result = null;
if ( useExactMatch )
{
// invoke using exact match
result = invokeExactMethod( target, methodName, paramValues, paramTypes );
}
else
{
// invoke using fuzzier match
result = invokeMethod( target, methodName, paramValues, paramTypes );
}
processMethodCallResult( result );
}
/**
* {@inheritDoc}
*/
@Override
public void finish()
throws Exception
{
bodyText = null;
}
/**
* Subclasses may override this method to perform additional processing of the invoked method's result.
*
* @param result the Object returned by the method invoked, possibly null
*/
protected void processMethodCallResult( Object result )
{
// do nothing
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
Formatter formatter = new Formatter().format( "CallMethodRule[methodName=%s, paramCount=%s, paramTypes={",
methodName, paramCount );
if ( paramTypes != null )
{
for ( int i = 0; i < paramTypes.length; i++ )
{
formatter.format( "%s%s",
( i > 0 ? ", " : "" ),
( paramTypes[i] != null ? paramTypes[i].getName() : "null" ) );
}
}
formatter.format( "}]" );
return ( formatter.toString() );
}
}
| false | true | public void end( String namespace, String name )
throws Exception
{
// Retrieve or construct the parameter values array
Object parameters[] = null;
if ( paramCount > 0 )
{
parameters = getDigester().popParams();
if ( getDigester().getLogger().isTraceEnabled() )
{
for ( int i = 0, size = parameters.length; i < size; i++ )
{
getDigester().getLogger().trace( format( "[CallMethodRule]{%s} parameters[%s]=%s",
getDigester().getMatch(),
i,
parameters[i] ) );
}
}
// In the case where the target method takes a single parameter
// and that parameter does not exist (the CallParamRule never
// executed or the CallParamRule was intended to set the parameter
// from an attribute but the attribute wasn't present etc) then
// skip the method call.
//
// This is useful when a class has a "default" value that should
// only be overridden if data is present in the XML. I don't
// know why this should only apply to methods taking *one*
// parameter, but it always has been so we can't change it now.
if ( paramCount == 1 && parameters[0] == null )
{
return;
}
}
else if ( paramTypes != null && paramTypes.length != 0 )
{
// Having paramCount == 0 and paramTypes.length == 1 indicates
// that we have the special case where the target method has one
// parameter being the body text of the current element.
// There is no body text included in the source XML file,
// so skip the method call
if ( bodyText == null )
{
return;
}
parameters = new Object[] { bodyText };
if ( paramTypes.length == 0 )
{
paramTypes = new Class[] { String.class };
}
}
else
{
// When paramCount is zero and paramTypes.length is zero it
// means that we truly are calling a method with no parameters.
// Nothing special needs to be done here.
}
// Construct the parameter values array we will need
// We only do the conversion if the param value is a String and
// the specified paramType is not String.
Object[] paramValues = new Object[paramTypes.length];
for ( int i = 0; i < paramTypes.length; i++ )
{
// convert nulls and convert stringy parameters
// for non-stringy param types
if ( parameters[i] == null
|| ( parameters[i] instanceof String && !String.class.isAssignableFrom( paramTypes[i] ) ) )
{
paramValues[i] = convert( (String) parameters[i], paramTypes[i] );
}
else
{
paramValues[i] = parameters[i];
}
}
// Determine the target object for the method call
Object target;
if ( targetOffset >= 0 )
{
target = getDigester().peek( targetOffset );
}
else
{
target = getDigester().peek( getDigester().getCount() + targetOffset );
}
if ( target == null )
{
throw new SAXException( format( "[CallMethodRule]{%s} Call target is null (targetOffset=%s, stackdepth=%s)",
getDigester().getMatch(), targetOffset, getDigester().getCount() ) );
}
// Invoke the required method on the top object
if ( getDigester().getLogger().isDebugEnabled() )
{
Formatter formatter =
new Formatter().format( "[CallMethodRule]{%s} Call %s.%s(",
getDigester().getMatch(),
target.getClass().getName(),
methodName );
for ( int i = 0; i < paramValues.length; i++ )
{
formatter.format( "%s%s/%s", ( i > 0 ? ", " : "" ), paramValues[i], paramTypes[i].getName() );
}
formatter.format( ")" );
getDigester().getLogger().debug( formatter.toString() );
}
Object result = null;
if ( useExactMatch )
{
// invoke using exact match
result = invokeExactMethod( target, methodName, paramValues, paramTypes );
}
else
{
// invoke using fuzzier match
result = invokeMethod( target, methodName, paramValues, paramTypes );
}
processMethodCallResult( result );
}
| public void end( String namespace, String name )
throws Exception
{
// Retrieve or construct the parameter values array
Object[] parameters;
if ( paramCount > 0 )
{
parameters = getDigester().popParams();
if ( getDigester().getLogger().isTraceEnabled() )
{
for ( int i = 0, size = parameters.length; i < size; i++ )
{
getDigester().getLogger().trace( format( "[CallMethodRule]{%s} parameters[%s]=%s",
getDigester().getMatch(),
i,
parameters[i] ) );
}
}
// In the case where the target method takes a single parameter
// and that parameter does not exist (the CallParamRule never
// executed or the CallParamRule was intended to set the parameter
// from an attribute but the attribute wasn't present etc) then
// skip the method call.
//
// This is useful when a class has a "default" value that should
// only be overridden if data is present in the XML. I don't
// know why this should only apply to methods taking *one*
// parameter, but it always has been so we can't change it now.
if ( paramCount == 1 && parameters[0] == null )
{
return;
}
}
else if ( paramTypes != null && paramTypes.length != 0 )
{
// Having paramCount == 0 and paramTypes.length == 1 indicates
// that we have the special case where the target method has one
// parameter being the body text of the current element.
// There is no body text included in the source XML file,
// so skip the method call
if ( bodyText == null )
{
return;
}
parameters = new Object[] { bodyText };
if ( paramTypes.length == 0 )
{
paramTypes = new Class[] { String.class };
}
}
else
{
// When paramCount is zero and paramTypes.length is zero it
// means that we truly are calling a method with no parameters.
// Nothing special needs to be done here.
parameters = new Object[0];
}
// Construct the parameter values array we will need
// We only do the conversion if the param value is a String and
// the specified paramType is not String.
Object[] paramValues = new Object[paramTypes.length];
for ( int i = 0; i < paramTypes.length; i++ )
{
// convert nulls and convert stringy parameters
// for non-stringy param types
if ( parameters[i] == null
|| ( parameters[i] instanceof String && !String.class.isAssignableFrom( paramTypes[i] ) ) )
{
paramValues[i] = convert( (String) parameters[i], paramTypes[i] );
}
else
{
paramValues[i] = parameters[i];
}
}
// Determine the target object for the method call
Object target;
if ( targetOffset >= 0 )
{
target = getDigester().peek( targetOffset );
}
else
{
target = getDigester().peek( getDigester().getCount() + targetOffset );
}
if ( target == null )
{
throw new SAXException( format( "[CallMethodRule]{%s} Call target is null (targetOffset=%s, stackdepth=%s)",
getDigester().getMatch(), targetOffset, getDigester().getCount() ) );
}
// Invoke the required method on the top object
if ( getDigester().getLogger().isDebugEnabled() )
{
Formatter formatter =
new Formatter().format( "[CallMethodRule]{%s} Call %s.%s(",
getDigester().getMatch(),
target.getClass().getName(),
methodName );
for ( int i = 0; i < paramValues.length; i++ )
{
formatter.format( "%s%s/%s", ( i > 0 ? ", " : "" ), paramValues[i], paramTypes[i].getName() );
}
formatter.format( ")" );
getDigester().getLogger().debug( formatter.toString() );
}
Object result = null;
if ( useExactMatch )
{
// invoke using exact match
result = invokeExactMethod( target, methodName, paramValues, paramTypes );
}
else
{
// invoke using fuzzier match
result = invokeMethod( target, methodName, paramValues, paramTypes );
}
processMethodCallResult( result );
}
|
diff --git a/src/main/java/uk/co/CyniCode/CyniChat/Command/AdminCommand.java b/src/main/java/uk/co/CyniCode/CyniChat/Command/AdminCommand.java
index 2b4ca93..90e4c85 100644
--- a/src/main/java/uk/co/CyniCode/CyniChat/Command/AdminCommand.java
+++ b/src/main/java/uk/co/CyniCode/CyniChat/Command/AdminCommand.java
@@ -1,58 +1,58 @@
package uk.co.CyniCode.CyniChat.Command;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import uk.co.CyniCode.CyniChat.DataManager;
import uk.co.CyniCode.CyniChat.PermissionManager;
import uk.co.CyniCode.CyniChat.objects.Channel;
public class AdminCommand {
public static boolean create( CommandSender player, String name, String nick, Boolean protect ) {
if ( player instanceof Player )
if ( !PermissionManager.checkPerm( (Player) player, "cynichat.admin.create") )
return false;
if ( DataManager.getChannel(name) != null ) {
player.sendMessage("This channel is already in existance");
return true;
}
Channel newChan = new Channel();
if ( DataManager.hasNick( nick ) == true )
nick = name.substring(0, 2);
- newChan.create( name.toLowerCase(), nick, protect );
+ newChan.create( name.toLowerCase(), nick.toLowerCase(), protect );
DataManager.addChannel( newChan );
PermissionManager.addChannelPerms( player, newChan, protect );
player.sendMessage( "The channel: " + name + " has now been created" );
return true;
}
public static boolean remove( CommandSender player, String name ) {
if ( player instanceof Player )
if ( PermissionManager.checkPerm( (Player) player, "cynichat.admin.remove") )
return false;
if ( DataManager.deleteChannel( name ) == true ) {
player.sendMessage("Channel has been removed");
return true;
}
player.sendMessage("This channel doesn't exist");
return true;
}
public static boolean createInfo( CommandSender player ) {
player.sendMessage(ChatColor.RED + "Incorrect Command");
player.sendMessage( "/ch create "+ChCommand.necessary("name")+" "+ChCommand.optional("nick") );
return true;
}
public static boolean removeInfo( CommandSender player ) {
player.sendMessage(ChatColor.RED + "Incorrect Command");
player.sendMessage( "/ch remove "+ChCommand.necessary("name") );
return true;
}
}
| true | true | public static boolean create( CommandSender player, String name, String nick, Boolean protect ) {
if ( player instanceof Player )
if ( !PermissionManager.checkPerm( (Player) player, "cynichat.admin.create") )
return false;
if ( DataManager.getChannel(name) != null ) {
player.sendMessage("This channel is already in existance");
return true;
}
Channel newChan = new Channel();
if ( DataManager.hasNick( nick ) == true )
nick = name.substring(0, 2);
newChan.create( name.toLowerCase(), nick, protect );
DataManager.addChannel( newChan );
PermissionManager.addChannelPerms( player, newChan, protect );
player.sendMessage( "The channel: " + name + " has now been created" );
return true;
}
| public static boolean create( CommandSender player, String name, String nick, Boolean protect ) {
if ( player instanceof Player )
if ( !PermissionManager.checkPerm( (Player) player, "cynichat.admin.create") )
return false;
if ( DataManager.getChannel(name) != null ) {
player.sendMessage("This channel is already in existance");
return true;
}
Channel newChan = new Channel();
if ( DataManager.hasNick( nick ) == true )
nick = name.substring(0, 2);
newChan.create( name.toLowerCase(), nick.toLowerCase(), protect );
DataManager.addChannel( newChan );
PermissionManager.addChannelPerms( player, newChan, protect );
player.sendMessage( "The channel: " + name + " has now been created" );
return true;
}
|
diff --git a/src/main/java/net/krinsoft/jobsuite/commands/JobListCommand.java b/src/main/java/net/krinsoft/jobsuite/commands/JobListCommand.java
index 2f0d884..d7743bf 100644
--- a/src/main/java/net/krinsoft/jobsuite/commands/JobListCommand.java
+++ b/src/main/java/net/krinsoft/jobsuite/commands/JobListCommand.java
@@ -1,61 +1,62 @@
package net.krinsoft.jobsuite.commands;
import net.krinsoft.jobsuite.Job;
import net.krinsoft.jobsuite.JobCore;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* @author krinsdeath
*/
public class JobListCommand extends JobCommand {
public JobListCommand(JobCore instance) {
super(instance);
setName("JobSuite: List Jobs");
setCommandUsage("/job list [page]");
setArgRange(0, 1);
addKey("jobsuite list");
addKey("job list");
addKey("js list");
setPermission("jobsuite.list", "Lists active jobs.", PermissionDefault.TRUE);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
int page = 1;
if (args.size() > 0) {
try {
page = Integer.parseInt(args.get(0));
} catch (NumberFormatException e) {
page = 1;
}
}
List<Job> jobs = manager.getJobs(sender);
- int pages = jobs.size() / 6;
+ int pages = (int) Math.ceil(jobs.size() / 6.0D);
int bound = jobs.size();
- if (page >= pages) {
+ if (page > pages) {
page = pages;
} else {
- bound = (page * 6) + 6;
+ bound = ((page - 1) * 6) + 6;
}
if (page < 0) {
page = 1;
}
if (jobs.size() == 0) {
message(sender, "There are no jobs available.");
return;
}
- message(sender, "Job List [" + (page+1) + "/" + (pages+1) + "] - Total: " + jobs.size());
- message(sender, "Lock: " + ChatColor.AQUA + "/job lock [job id]");
- for (int i = page * 6; i < bound; i++) {
+ message(sender, "Job List [" + (page) + "/" + (pages) + "] - Total: " + jobs.size());
+ message(sender, "To Lock a Job: " + ChatColor.AQUA + "/job lock [job id]");
+ for (int i = ((page - 1) * 6); i < bound; i++) {
+ if (i >= jobs.size()) { break; }
Job job = jobs.get(i);
if (!job.isFinished()) {
message(sender, ChatColor.WHITE + "[ID: " + ChatColor.GOLD + job.getId() + ChatColor.WHITE + "] " + job.getName() + (job.getLock() != null ? ChatColor.GREEN + " (Locked By: " + ChatColor.AQUA + job.getLock() + ChatColor.GREEN + ")" + ChatColor.WHITE : "") + ": " + ChatColor.AQUA + job.getDescription());
}
}
}
}
| false | true | public void runCommand(CommandSender sender, List<String> args) {
int page = 1;
if (args.size() > 0) {
try {
page = Integer.parseInt(args.get(0));
} catch (NumberFormatException e) {
page = 1;
}
}
List<Job> jobs = manager.getJobs(sender);
int pages = jobs.size() / 6;
int bound = jobs.size();
if (page >= pages) {
page = pages;
} else {
bound = (page * 6) + 6;
}
if (page < 0) {
page = 1;
}
if (jobs.size() == 0) {
message(sender, "There are no jobs available.");
return;
}
message(sender, "Job List [" + (page+1) + "/" + (pages+1) + "] - Total: " + jobs.size());
message(sender, "Lock: " + ChatColor.AQUA + "/job lock [job id]");
for (int i = page * 6; i < bound; i++) {
Job job = jobs.get(i);
if (!job.isFinished()) {
message(sender, ChatColor.WHITE + "[ID: " + ChatColor.GOLD + job.getId() + ChatColor.WHITE + "] " + job.getName() + (job.getLock() != null ? ChatColor.GREEN + " (Locked By: " + ChatColor.AQUA + job.getLock() + ChatColor.GREEN + ")" + ChatColor.WHITE : "") + ": " + ChatColor.AQUA + job.getDescription());
}
}
}
| public void runCommand(CommandSender sender, List<String> args) {
int page = 1;
if (args.size() > 0) {
try {
page = Integer.parseInt(args.get(0));
} catch (NumberFormatException e) {
page = 1;
}
}
List<Job> jobs = manager.getJobs(sender);
int pages = (int) Math.ceil(jobs.size() / 6.0D);
int bound = jobs.size();
if (page > pages) {
page = pages;
} else {
bound = ((page - 1) * 6) + 6;
}
if (page < 0) {
page = 1;
}
if (jobs.size() == 0) {
message(sender, "There are no jobs available.");
return;
}
message(sender, "Job List [" + (page) + "/" + (pages) + "] - Total: " + jobs.size());
message(sender, "To Lock a Job: " + ChatColor.AQUA + "/job lock [job id]");
for (int i = ((page - 1) * 6); i < bound; i++) {
if (i >= jobs.size()) { break; }
Job job = jobs.get(i);
if (!job.isFinished()) {
message(sender, ChatColor.WHITE + "[ID: " + ChatColor.GOLD + job.getId() + ChatColor.WHITE + "] " + job.getName() + (job.getLock() != null ? ChatColor.GREEN + " (Locked By: " + ChatColor.AQUA + job.getLock() + ChatColor.GREEN + ")" + ChatColor.WHITE : "") + ": " + ChatColor.AQUA + job.getDescription());
}
}
}
|
diff --git a/tika-thrift/src/main/java/it/tika/TikaServiceImpl.java b/tika-thrift/src/main/java/it/tika/TikaServiceImpl.java
index 5d2bead..509f405 100644
--- a/tika-thrift/src/main/java/it/tika/TikaServiceImpl.java
+++ b/tika-thrift/src/main/java/it/tika/TikaServiceImpl.java
@@ -1,49 +1,49 @@
package it.tika;
import flipdroid.grepper.URLAbstract;
import org.apache.thrift.TException;
import java.io.UnsupportedEncodingException;
/**
* Created by IntelliJ IDEA.
* User: Administrator
* Date: 8/10/11
* Time: 10:24 AM
* To change this template use File | Settings | File Templates.
*/
public class TikaServiceImpl implements TikaService.Iface {
private Tika tika = Tika.getInstance();
public TikaResponse fire(TikaRequest request) throws TikaException, TException {
String url = request.getUrl();
String urlDecoded = null;
try {
urlDecoded = java.net.URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
return null;
}
- URLAbstract result = tika.extract(urlDecoded, false);
+ URLAbstract result = tika.extract(urlDecoded, false,request.getReferencedFrom());
if (result == null)
throw new TikaException();
result.setUrl(urlDecoded);
TikaResponse response = new TikaResponse();
response.setContent(result.getContent());
response.setImages(result.getImages());
response.setTitle(result.getTitle());
response.setSuccess(true);
return response;
}
public static void main(String[] args) throws TException, TikaException {
TikaServiceImpl tikaService = new TikaServiceImpl();
TikaRequest request = new TikaRequest();
request.setUrl("http://www.ifanr.com/48929");
TikaResponse response = tikaService.fire(request);
System.out.println(response.getContent());
}
}
| true | true | public TikaResponse fire(TikaRequest request) throws TikaException, TException {
String url = request.getUrl();
String urlDecoded = null;
try {
urlDecoded = java.net.URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
return null;
}
URLAbstract result = tika.extract(urlDecoded, false);
if (result == null)
throw new TikaException();
result.setUrl(urlDecoded);
TikaResponse response = new TikaResponse();
response.setContent(result.getContent());
response.setImages(result.getImages());
response.setTitle(result.getTitle());
response.setSuccess(true);
return response;
}
| public TikaResponse fire(TikaRequest request) throws TikaException, TException {
String url = request.getUrl();
String urlDecoded = null;
try {
urlDecoded = java.net.URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
return null;
}
URLAbstract result = tika.extract(urlDecoded, false,request.getReferencedFrom());
if (result == null)
throw new TikaException();
result.setUrl(urlDecoded);
TikaResponse response = new TikaResponse();
response.setContent(result.getContent());
response.setImages(result.getImages());
response.setTitle(result.getTitle());
response.setSuccess(true);
return response;
}
|