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/org/freenetproject/freemail/ui/web/LogInToadlet.java b/src/org/freenetproject/freemail/ui/web/LogInToadlet.java index 6d3a912..0089050 100644 --- a/src/org/freenetproject/freemail/ui/web/LogInToadlet.java +++ b/src/org/freenetproject/freemail/ui/web/LogInToadlet.java @@ -1,130 +1,130 @@ /* * LogInToadlet.java * This file is part of Freemail * Copyright (C) 2011 Martin Nyhus * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.freenetproject.freemail.ui.web; import java.io.IOException; import java.net.URI; import java.util.NoSuchElementException; import javax.naming.SizeLimitExceededException; import org.freenetproject.freemail.AccountManager; import org.freenetproject.freemail.FreemailAccount; import org.freenetproject.freemail.l10n.FreemailL10n; import org.freenetproject.freemail.utils.Logger; import freenet.clients.http.PageNode; import freenet.clients.http.ToadletContext; import freenet.clients.http.ToadletContextClosedException; import freenet.pluginmanager.PluginRespirator; import freenet.support.HTMLNode; import freenet.support.api.HTTPRequest; public class LogInToadlet extends WebPage { private static final String PATH = WebInterface.PATH + "/Login"; private final AccountManager accountManager; public LogInToadlet(PluginRespirator pluginRespirator, AccountManager accountManager) { super(pluginRespirator); this.accountManager = accountManager; } @Override public String path() { return PATH; } static String getPath() { return PATH; } @Override public boolean isEnabled(ToadletContext ctx) { return ctx.isAllowedFullAccess() && !sessionManager.sessionExists(ctx); } @Override void makeWebPageGet(URI uri, HTTPRequest req, ToadletContext ctx, PageNode page) throws ToadletContextClosedException, IOException { HTMLNode pageNode = page.outer; HTMLNode contentNode = page.content; if(accountManager.getAllAccounts().size() > 0) { addLoginBox(contentNode); } addNewAccountBox(contentNode); writeHTMLReply(ctx, 200, "OK", pageNode.generate()); } private void addLoginBox(HTMLNode contentNode) { HTMLNode boxContent = addInfobox(contentNode, FreemailL10n.getString("Freemail.LoginToadlet.LoginBox")); HTMLNode loginForm = pluginRespirator.addFormChild(boxContent, LogInToadlet.getPath(), "login"); HTMLNode ownIdSelector = loginForm.addChild("select", "name", "OwnIdentityID"); for(FreemailAccount account : accountManager.getAllAccounts()) { //FIXME: Nickname might be ambiguous String nickname = account.getNickname(); if(nickname == null) { nickname = account.getIdentity(); } ownIdSelector.addChild("option", "value", account.getIdentity(), nickname); } loginForm.addChild("input", new String[] {"type", "name", "value"}, new String[] {"submit", "submit", FreemailL10n.getString("Freemail.LoginToadlet.LoginButton")}); } private void addNewAccountBox(HTMLNode parent) { HTMLNode boxContent = addInfobox(parent, "Add account"); boxContent.addChild("a", "href", AddAccountToadlet.getPath(), "You can add another account here"); } @Override void makeWebPagePost(URI uri, HTTPRequest req, ToadletContext ctx, PageNode page) throws ToadletContextClosedException, IOException { String identity; try { identity = req.getPartAsStringThrowing("OwnIdentityID", 64); } catch (SizeLimitExceededException e) { //Someone is deliberately passing bad data, or there is a bug in the PUT code Logger.error(this, "Got OwnIdentityID that was too long. First 100 bytes: " + req.getPartAsStringFailsafe("OwnIdentityID", 100)); //TODO: Write a better message writeHTMLReply(ctx, 200, "OK", "The request contained bad data. This is probably a bug in Freemail"); return; } catch (NoSuchElementException e) { //Someone is deliberately passing bad data, or there is a bug in the PUT code Logger.error(this, "Got POST request without OwnIdentityID"); //TODO: Write a better message writeHTMLReply(ctx, 200, "OK", "The request didn't contain the expected data. This is probably a bug in Freemail"); return; } sessionManager.createSession(accountManager.getAccount(identity).getIdentity(), ctx); - writeTemporaryRedirect(ctx, "Login successful, redirecting to home page", HomeToadlet.getPath()); + writeTemporaryRedirect(ctx, "Login successful, redirecting to inbox", InboxToadlet.getPath()); } @Override boolean requiresValidSession() { return false; } }
true
true
void makeWebPagePost(URI uri, HTTPRequest req, ToadletContext ctx, PageNode page) throws ToadletContextClosedException, IOException { String identity; try { identity = req.getPartAsStringThrowing("OwnIdentityID", 64); } catch (SizeLimitExceededException e) { //Someone is deliberately passing bad data, or there is a bug in the PUT code Logger.error(this, "Got OwnIdentityID that was too long. First 100 bytes: " + req.getPartAsStringFailsafe("OwnIdentityID", 100)); //TODO: Write a better message writeHTMLReply(ctx, 200, "OK", "The request contained bad data. This is probably a bug in Freemail"); return; } catch (NoSuchElementException e) { //Someone is deliberately passing bad data, or there is a bug in the PUT code Logger.error(this, "Got POST request without OwnIdentityID"); //TODO: Write a better message writeHTMLReply(ctx, 200, "OK", "The request didn't contain the expected data. This is probably a bug in Freemail"); return; } sessionManager.createSession(accountManager.getAccount(identity).getIdentity(), ctx); writeTemporaryRedirect(ctx, "Login successful, redirecting to home page", HomeToadlet.getPath()); }
void makeWebPagePost(URI uri, HTTPRequest req, ToadletContext ctx, PageNode page) throws ToadletContextClosedException, IOException { String identity; try { identity = req.getPartAsStringThrowing("OwnIdentityID", 64); } catch (SizeLimitExceededException e) { //Someone is deliberately passing bad data, or there is a bug in the PUT code Logger.error(this, "Got OwnIdentityID that was too long. First 100 bytes: " + req.getPartAsStringFailsafe("OwnIdentityID", 100)); //TODO: Write a better message writeHTMLReply(ctx, 200, "OK", "The request contained bad data. This is probably a bug in Freemail"); return; } catch (NoSuchElementException e) { //Someone is deliberately passing bad data, or there is a bug in the PUT code Logger.error(this, "Got POST request without OwnIdentityID"); //TODO: Write a better message writeHTMLReply(ctx, 200, "OK", "The request didn't contain the expected data. This is probably a bug in Freemail"); return; } sessionManager.createSession(accountManager.getAccount(identity).getIdentity(), ctx); writeTemporaryRedirect(ctx, "Login successful, redirecting to inbox", InboxToadlet.getPath()); }
diff --git a/platform/android/src/org/geometerplus/zlibrary/ui/android/library/BugReportActivity.java b/platform/android/src/org/geometerplus/zlibrary/ui/android/library/BugReportActivity.java index 71c707ba..f5acfcec 100644 --- a/platform/android/src/org/geometerplus/zlibrary/ui/android/library/BugReportActivity.java +++ b/platform/android/src/org/geometerplus/zlibrary/ui/android/library/BugReportActivity.java @@ -1,70 +1,70 @@ /* * Copyright (C) 2007-2009 Geometer Plus <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.zlibrary.ui.android.library; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.text.method.ScrollingMovementMethod; import android.graphics.Typeface; import org.geometerplus.zlibrary.ui.android.R; public class BugReportActivity extends Activity { static final String STACKTRACE = "fbreader.stacktrace"; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bug_report_view); final String stackTrace = getIntent().getStringExtra(STACKTRACE); final TextView reportTextView = (TextView)findViewById(R.id.report_text); reportTextView.setMovementMethod(ScrollingMovementMethod.getInstance()); reportTextView.setClickable(false); reportTextView.setLongClickable(false); - final String versionName = ZLibrary.Instance().getVersionName(); + final String versionName = ZLAndroidLibrary.Instance().getVersionName(); reportTextView.append("FBReader " + versionName + " has been crached, sorry. You can help to fix this bug by sending the report below to FBReader developers. The report will be sent by e-mail. Thank you in advance!\n\n"); reportTextView.append(stackTrace); findViewById(R.id.send_report).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" }); sendIntent.putExtra(Intent.EXTRA_TEXT, stackTrace); sendIntent.putExtra(Intent.EXTRA_SUBJECT, "FBReader " + versionName + " exception report"); sendIntent.setType("message/rfc822"); startActivity(sendIntent); finish(); } } ); findViewById(R.id.cancel_report).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { finish(); } } ); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bug_report_view); final String stackTrace = getIntent().getStringExtra(STACKTRACE); final TextView reportTextView = (TextView)findViewById(R.id.report_text); reportTextView.setMovementMethod(ScrollingMovementMethod.getInstance()); reportTextView.setClickable(false); reportTextView.setLongClickable(false); final String versionName = ZLibrary.Instance().getVersionName(); reportTextView.append("FBReader " + versionName + " has been crached, sorry. You can help to fix this bug by sending the report below to FBReader developers. The report will be sent by e-mail. Thank you in advance!\n\n"); reportTextView.append(stackTrace); findViewById(R.id.send_report).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" }); sendIntent.putExtra(Intent.EXTRA_TEXT, stackTrace); sendIntent.putExtra(Intent.EXTRA_SUBJECT, "FBReader " + versionName + " exception report"); sendIntent.setType("message/rfc822"); startActivity(sendIntent); finish(); } } ); findViewById(R.id.cancel_report).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { finish(); } } ); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bug_report_view); final String stackTrace = getIntent().getStringExtra(STACKTRACE); final TextView reportTextView = (TextView)findViewById(R.id.report_text); reportTextView.setMovementMethod(ScrollingMovementMethod.getInstance()); reportTextView.setClickable(false); reportTextView.setLongClickable(false); final String versionName = ZLAndroidLibrary.Instance().getVersionName(); reportTextView.append("FBReader " + versionName + " has been crached, sorry. You can help to fix this bug by sending the report below to FBReader developers. The report will be sent by e-mail. Thank you in advance!\n\n"); reportTextView.append(stackTrace); findViewById(R.id.send_report).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" }); sendIntent.putExtra(Intent.EXTRA_TEXT, stackTrace); sendIntent.putExtra(Intent.EXTRA_SUBJECT, "FBReader " + versionName + " exception report"); sendIntent.setType("message/rfc822"); startActivity(sendIntent); finish(); } } ); findViewById(R.id.cancel_report).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { finish(); } } ); }
diff --git a/cocos2dx-common/java/org/cocos2dx/lib/RichLabelBitmap.java b/cocos2dx-common/java/org/cocos2dx/lib/RichLabelBitmap.java index 63a596b..87b954d 100644 --- a/cocos2dx-common/java/org/cocos2dx/lib/RichLabelBitmap.java +++ b/cocos2dx-common/java/org/cocos2dx/lib/RichLabelBitmap.java @@ -1,997 +1,1001 @@ /**************************************************************************** Author: Luma ([email protected]) https://github.com/stubma/cocos2dx-common Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ package org.cocos2dx.lib; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Typeface; import android.text.Layout.Alignment; import android.text.Spannable; import android.text.SpannableString; import android.text.StaticLayout; import android.text.TextPaint; import android.text.style.AbsoluteSizeSpan; import android.text.style.DynamicDrawableSpan; import android.text.style.ForegroundColorSpan; import android.text.style.ImageSpan; import android.text.style.TypefaceSpan; import android.text.style.UnderlineSpan; import android.util.Log; public class RichLabelBitmap { /* The values are the same as cocos2dx/platform/CCImage.h. */ private static final int HORIZONTALALIGN_LEFT = 1; private static final int HORIZONTALALIGN_RIGHT = 2; private static final int HORIZONTALALIGN_CENTER = 3; private static final int VERTICALALIGN_TOP = 1; private static final int VERTICALALIGN_BOTTOM = 2; private static final int VERTICALALIGN_CENTER = 3; private static final char TAG_START = '['; private static final char TAG_END = ']'; private enum SpanType { UNKNOWN, COLOR, FONT, SIZE, BOLD, ITALIC, UNDERLINE, IMAGE, LINK } // link meta info final static class LinkMeta { int normalBgColor; int selectedBgColor; // the tag of link, multiple link can have same tag (in line break situation) int tag; // link rect area float x; float y; float width; float height; } // span info final static class Span { public SpanType type; public boolean close; public int pos; // only for color public int color; // only for size public float fontSize; // only for font public String fontName; // only for image public String imageName; public float scaleX; public float scaleY; public float width; public float height; // for link tag int normalBgColor; int selectedBgColor; } // tag parse result final static class TagParseResult { SpanType type; boolean close; int endTagPos; int dataStart; int dataEnd; } // tag parse state private enum TagParseState { READY, START_TAG, CLOSE_TAG, EQUAL, SUCCESS, FAIL } static class CustomTypefaceSpan extends TypefaceSpan { private final Typeface newType; public CustomTypefaceSpan(String family, Typeface type) { super(family); newType = type; } @Override public void updateDrawState(TextPaint ds) { applyCustomTypeFace(ds, newType); } @Override public void updateMeasureState(TextPaint paint) { applyCustomTypeFace(paint, newType); } private void applyCustomTypeFace(Paint paint, Typeface tf) { int oldStyle; Typeface old = paint.getTypeface(); if (old == null) { oldStyle = 0; } else { oldStyle = old.getStyle(); } int fake = oldStyle & ~tf.getStyle(); if ((fake & Typeface.BOLD) != 0) { paint.setFakeBoldText(true); } if ((fake & Typeface.ITALIC) != 0) { paint.setTextSkewX(-0.25f); } paint.setTypeface(tf); } } public static void createRichLabelBitmap(String pString, final String pFontName, final int pFontSize, final float fontTintR, final float fontTintG, final float fontTintB, final int pAlignment, final int pWidth, final int pHeight, final boolean shadow, final float shadowDX, final float shadowDY, final int shadowColor, final float shadowBlur, final boolean stroke, final float strokeR, final float strokeG, final float strokeB, final float strokeSize, float contentScaleFactor, boolean sizeOnly) { // reset bitmap dc nativeResetBitmapDC(); // extract span info and return text without span style List<Span> spans = new ArrayList<Span>(); String plain = buildSpan(pString, spans); // alignment int horizontalAlignment = pAlignment & 0x0F; int verticalAlignment = (pAlignment >> 4) & 0x0F; Alignment align = Alignment.ALIGN_NORMAL; switch(horizontalAlignment) { case HORIZONTALALIGN_CENTER: align = Alignment.ALIGN_CENTER; break; case HORIZONTALALIGN_RIGHT: align = Alignment.ALIGN_OPPOSITE; break; } // create paint TextPaint paint = new TextPaint(); paint.setColor(Color.WHITE); paint.setTextSize(pFontSize); paint.setAntiAlias(true); if (pFontName.endsWith(".ttf")) { try { Typeface typeFace = Cocos2dxTypefaces.get(Cocos2dxActivity.getContext(), pFontName); paint.setTypeface(typeFace); } catch (final Exception e) { Log.e("ColorLabelBitmap", "error to create ttf type face: " + pFontName); /* The file may not find, use system font. */ paint.setTypeface(Typeface.create(pFontName, Typeface.NORMAL)); } } else { paint.setTypeface(Typeface.create(pFontName, Typeface.NORMAL)); } // shadow // shadowBlur can be zero in android Paint, so set a min value to 1 if (shadow) { paint.setShadowLayer(Math.max(shadowBlur, 1), shadowDX, shadowDY, shadowColor); } // compute the padding needed by shadow and stroke float shadowStrokePaddingX = 0.0f; float shadowStrokePaddingY = 0.0f; if (stroke) { shadowStrokePaddingX = (float)Math.ceil(strokeSize); shadowStrokePaddingY = (float)Math.ceil(strokeSize); } if (shadow) { shadowStrokePaddingX = Math.max(shadowStrokePaddingX, (float)Math.abs(shadowDX)); shadowStrokePaddingY = Math.max(shadowStrokePaddingY, (float)Math.abs(shadowDY)); } // stack of color and font int defaultColor = 0xff000000 | ((int)(fontTintR * 255) << 16) | ((int)(fontTintG * 255) << 8) | (int)(fontTintB * 255); Typeface defaultFont = Typeface.DEFAULT; Stack<Integer> colorStack = new Stack<Integer>(); Stack<Typeface> fontStack = new Stack<Typeface>(); Stack<Float> fontSizeStack = new Stack<Float>(); colorStack.push(defaultColor); fontStack.push(defaultFont); fontSizeStack.push(pFontSize / contentScaleFactor); // build spannable string Map<String, Bitmap> imageMap = new HashMap<String, Bitmap>(); int colorStart = 0; int fontStart = 0; int sizeStart = 0; int underlineStart = -1; Span openSpan = null; SpannableString rich = new SpannableString(plain); for(Span span : spans) { if(span.close) { switch(span.type) { case COLOR: { int curColor = colorStack.pop(); if(span.pos > colorStart) { rich.setSpan(new ForegroundColorSpan(curColor), colorStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // start need to be reset colorStart = span.pos; } break; } case FONT: case BOLD: case ITALIC: { // set previous span Typeface font = fontStack.pop(); if(span.pos > fontStart && font != null) { rich.setSpan(new CustomTypefaceSpan("", font), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); fontStart = span.pos; } break; } case SIZE: { float size = fontSizeStack.pop(); if(span.pos > sizeStart) { rich.setSpan(new AbsoluteSizeSpan((int)(size * contentScaleFactor)), sizeStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sizeStart = span.pos; } break; } case UNDERLINE: { if(underlineStart > -1) { rich.setSpan(new UnderlineSpan(), underlineStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); underlineStart = -1; } break; } case IMAGE: { if(openSpan != null) { AssetManager am = Cocos2dxHelper.getAssetManager(); InputStream is = null; try { is = am.open(openSpan.imageName); Bitmap bitmap = BitmapFactory.decodeStream(is); - if(openSpan.scaleX != 1 || openSpan.scaleY != 1) { + if(openSpan.scaleX != 1 || openSpan.scaleY != 1 || contentScaleFactor != 1) { + float dstW = openSpan.width != 0 ? (int)openSpan.width : (int)(bitmap.getWidth() * openSpan.scaleX); + float dstH = openSpan.height != 0 ? (int)openSpan.height : (int)(bitmap.getHeight() * openSpan.scaleY); + dstW *= contentScaleFactor; + dstH *= contentScaleFactor; Bitmap scaled = Bitmap.createScaledBitmap(bitmap, - openSpan.width != 0 ? (int)openSpan.width : (int)(bitmap.getWidth() * openSpan.scaleX), - openSpan.height != 0 ? (int)openSpan.height : (int)(bitmap.getHeight() * openSpan.scaleY), + (int)dstW, + (int)dstH, true); bitmap.recycle(); bitmap = scaled; } imageMap.put(span.imageName, bitmap); rich.setSpan(new ImageSpan(bitmap, DynamicDrawableSpan.ALIGN_BASELINE), openSpan.pos, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Throwable e) { } finally { if(is != null) { try { is.close(); } catch (IOException e) { } } } openSpan = null; } break; } } } else { switch(span.type) { case COLOR: { // process previous run if(span.pos > colorStart) { int curColor = colorStack.peek(); rich.setSpan(new ForegroundColorSpan(curColor), colorStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // start need to be reset colorStart = span.pos; } // push color colorStack.push(span.color); break; } case FONT: { // set previous span Typeface curFont = fontStack.peek(); if(span.pos > fontStart) { rich.setSpan(new CustomTypefaceSpan("", curFont), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); fontStart = span.pos; } // create the font Typeface font = null; if (span.fontName.endsWith(".ttf")) { try { font = Cocos2dxTypefaces.get(Cocos2dxActivity.getContext(), span.fontName); } catch (final Exception e) { } } else { font = Typeface.create(span.fontName, Typeface.NORMAL); if(font == null) { font = Typeface.DEFAULT; } } fontStack.push(font); break; } case SIZE: { // set previous span if(span.pos > sizeStart) { float size = fontSizeStack.peek(); rich.setSpan(new AbsoluteSizeSpan((int)(size * contentScaleFactor)), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sizeStart = span.pos; } // push new size fontSizeStack.push(span.fontSize); break; } case BOLD: { // set previous span Typeface curFont = fontStack.peek(); if(span.pos > fontStart) { rich.setSpan(new CustomTypefaceSpan("", curFont), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); fontStart = span.pos; } // create new font Typeface font = Typeface.create(curFont, Typeface.BOLD | curFont.getStyle()); fontStack.push(font); break; } case ITALIC: { // set previous span Typeface curFont = fontStack.peek(); if(span.pos > fontStart) { rich.setSpan(new CustomTypefaceSpan("", curFont), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); fontStart = span.pos; } // create new font Typeface font = Typeface.create(curFont, Typeface.ITALIC | curFont.getStyle()); fontStack.push(font); break; } case UNDERLINE: { underlineStart = span.pos; break; } case IMAGE: { openSpan = span; break; } } } } // last segment if(plain.length() > colorStart) { int curColor = colorStack.peek(); rich.setSpan(new ForegroundColorSpan(curColor), colorStart, plain.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } if(plain.length() > sizeStart) { float size = fontSizeStack.peek(); rich.setSpan(new AbsoluteSizeSpan((int)(size * contentScaleFactor)), fontStart, plain.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } if(plain.length() > fontStart) { Typeface curFont = fontStack.peek(); rich.setSpan(new CustomTypefaceSpan("", curFont), fontStart, plain.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } // layout this text StaticLayout layout = new StaticLayout(rich, paint, pWidth <= 0 ? (int)StaticLayout.getDesiredWidth(rich, paint) : pWidth, align, 1, 0, false); // size of layout int width = layout.getWidth(); int height = layout.getHeight(); // add padding of stroke width += shadowStrokePaddingX; height += shadowStrokePaddingY; // text origin int startY = 0; int startX = 0; if (pHeight > height) { // vertical alignment if (verticalAlignment == VERTICALALIGN_TOP) { startY = 0; } else if (verticalAlignment == VERTICALALIGN_CENTER) { startY = (pHeight - height) / 2; } else { startY = pHeight - height; } } if(shadow) { if(shadowDY < 0) { startY -= shadowDY; } if(shadowDX < 0) { startX -= shadowDX; } } // adjust layout if(pWidth > 0 && pWidth > width) width = pWidth; if(pHeight > 0 && pHeight > height) height = pHeight; // if only measure, just pass size to native layer // if not, render a bitmap if(!sizeOnly) { // save padding nativeSaveShadowStrokePadding(startX, Math.max(0, height - layout.getHeight() - startY)); // create bitmap and canvas Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas c = new Canvas(bitmap); // translate for vertical alignment c.translate(startX, startY); // draw text - layout.draw(c); + layout.draw(c); // draw again if stroke is enabled if(stroke) { // reset paint to stroke mode paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(strokeSize); paint.setARGB(255, (int)strokeR * 255, (int)strokeG * 255, (int)strokeB * 255); paint.clearShadowLayer(); // clear color and underline span for(ForegroundColorSpan span : rich.getSpans(0, rich.length(), ForegroundColorSpan.class)) { rich.removeSpan(span); } for(UnderlineSpan span : rich.getSpans(0, rich.length(), UnderlineSpan.class)) { rich.removeSpan(span); } layout.draw(c); } // extract link meta info extractLinkMeta(layout, spans, contentScaleFactor); // transfer bitmap data to native layer, and release bitmap when done initNativeObject(bitmap); bitmap.recycle(); } else { nativeInitBitmapDC(width, height, null); } // release cached images for(Bitmap b : imageMap.values()) { if(!b.isRecycled()) { b.recycle(); } } } private static void extractLinkMeta(StaticLayout layout, List<Span> spans, float contentScaleFactor) { // get line count int lineCount = layout.getLineCount(); // total height float totalHeight = layout.getHeight(); // get line origin PointF[] origin = new PointF[lineCount]; for(int i = 0; i < lineCount; i++) { origin[i] = new PointF(); origin[i].x = layout.getLineLeft(i) / contentScaleFactor; origin[i].y = (totalHeight - layout.getLineBaseline(i)) / contentScaleFactor; } // get line range Point[] range = new Point[lineCount]; for(int i = 0; i < lineCount; i++) { range[i] = new Point(); range[i].x = layout.getLineStart(i); range[i].y = layout.getLineEnd(i); } // get rect area for every link, or link part LinkMeta meta = new LinkMeta(); int tag = 0; int linkStart = 0, linkEnd = 0; int startLine = 0, endLine = 0; for(Span span : spans) { if(span.type == SpanType.LINK) { if(!span.close) { // get start pos linkStart = span.pos; // save color info meta.normalBgColor = span.normalBgColor; meta.selectedBgColor = span.selectedBgColor; } else { // remember end pos linkEnd = span.pos; // find out the line for start and end pos for (int i = 0; i < lineCount; i++) { if(linkStart >= range[i].x && linkStart < range[i].y) { startLine = i; } if(linkEnd >= range[i].x && linkEnd < range[i].y) { endLine = i; break; } } // get rect area int firstLine = startLine; while(startLine <= endLine) { float ascent = -layout.getLineAscent(startLine) / contentScaleFactor; float descent = layout.getLineDescent(startLine) / contentScaleFactor; int charEnd = linkEnd; if(startLine < endLine) charEnd = range[startLine].y; float startOffsetX = startLine > firstLine ? (layout.getLineLeft(startLine) / contentScaleFactor) : (layout.getPrimaryHorizontal(linkStart) / contentScaleFactor); float endOffsetX = startLine < endLine ? (layout.getLineRight(startLine) / contentScaleFactor) : (layout.getPrimaryHorizontal(charEnd) / contentScaleFactor); meta.x = startOffsetX; meta.y = origin[startLine].y - descent; meta.width = endOffsetX - meta.x; meta.height = descent + ascent; meta.tag = tag; // push meta nativeSaveLinkMeta(meta.normalBgColor, meta.selectedBgColor, meta.x, meta.y, meta.width, meta.height, meta.tag); // move line startLine++; // move start linkStart = charEnd; } // increase tag tag++; } } } } // if parse failed, endTagPos will be len, otherwise it is end tag position private static TagParseResult checkTag(String p, int start) { TagParseResult r = new TagParseResult(); r.type = SpanType.UNKNOWN; TagParseState state = TagParseState.READY; int tagNameStart = 0, tagNameEnd = 0; r.close = false; int len = p.length(); r.endTagPos = len; r.dataStart = -1; int i = start; while(i < len) { switch (state) { case READY: if(p.charAt(i) == TAG_START) { state = TagParseState.START_TAG; tagNameStart = ++i; } else { state = TagParseState.FAIL; } break; case START_TAG: if((i == start + 1) && p.charAt(i) == '/') { state = TagParseState.CLOSE_TAG; r.close = true; tagNameStart = ++i; } else if(p.charAt(i) == '=') { state = TagParseState.EQUAL; tagNameEnd = i++; r.type = checkTagName(p, tagNameStart, tagNameEnd); r.dataStart = i; } else if(p.charAt(i) == TAG_END) { state = TagParseState.SUCCESS; r.endTagPos = i; r.dataEnd = i; tagNameEnd = i; if(r.type == SpanType.UNKNOWN) { r.type = checkTagName(p, tagNameStart, tagNameEnd); } } else if(p.charAt(i) == ' ') { state = TagParseState.EQUAL; tagNameEnd = i++; r.type = checkTagName(p, tagNameStart, tagNameEnd); r.dataStart = i; } else { i++; } break; case CLOSE_TAG: if(p.charAt(i) == TAG_END) { state = TagParseState.SUCCESS; r.endTagPos = i; tagNameEnd = i; r.type = checkTagName(p, tagNameStart, tagNameEnd); } else { i++; } break; case EQUAL: if(p.charAt(i) == TAG_END) { state = TagParseState.SUCCESS; r.endTagPos = i; r.dataEnd = i; } else { i++; } break; default: break; } if(state == TagParseState.FAIL || state == TagParseState.SUCCESS) break; } if(state != TagParseState.SUCCESS) r.type = SpanType.UNKNOWN; return r; } private static SpanType checkTagName(String p, int start, int end) { int len = end - start; switch(len) { case 1: if(p.charAt(start) == 'b') { return SpanType.BOLD; } else if(p.charAt(start) == 'i') { return SpanType.ITALIC; } else if(p.charAt(start) == 'u') { return SpanType.UNDERLINE; } break; case 4: if(p.charAt(start) == 'f' && p.charAt(start + 1) == 'o' && p.charAt(start + 2) == 'n' && p.charAt(start + 3) == 't') { return SpanType.FONT; } else if(p.charAt(start) == 's' && p.charAt(start + 1) == 'i' && p.charAt(start + 2) == 'z' && p.charAt(start + 3) == 'e') { return SpanType.SIZE; } else if(p.charAt(start) == 'l' && p.charAt(start + 1) == 'i' && p.charAt(start + 2) == 'n' && p.charAt(start + 3) == 'k') { return SpanType.LINK; } case 5: if(p.charAt(start) == 'c' && p.charAt(start + 1) == 'o' && p.charAt(start + 2) == 'l' && p.charAt(start + 3) == 'o' && p.charAt(start + 4) == 'r') { return SpanType.COLOR; } else if(p.charAt(start) == 'i' && p.charAt(start + 1) == 'm' && p.charAt(start + 2) == 'a' && p.charAt(start + 3) == 'g' && p.charAt(start + 4) == 'e') { return SpanType.IMAGE; } break; } return SpanType.UNKNOWN; } private static String buildSpan(String text, List<Span> spans) { int uniLen = text.length(); StringBuilder plain = new StringBuilder(); for(int i = 0; i < uniLen; i++) { char c = text.charAt(i); switch(c) { case '\\': if(i < uniLen - 1) { char cc = text.charAt(i + 1); if(cc == '[' || cc == ']') { plain.append(cc); i++; } } else { plain.append(c); } break; case TAG_START: { // parse the tag Span span = new Span(); TagParseResult r = checkTag(text, i); // fill span info do { // if type is unknown, discard if(r.type == SpanType.UNKNOWN) break; // parse span data span.type = r.type; span.close = r.close; span.pos = plain.length(); if(!r.close) { switch(span.type) { case COLOR: span.color = parseColor(text, r.dataStart, r.dataEnd - r.dataStart); break; case FONT: span.fontName = text.substring(r.dataStart, r.dataEnd); break; case SIZE: try { span.fontSize = Integer.parseInt(text.substring(r.dataStart, r.dataEnd)); } catch (NumberFormatException e) { span.fontSize = 16; } break; case IMAGE: { String name = text.substring(r.dataStart, r.dataEnd); String[] parts = name.split(" "); span.imageName = parts[0]; span.scaleX = span.scaleY = 1; span.width = span.height = 0; // if parts more than one, parse attributes if(parts.length > 1) { for(int j = 1; j < parts.length; j++) { String[] pair = parts[j].split("="); if(pair.length == 2) { try { if("scale".equals(pair[0])) { span.scaleX = span.scaleY = Float.parseFloat(pair[1]); } else if("scalex".equals(pair[0])) { span.scaleX = Float.parseFloat(pair[1]); } else if("scaley".equals(pair[0])) { span.scaleY = Float.parseFloat(pair[1]); } else if("w".equals(pair[0])) { span.width = Float.parseFloat(pair[1]); } else if("h".equals(pair[0])) { span.height = Float.parseFloat(pair[1]); } } catch (NumberFormatException e) { } } } } break; } case LINK: { String v = text.substring(r.dataStart, r.dataEnd); String[] parts = v.split(" "); for(String part : parts) { String[] pair = part.split("="); if(pair.length == 2) { if("bg".equals(pair[0])) { span.normalBgColor = parseColor(pair[1], 0, pair[1].length()); } else if("bg_click".equals(pair[0])) { span.selectedBgColor = parseColor(pair[1], 0, pair[1].length()); } } } break; } default: break; } } // add span spans.add(span); // set i pos i = r.endTagPos; } while(false); break; } case TAG_END: // just discard it break; default: plain.append(c); break; } } // return plain str return plain.toString(); } private static int parseColor(String text, int start, int len) { int color = 0; int end = start + len; for(int i = start; i < end; i++) { color <<= 4; char c = text.charAt(i); if(c >= '0' && c <= '9') { color |= c - '0'; } else if(c >= 'a' && c <= 'f') { color |= c - 'a' + 10; } else if(c >= 'A' && c <= 'F') { color |= c - 'A' + 10; } } return color; } private static byte[] getPixels(final Bitmap pBitmap) { if (pBitmap != null) { final byte[] pixels = new byte[pBitmap.getWidth() * pBitmap.getHeight() * 4]; final ByteBuffer buf = ByteBuffer.wrap(pixels); buf.order(ByteOrder.nativeOrder()); pBitmap.copyPixelsToBuffer(buf); return pixels; } return null; } private static void initNativeObject(final Bitmap pBitmap) { final byte[] pixels = getPixels(pBitmap); if (pixels == null) { return; } nativeInitBitmapDC(pBitmap.getWidth(), pBitmap.getHeight(), pixels); } private static native void nativeInitBitmapDC(int pWidth, int pHeight, byte[] pPixels); private native static void nativeSaveLinkMeta(int normalBgColor, int selectedBgColor, float x, float y, float width, float height, int tag); private native static void nativeSaveShadowStrokePadding(float x, float y); private native static void nativeResetBitmapDC(); }
false
true
public static void createRichLabelBitmap(String pString, final String pFontName, final int pFontSize, final float fontTintR, final float fontTintG, final float fontTintB, final int pAlignment, final int pWidth, final int pHeight, final boolean shadow, final float shadowDX, final float shadowDY, final int shadowColor, final float shadowBlur, final boolean stroke, final float strokeR, final float strokeG, final float strokeB, final float strokeSize, float contentScaleFactor, boolean sizeOnly) { // reset bitmap dc nativeResetBitmapDC(); // extract span info and return text without span style List<Span> spans = new ArrayList<Span>(); String plain = buildSpan(pString, spans); // alignment int horizontalAlignment = pAlignment & 0x0F; int verticalAlignment = (pAlignment >> 4) & 0x0F; Alignment align = Alignment.ALIGN_NORMAL; switch(horizontalAlignment) { case HORIZONTALALIGN_CENTER: align = Alignment.ALIGN_CENTER; break; case HORIZONTALALIGN_RIGHT: align = Alignment.ALIGN_OPPOSITE; break; } // create paint TextPaint paint = new TextPaint(); paint.setColor(Color.WHITE); paint.setTextSize(pFontSize); paint.setAntiAlias(true); if (pFontName.endsWith(".ttf")) { try { Typeface typeFace = Cocos2dxTypefaces.get(Cocos2dxActivity.getContext(), pFontName); paint.setTypeface(typeFace); } catch (final Exception e) { Log.e("ColorLabelBitmap", "error to create ttf type face: " + pFontName); /* The file may not find, use system font. */ paint.setTypeface(Typeface.create(pFontName, Typeface.NORMAL)); } } else { paint.setTypeface(Typeface.create(pFontName, Typeface.NORMAL)); } // shadow // shadowBlur can be zero in android Paint, so set a min value to 1 if (shadow) { paint.setShadowLayer(Math.max(shadowBlur, 1), shadowDX, shadowDY, shadowColor); } // compute the padding needed by shadow and stroke float shadowStrokePaddingX = 0.0f; float shadowStrokePaddingY = 0.0f; if (stroke) { shadowStrokePaddingX = (float)Math.ceil(strokeSize); shadowStrokePaddingY = (float)Math.ceil(strokeSize); } if (shadow) { shadowStrokePaddingX = Math.max(shadowStrokePaddingX, (float)Math.abs(shadowDX)); shadowStrokePaddingY = Math.max(shadowStrokePaddingY, (float)Math.abs(shadowDY)); } // stack of color and font int defaultColor = 0xff000000 | ((int)(fontTintR * 255) << 16) | ((int)(fontTintG * 255) << 8) | (int)(fontTintB * 255); Typeface defaultFont = Typeface.DEFAULT; Stack<Integer> colorStack = new Stack<Integer>(); Stack<Typeface> fontStack = new Stack<Typeface>(); Stack<Float> fontSizeStack = new Stack<Float>(); colorStack.push(defaultColor); fontStack.push(defaultFont); fontSizeStack.push(pFontSize / contentScaleFactor); // build spannable string Map<String, Bitmap> imageMap = new HashMap<String, Bitmap>(); int colorStart = 0; int fontStart = 0; int sizeStart = 0; int underlineStart = -1; Span openSpan = null; SpannableString rich = new SpannableString(plain); for(Span span : spans) { if(span.close) { switch(span.type) { case COLOR: { int curColor = colorStack.pop(); if(span.pos > colorStart) { rich.setSpan(new ForegroundColorSpan(curColor), colorStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // start need to be reset colorStart = span.pos; } break; } case FONT: case BOLD: case ITALIC: { // set previous span Typeface font = fontStack.pop(); if(span.pos > fontStart && font != null) { rich.setSpan(new CustomTypefaceSpan("", font), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); fontStart = span.pos; } break; } case SIZE: { float size = fontSizeStack.pop(); if(span.pos > sizeStart) { rich.setSpan(new AbsoluteSizeSpan((int)(size * contentScaleFactor)), sizeStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sizeStart = span.pos; } break; } case UNDERLINE: { if(underlineStart > -1) { rich.setSpan(new UnderlineSpan(), underlineStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); underlineStart = -1; } break; } case IMAGE: { if(openSpan != null) { AssetManager am = Cocos2dxHelper.getAssetManager(); InputStream is = null; try { is = am.open(openSpan.imageName); Bitmap bitmap = BitmapFactory.decodeStream(is); if(openSpan.scaleX != 1 || openSpan.scaleY != 1) { Bitmap scaled = Bitmap.createScaledBitmap(bitmap, openSpan.width != 0 ? (int)openSpan.width : (int)(bitmap.getWidth() * openSpan.scaleX), openSpan.height != 0 ? (int)openSpan.height : (int)(bitmap.getHeight() * openSpan.scaleY), true); bitmap.recycle(); bitmap = scaled; } imageMap.put(span.imageName, bitmap); rich.setSpan(new ImageSpan(bitmap, DynamicDrawableSpan.ALIGN_BASELINE), openSpan.pos, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Throwable e) { } finally { if(is != null) { try { is.close(); } catch (IOException e) { } } } openSpan = null; } break; } } } else { switch(span.type) { case COLOR: { // process previous run if(span.pos > colorStart) { int curColor = colorStack.peek(); rich.setSpan(new ForegroundColorSpan(curColor), colorStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // start need to be reset colorStart = span.pos; } // push color colorStack.push(span.color); break; } case FONT: { // set previous span Typeface curFont = fontStack.peek(); if(span.pos > fontStart) { rich.setSpan(new CustomTypefaceSpan("", curFont), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); fontStart = span.pos; } // create the font Typeface font = null; if (span.fontName.endsWith(".ttf")) { try { font = Cocos2dxTypefaces.get(Cocos2dxActivity.getContext(), span.fontName); } catch (final Exception e) { } } else { font = Typeface.create(span.fontName, Typeface.NORMAL); if(font == null) { font = Typeface.DEFAULT; } } fontStack.push(font); break; } case SIZE: { // set previous span if(span.pos > sizeStart) { float size = fontSizeStack.peek(); rich.setSpan(new AbsoluteSizeSpan((int)(size * contentScaleFactor)), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sizeStart = span.pos; } // push new size fontSizeStack.push(span.fontSize); break; } case BOLD: { // set previous span Typeface curFont = fontStack.peek(); if(span.pos > fontStart) { rich.setSpan(new CustomTypefaceSpan("", curFont), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); fontStart = span.pos; } // create new font Typeface font = Typeface.create(curFont, Typeface.BOLD | curFont.getStyle()); fontStack.push(font); break; } case ITALIC: { // set previous span Typeface curFont = fontStack.peek(); if(span.pos > fontStart) { rich.setSpan(new CustomTypefaceSpan("", curFont), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); fontStart = span.pos; } // create new font Typeface font = Typeface.create(curFont, Typeface.ITALIC | curFont.getStyle()); fontStack.push(font); break; } case UNDERLINE: { underlineStart = span.pos; break; } case IMAGE: { openSpan = span; break; } } } } // last segment if(plain.length() > colorStart) { int curColor = colorStack.peek(); rich.setSpan(new ForegroundColorSpan(curColor), colorStart, plain.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } if(plain.length() > sizeStart) { float size = fontSizeStack.peek(); rich.setSpan(new AbsoluteSizeSpan((int)(size * contentScaleFactor)), fontStart, plain.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } if(plain.length() > fontStart) { Typeface curFont = fontStack.peek(); rich.setSpan(new CustomTypefaceSpan("", curFont), fontStart, plain.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } // layout this text StaticLayout layout = new StaticLayout(rich, paint, pWidth <= 0 ? (int)StaticLayout.getDesiredWidth(rich, paint) : pWidth, align, 1, 0, false); // size of layout int width = layout.getWidth(); int height = layout.getHeight(); // add padding of stroke width += shadowStrokePaddingX; height += shadowStrokePaddingY; // text origin int startY = 0; int startX = 0; if (pHeight > height) { // vertical alignment if (verticalAlignment == VERTICALALIGN_TOP) { startY = 0; } else if (verticalAlignment == VERTICALALIGN_CENTER) { startY = (pHeight - height) / 2; } else { startY = pHeight - height; } } if(shadow) { if(shadowDY < 0) { startY -= shadowDY; } if(shadowDX < 0) { startX -= shadowDX; } } // adjust layout if(pWidth > 0 && pWidth > width) width = pWidth; if(pHeight > 0 && pHeight > height) height = pHeight; // if only measure, just pass size to native layer // if not, render a bitmap if(!sizeOnly) { // save padding nativeSaveShadowStrokePadding(startX, Math.max(0, height - layout.getHeight() - startY)); // create bitmap and canvas Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas c = new Canvas(bitmap); // translate for vertical alignment c.translate(startX, startY); // draw text layout.draw(c); // draw again if stroke is enabled if(stroke) { // reset paint to stroke mode paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(strokeSize); paint.setARGB(255, (int)strokeR * 255, (int)strokeG * 255, (int)strokeB * 255); paint.clearShadowLayer(); // clear color and underline span for(ForegroundColorSpan span : rich.getSpans(0, rich.length(), ForegroundColorSpan.class)) { rich.removeSpan(span); } for(UnderlineSpan span : rich.getSpans(0, rich.length(), UnderlineSpan.class)) { rich.removeSpan(span); } layout.draw(c); } // extract link meta info extractLinkMeta(layout, spans, contentScaleFactor); // transfer bitmap data to native layer, and release bitmap when done initNativeObject(bitmap); bitmap.recycle(); } else { nativeInitBitmapDC(width, height, null); } // release cached images for(Bitmap b : imageMap.values()) { if(!b.isRecycled()) { b.recycle(); } } }
public static void createRichLabelBitmap(String pString, final String pFontName, final int pFontSize, final float fontTintR, final float fontTintG, final float fontTintB, final int pAlignment, final int pWidth, final int pHeight, final boolean shadow, final float shadowDX, final float shadowDY, final int shadowColor, final float shadowBlur, final boolean stroke, final float strokeR, final float strokeG, final float strokeB, final float strokeSize, float contentScaleFactor, boolean sizeOnly) { // reset bitmap dc nativeResetBitmapDC(); // extract span info and return text without span style List<Span> spans = new ArrayList<Span>(); String plain = buildSpan(pString, spans); // alignment int horizontalAlignment = pAlignment & 0x0F; int verticalAlignment = (pAlignment >> 4) & 0x0F; Alignment align = Alignment.ALIGN_NORMAL; switch(horizontalAlignment) { case HORIZONTALALIGN_CENTER: align = Alignment.ALIGN_CENTER; break; case HORIZONTALALIGN_RIGHT: align = Alignment.ALIGN_OPPOSITE; break; } // create paint TextPaint paint = new TextPaint(); paint.setColor(Color.WHITE); paint.setTextSize(pFontSize); paint.setAntiAlias(true); if (pFontName.endsWith(".ttf")) { try { Typeface typeFace = Cocos2dxTypefaces.get(Cocos2dxActivity.getContext(), pFontName); paint.setTypeface(typeFace); } catch (final Exception e) { Log.e("ColorLabelBitmap", "error to create ttf type face: " + pFontName); /* The file may not find, use system font. */ paint.setTypeface(Typeface.create(pFontName, Typeface.NORMAL)); } } else { paint.setTypeface(Typeface.create(pFontName, Typeface.NORMAL)); } // shadow // shadowBlur can be zero in android Paint, so set a min value to 1 if (shadow) { paint.setShadowLayer(Math.max(shadowBlur, 1), shadowDX, shadowDY, shadowColor); } // compute the padding needed by shadow and stroke float shadowStrokePaddingX = 0.0f; float shadowStrokePaddingY = 0.0f; if (stroke) { shadowStrokePaddingX = (float)Math.ceil(strokeSize); shadowStrokePaddingY = (float)Math.ceil(strokeSize); } if (shadow) { shadowStrokePaddingX = Math.max(shadowStrokePaddingX, (float)Math.abs(shadowDX)); shadowStrokePaddingY = Math.max(shadowStrokePaddingY, (float)Math.abs(shadowDY)); } // stack of color and font int defaultColor = 0xff000000 | ((int)(fontTintR * 255) << 16) | ((int)(fontTintG * 255) << 8) | (int)(fontTintB * 255); Typeface defaultFont = Typeface.DEFAULT; Stack<Integer> colorStack = new Stack<Integer>(); Stack<Typeface> fontStack = new Stack<Typeface>(); Stack<Float> fontSizeStack = new Stack<Float>(); colorStack.push(defaultColor); fontStack.push(defaultFont); fontSizeStack.push(pFontSize / contentScaleFactor); // build spannable string Map<String, Bitmap> imageMap = new HashMap<String, Bitmap>(); int colorStart = 0; int fontStart = 0; int sizeStart = 0; int underlineStart = -1; Span openSpan = null; SpannableString rich = new SpannableString(plain); for(Span span : spans) { if(span.close) { switch(span.type) { case COLOR: { int curColor = colorStack.pop(); if(span.pos > colorStart) { rich.setSpan(new ForegroundColorSpan(curColor), colorStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // start need to be reset colorStart = span.pos; } break; } case FONT: case BOLD: case ITALIC: { // set previous span Typeface font = fontStack.pop(); if(span.pos > fontStart && font != null) { rich.setSpan(new CustomTypefaceSpan("", font), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); fontStart = span.pos; } break; } case SIZE: { float size = fontSizeStack.pop(); if(span.pos > sizeStart) { rich.setSpan(new AbsoluteSizeSpan((int)(size * contentScaleFactor)), sizeStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sizeStart = span.pos; } break; } case UNDERLINE: { if(underlineStart > -1) { rich.setSpan(new UnderlineSpan(), underlineStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); underlineStart = -1; } break; } case IMAGE: { if(openSpan != null) { AssetManager am = Cocos2dxHelper.getAssetManager(); InputStream is = null; try { is = am.open(openSpan.imageName); Bitmap bitmap = BitmapFactory.decodeStream(is); if(openSpan.scaleX != 1 || openSpan.scaleY != 1 || contentScaleFactor != 1) { float dstW = openSpan.width != 0 ? (int)openSpan.width : (int)(bitmap.getWidth() * openSpan.scaleX); float dstH = openSpan.height != 0 ? (int)openSpan.height : (int)(bitmap.getHeight() * openSpan.scaleY); dstW *= contentScaleFactor; dstH *= contentScaleFactor; Bitmap scaled = Bitmap.createScaledBitmap(bitmap, (int)dstW, (int)dstH, true); bitmap.recycle(); bitmap = scaled; } imageMap.put(span.imageName, bitmap); rich.setSpan(new ImageSpan(bitmap, DynamicDrawableSpan.ALIGN_BASELINE), openSpan.pos, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Throwable e) { } finally { if(is != null) { try { is.close(); } catch (IOException e) { } } } openSpan = null; } break; } } } else { switch(span.type) { case COLOR: { // process previous run if(span.pos > colorStart) { int curColor = colorStack.peek(); rich.setSpan(new ForegroundColorSpan(curColor), colorStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // start need to be reset colorStart = span.pos; } // push color colorStack.push(span.color); break; } case FONT: { // set previous span Typeface curFont = fontStack.peek(); if(span.pos > fontStart) { rich.setSpan(new CustomTypefaceSpan("", curFont), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); fontStart = span.pos; } // create the font Typeface font = null; if (span.fontName.endsWith(".ttf")) { try { font = Cocos2dxTypefaces.get(Cocos2dxActivity.getContext(), span.fontName); } catch (final Exception e) { } } else { font = Typeface.create(span.fontName, Typeface.NORMAL); if(font == null) { font = Typeface.DEFAULT; } } fontStack.push(font); break; } case SIZE: { // set previous span if(span.pos > sizeStart) { float size = fontSizeStack.peek(); rich.setSpan(new AbsoluteSizeSpan((int)(size * contentScaleFactor)), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); sizeStart = span.pos; } // push new size fontSizeStack.push(span.fontSize); break; } case BOLD: { // set previous span Typeface curFont = fontStack.peek(); if(span.pos > fontStart) { rich.setSpan(new CustomTypefaceSpan("", curFont), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); fontStart = span.pos; } // create new font Typeface font = Typeface.create(curFont, Typeface.BOLD | curFont.getStyle()); fontStack.push(font); break; } case ITALIC: { // set previous span Typeface curFont = fontStack.peek(); if(span.pos > fontStart) { rich.setSpan(new CustomTypefaceSpan("", curFont), fontStart, span.pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); fontStart = span.pos; } // create new font Typeface font = Typeface.create(curFont, Typeface.ITALIC | curFont.getStyle()); fontStack.push(font); break; } case UNDERLINE: { underlineStart = span.pos; break; } case IMAGE: { openSpan = span; break; } } } } // last segment if(plain.length() > colorStart) { int curColor = colorStack.peek(); rich.setSpan(new ForegroundColorSpan(curColor), colorStart, plain.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } if(plain.length() > sizeStart) { float size = fontSizeStack.peek(); rich.setSpan(new AbsoluteSizeSpan((int)(size * contentScaleFactor)), fontStart, plain.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } if(plain.length() > fontStart) { Typeface curFont = fontStack.peek(); rich.setSpan(new CustomTypefaceSpan("", curFont), fontStart, plain.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } // layout this text StaticLayout layout = new StaticLayout(rich, paint, pWidth <= 0 ? (int)StaticLayout.getDesiredWidth(rich, paint) : pWidth, align, 1, 0, false); // size of layout int width = layout.getWidth(); int height = layout.getHeight(); // add padding of stroke width += shadowStrokePaddingX; height += shadowStrokePaddingY; // text origin int startY = 0; int startX = 0; if (pHeight > height) { // vertical alignment if (verticalAlignment == VERTICALALIGN_TOP) { startY = 0; } else if (verticalAlignment == VERTICALALIGN_CENTER) { startY = (pHeight - height) / 2; } else { startY = pHeight - height; } } if(shadow) { if(shadowDY < 0) { startY -= shadowDY; } if(shadowDX < 0) { startX -= shadowDX; } } // adjust layout if(pWidth > 0 && pWidth > width) width = pWidth; if(pHeight > 0 && pHeight > height) height = pHeight; // if only measure, just pass size to native layer // if not, render a bitmap if(!sizeOnly) { // save padding nativeSaveShadowStrokePadding(startX, Math.max(0, height - layout.getHeight() - startY)); // create bitmap and canvas Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas c = new Canvas(bitmap); // translate for vertical alignment c.translate(startX, startY); // draw text layout.draw(c); // draw again if stroke is enabled if(stroke) { // reset paint to stroke mode paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(strokeSize); paint.setARGB(255, (int)strokeR * 255, (int)strokeG * 255, (int)strokeB * 255); paint.clearShadowLayer(); // clear color and underline span for(ForegroundColorSpan span : rich.getSpans(0, rich.length(), ForegroundColorSpan.class)) { rich.removeSpan(span); } for(UnderlineSpan span : rich.getSpans(0, rich.length(), UnderlineSpan.class)) { rich.removeSpan(span); } layout.draw(c); } // extract link meta info extractLinkMeta(layout, spans, contentScaleFactor); // transfer bitmap data to native layer, and release bitmap when done initNativeObject(bitmap); bitmap.recycle(); } else { nativeInitBitmapDC(width, height, null); } // release cached images for(Bitmap b : imageMap.values()) { if(!b.isRecycled()) { b.recycle(); } } }
diff --git a/src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java b/src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java index bc63c14a9..b568ddeb2 100644 --- a/src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java +++ b/src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java @@ -1,416 +1,415 @@ /* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.fop.render.awt.viewer; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Rectangle2D; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JViewport; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import org.apache.fop.apps.Fop; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.area.PageViewport; import org.apache.fop.fo.Constants; import org.apache.fop.render.awt.AWTRenderer; /** * <p>Holds a scrollpane with the rendered page(s) and handles actions performed * to alter the display of the page. * </p> * <p>Use PreviewPanel when you want to embed a preview in your own application * with your own controls. Use PreviewDialog when you want to use the standard * Fop controls. * </p> * <p>In order to embed a PreviewPanel in your own app, create your own renderer, * and your own agent. Then call setPreviewDialogDisplayed(false) to hide the * default dialog. Finally create a preview panel with the renderer and add it * to your gui: * </p> * <pre> * AWTRenderer renderer = new AWTRenderer(); * FOUserAgent agent = new FOUserAgent(); * agent.setRendererOverride(renderer); * renderer.setPreviewDialogDisplayed(false); * renderer.setUserAgent(agent); * previewPanel = new PreviewPanel(agent, renderer); * previewPanel = new PreviewPanel(ua); * myGui.add(previewPanel); * </pre> * * In order to set options and display a page do: * <pre> * renderer.clearViewportList(); * // build report xml here * reload(); // optional if setting changed * </pre> * * If you wan't to change settings, don't call reload. A good example is * to set the page to fill the screen and set the scrolling mode: * <pre> * double scale = previewPanel.getScaleToFitWindow(); * previewPanel.setScaleFactor(scale); * previewPanel.setDisplayMode(PreviewPanel.CONTINUOUS); * </pre> */ public class PreviewPanel extends JPanel { /** Constant for setting single page display. */ public static final int SINGLE = 1; /** Constant for setting continuous page display. */ public static final int CONTINUOUS = 2; /** Constant for displaying even/odd pages side by side in continuous form. */ public static final int CONT_FACING = 3; /** The number of pixels left empty at the top bottom and sides of the page. */ private static final int BORDER_SPACING = 10; /** The main display area */ private JScrollPane previewArea; /** The AWT renderer - often shared with PreviewDialog */ private AWTRenderer renderer; /** The FOUserAgent associated with this panel - often shared with PreviewDialog */ protected FOUserAgent foUserAgent; /** The number of the page which is currently selected */ private int currentPage = 0; /** The index of the first page displayed on screen. */ private int firstPage = 0; /** The number of pages concurrently displayed on screen. */ private int pageRange = 1; /** The display mode. One of SINGLE, CONTINUOUS or CONT_FACING. */ private int displayMode = SINGLE; /** The component(s) that hold the rendered page(s) */ private ImageProxyPanel[] pagePanels = null; /** * Panel showing the page panels in a grid. Usually the dimensions * of the grid are 1x1, nx1 or nx2. */ private JPanel gridPanel = null; /** Asynchronous reloader thread, used when reload() method is called. */ private Reloader reloader; /** The Fop object used for refreshing/reloading the view */ protected Fop fop; /** * Allows any mouse drag on the page area to scroll the display window. */ private ViewportScroller scroller; /** * Creates a new PreviewPanel instance. * @param foUserAgent the user agent * @param renderer the AWT Renderer instance to paint with */ public PreviewPanel(FOUserAgent foUserAgent, AWTRenderer renderer) { super(new GridLayout(1, 1)); this.renderer = renderer; this.foUserAgent = foUserAgent; gridPanel = new JPanel(); gridPanel.setLayout(new GridLayout(0, 1)); // rows, cols previewArea = new JScrollPane(gridPanel); previewArea.getViewport().setBackground(Color.gray); // FIXME should add scroll wheel support here at some point. scroller = new ViewportScroller(previewArea.getViewport()); previewArea.addMouseListener(scroller); previewArea.addMouseMotionListener(scroller); previewArea.setMinimumSize(new Dimension(50, 50)); add(previewArea); } /** * @return the currently visible page */ public int getPage() { return currentPage; } /** * Selects the given page, displays it on screen and notifies * listeners about the change in selection. * @param number the page number */ public void setPage(int number) { if (displayMode == CONTINUOUS || displayMode == CONT_FACING) { // FIXME Should scroll so page is visible currentPage = number; } else { // single page mode currentPage = number; firstPage = currentPage; } showPage(); } /** * Sets the display mode. * @param mode One of SINGLE, CONTINUOUS or CONT_FACING. */ public void setDisplayMode(int mode) { if (mode != displayMode) { displayMode = mode; gridPanel.setLayout(new GridLayout(0, displayMode == CONT_FACING ? 2 : 1)); reload(); } } /** * Returns the display mode. * @return mode One of SINGLE, CONTINUOUS or CONT_FACING. */ public int getDisplayMode() { return displayMode; } /** * Reloads and reformats document. */ public synchronized void reload() { if (reloader == null || !reloader.isAlive()) { reloader = new Reloader(); reloader.start(); } } /** * Allows a (yet) simple visual debug of the document. */ void debug() { renderer.debug = !renderer.debug; reload(); } /** * Allows any mouse drag on the page area to scroll the display window. */ private class ViewportScroller implements MouseListener, MouseMotionListener { /** The viewport to be scrolled */ private final JViewport viewport; /** Starting position of a mouse drag - X co-ordinate */ private int startPosX = 0; /** Starting position of a mouse drag - Y co-ordinate */ private int startPosY = 0; ViewportScroller(JViewport vp) { viewport = vp; } // ***** MouseMotionListener ***** public synchronized void mouseDragged(MouseEvent e) { if (viewport == null) { return; } int x = e.getX(); int y = e.getY(); int xmove = x - startPosX; int ymove = y - startPosY; int viewWidth = viewport.getExtentSize().width; int viewHeight = viewport.getExtentSize().height; int imageWidth = viewport.getViewSize().width; int imageHeight = viewport.getViewSize().height; Point viewPoint = viewport.getViewPosition(); int viewX = Math.max(0, Math.min(imageWidth - viewWidth, viewPoint.x - xmove)); int viewY = Math.max(0, Math.min(imageHeight - viewHeight, viewPoint.y - ymove)); viewport.setViewPosition(new Point(viewX, viewY)); startPosX = x; startPosY = y; } public void mouseMoved(MouseEvent e) { } // ***** MouseListener ***** public void mousePressed(MouseEvent e) { startPosX = e.getX(); startPosY = e.getY(); } public void mouseExited(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } } /** * This class is used to reload document in a thread safe way. */ private class Reloader extends Thread { public void run() { if (!renderer.renderingDone) { // do not allow the reloading while FOP is still rendering JOptionPane.showMessageDialog(previewArea, "Cannot perform the requested operation until " + "all page are rendererd. Please wait", "Please wait ", 1 /* INFORMATION_MESSAGE */); return; } - if (fop == null) { - fop = new Fop(Constants.RENDER_AWT, foUserAgent); - } + //Always recreate the Fop instance. It is a use-once only. + fop = new Fop(Constants.RENDER_AWT, foUserAgent); pagePanels = null; int savedCurrentPage = currentPage; currentPage = 0; gridPanel.removeAll(); switch(displayMode) { case CONT_FACING: // This page intentionally left blank // Makes 0th/1st page on rhs gridPanel.add(new JLabel("")); case CONTINUOUS: currentPage = 0; firstPage = 0; pageRange = renderer.getNumberOfPages(); break; case SINGLE: default: currentPage = 0; firstPage = 0; pageRange = 1; break; } pagePanels = new ImageProxyPanel[pageRange]; for (int pg = 0; pg < pageRange; pg++) { pagePanels[pg] = new ImageProxyPanel(renderer, pg + firstPage); pagePanels[pg].setBorder(new EmptyBorder( BORDER_SPACING, BORDER_SPACING, BORDER_SPACING, BORDER_SPACING)); gridPanel.add(pagePanels[pg]); } try { if (foUserAgent.getInputHandler() != null) { renderer.clearViewportList(); foUserAgent.getInputHandler().render(fop); } } catch (FOPException e) { e.printStackTrace(); // FIXME Should show exception in gui - was reportException(e); } setPage(savedCurrentPage); } } /** * Scales page image * @param scale [0;1] */ public void setScaleFactor(double scale) { renderer.setScaleFactor(scale); reload(); } /** * Returns the scale factor required in order to fit either the current * page within the current window or to fit two adjacent pages within * the display if the displaymode is continuous. * @return the requested scale factor * @throws FOPException in case of an error while fetching the PageViewport */ public double getScaleToFitWindow() throws FOPException { Dimension extents = previewArea.getViewport().getExtentSize(); return getScaleToFit(extents.getWidth() - 2 * BORDER_SPACING, extents.getHeight() - 2 * BORDER_SPACING); } /** * As getScaleToFitWindow, but ignoring the Y axis. * @return the requested scale factor * @throws FOPException in case of an error while fetching the PageViewport */ public double getScaleToFitWidth() throws FOPException { Dimension extents = previewArea.getViewport().getExtentSize(); return getScaleToFit(extents.getWidth() - 2 * BORDER_SPACING, Double.MAX_VALUE); } /** * Returns the scale factor required in order to fit either the current page or * two adjacent pages within a window of the given height and width, depending * on the display mode. In order to ignore either dimension, * just specify it as Double.MAX_VALUE. * @param viewWidth width of the view * @param viewHeight height of the view * @return the requested scale factor * @throws FOPException in case of an error while fetching the PageViewport */ public double getScaleToFit(double viewWidth, double viewHeight) throws FOPException { PageViewport pageViewport = renderer.getPageViewport(currentPage); Rectangle2D pageSize = pageViewport.getViewArea(); double widthScale = viewWidth / (pageSize.getWidth() / 1000f); double heightScale = viewHeight / (pageSize.getHeight() / 1000f); return Math.min(displayMode == CONT_FACING ? widthScale / 2 : widthScale, heightScale); } /** Starts rendering process and shows the current page. */ public synchronized void showPage() { ShowPageImage viewer = new ShowPageImage(); if (SwingUtilities.isEventDispatchThread()) { viewer.run(); } else { SwingUtilities.invokeLater(viewer); } } /** This class is used to render the page image in a thread safe way. */ private class ShowPageImage implements Runnable { /** * The run method that does the actual rendering of the viewed page */ public void run() { for (int pg = firstPage; pg < firstPage + pageRange; pg++) { pagePanels[pg - firstPage].setPage(pg); } revalidate(); } } }
true
true
public void run() { if (!renderer.renderingDone) { // do not allow the reloading while FOP is still rendering JOptionPane.showMessageDialog(previewArea, "Cannot perform the requested operation until " + "all page are rendererd. Please wait", "Please wait ", 1 /* INFORMATION_MESSAGE */); return; } if (fop == null) { fop = new Fop(Constants.RENDER_AWT, foUserAgent); } pagePanels = null; int savedCurrentPage = currentPage; currentPage = 0; gridPanel.removeAll(); switch(displayMode) { case CONT_FACING: // This page intentionally left blank // Makes 0th/1st page on rhs gridPanel.add(new JLabel("")); case CONTINUOUS: currentPage = 0; firstPage = 0; pageRange = renderer.getNumberOfPages(); break; case SINGLE: default: currentPage = 0; firstPage = 0; pageRange = 1; break; } pagePanels = new ImageProxyPanel[pageRange]; for (int pg = 0; pg < pageRange; pg++) { pagePanels[pg] = new ImageProxyPanel(renderer, pg + firstPage); pagePanels[pg].setBorder(new EmptyBorder( BORDER_SPACING, BORDER_SPACING, BORDER_SPACING, BORDER_SPACING)); gridPanel.add(pagePanels[pg]); } try { if (foUserAgent.getInputHandler() != null) { renderer.clearViewportList(); foUserAgent.getInputHandler().render(fop); } } catch (FOPException e) { e.printStackTrace(); // FIXME Should show exception in gui - was reportException(e); } setPage(savedCurrentPage); }
public void run() { if (!renderer.renderingDone) { // do not allow the reloading while FOP is still rendering JOptionPane.showMessageDialog(previewArea, "Cannot perform the requested operation until " + "all page are rendererd. Please wait", "Please wait ", 1 /* INFORMATION_MESSAGE */); return; } //Always recreate the Fop instance. It is a use-once only. fop = new Fop(Constants.RENDER_AWT, foUserAgent); pagePanels = null; int savedCurrentPage = currentPage; currentPage = 0; gridPanel.removeAll(); switch(displayMode) { case CONT_FACING: // This page intentionally left blank // Makes 0th/1st page on rhs gridPanel.add(new JLabel("")); case CONTINUOUS: currentPage = 0; firstPage = 0; pageRange = renderer.getNumberOfPages(); break; case SINGLE: default: currentPage = 0; firstPage = 0; pageRange = 1; break; } pagePanels = new ImageProxyPanel[pageRange]; for (int pg = 0; pg < pageRange; pg++) { pagePanels[pg] = new ImageProxyPanel(renderer, pg + firstPage); pagePanels[pg].setBorder(new EmptyBorder( BORDER_SPACING, BORDER_SPACING, BORDER_SPACING, BORDER_SPACING)); gridPanel.add(pagePanels[pg]); } try { if (foUserAgent.getInputHandler() != null) { renderer.clearViewportList(); foUserAgent.getInputHandler().render(fop); } } catch (FOPException e) { e.printStackTrace(); // FIXME Should show exception in gui - was reportException(e); } setPage(savedCurrentPage); }
diff --git a/nuxeo-platform-webapp-core/src/main/java/org/nuxeo/ecm/webapp/helpers/EventManager.java b/nuxeo-platform-webapp-core/src/main/java/org/nuxeo/ecm/webapp/helpers/EventManager.java index a01538058..30d2763b8 100644 --- a/nuxeo-platform-webapp-core/src/main/java/org/nuxeo/ecm/webapp/helpers/EventManager.java +++ b/nuxeo-platform-webapp-core/src/main/java/org/nuxeo/ecm/webapp/helpers/EventManager.java @@ -1,201 +1,203 @@ /* * (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Nuxeo - initial API and implementation * * $Id$ */ package org.nuxeo.ecm.webapp.helpers; import static org.jboss.seam.ScopeType.APPLICATION; import static org.jboss.seam.annotations.Install.FRAMEWORK; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.seam.annotations.Install; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.Startup; import org.jboss.seam.core.Events; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.platform.ui.web.shield.NuxeoJavaBeanErrorHandler; /** * Knows what events need to be raised based on the user selected document. * * @author <a href="mailto:[email protected]">Razvan Caraghin</a> * */ @Name("eventManager") @Scope(APPLICATION) @Startup @NuxeoJavaBeanErrorHandler @Install(precedence=FRAMEWORK) public class EventManager implements Serializable { private static final long serialVersionUID = -7572053704069819975L; private static final Log log = LogFactory.getLog(EventManager.class); /** * Raises events on going home, will be processed immediately. * * @return events fired */ public static List<String> raiseEventsOnGoingHome() { List<String> eventsFired = new ArrayList<String>(); Events evtManager = Events.instance(); log.debug("Fire Event: " + EventNames.LOCATION_SELECTION_CHANGED); evtManager.raiseEvent(EventNames.LOCATION_SELECTION_CHANGED); eventsFired.add(EventNames.LOCATION_SELECTION_CHANGED); log.debug("Fire Event: " + EventNames.GO_HOME); evtManager.raiseEvent(EventNames.GO_HOME); eventsFired.add(EventNames.GO_HOME); return eventsFired; } /** * Raises events on location selection change, will be processed immediately. * * @return events fired */ public static List<String> raiseEventsOnLocationSelectionChanged() { List<String> eventsFired = new ArrayList<String>(); Events evtManager = Events.instance(); log.debug("Fire Event: " + EventNames.LOCATION_SELECTION_CHANGED); evtManager.raiseEvent(EventNames.LOCATION_SELECTION_CHANGED); eventsFired.add(EventNames.LOCATION_SELECTION_CHANGED); log.debug("Fire Event: " + EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); evtManager.raiseEvent( EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); eventsFired.add(EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); return eventsFired; } /** * Fires the necessary events so that the nuxeo infrastructure components get * updated. The raised events will be processed immediately, before this * call is ended. Intended to be used when a document gets selected. If the * docType is NULL then the GO_HOME event is fired. * * @param docType * @return events fired */ public static List<String> raiseEventsOnDocumentSelected(DocumentModel document) { List<String> eventsFired = new ArrayList<String>(); if (document == null) { // XXX AT: kind of BBB, not sure why this was used like this eventsFired = raiseEventsOnLocationSelectionChanged(); } else { - Events evtManager = Events.instance(); + Events evtManager = Events.instance(); String docType = document.getType(); String eventName; if ("Domain".equals(docType)) { eventName = EventNames.DOMAIN_SELECTION_CHANGED; + } else if ("Root".equals(docType)) { + eventName = EventNames.GO_HOME; } else if ("WorkspaceRoot".equals(docType) || "SectionRoot".equals(docType)) { eventName = EventNames.CONTENT_ROOT_SELECTION_CHANGED; } else { // regular document is selected eventName = EventNames.DOCUMENT_SELECTION_CHANGED; } if (document.isFolder()) { evtManager.raiseEvent( EventNames.FOLDERISHDOCUMENT_SELECTION_CHANGED, document); } log.debug("Fire Event: " + eventName); evtManager.raiseEvent(eventName, document); eventsFired.add(eventName); log.debug("Fire Event: " + EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); evtManager.raiseEvent( EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); eventsFired.add(EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); } return eventsFired; } /** * Fires the necessary events so that the nuxeo infrastructure componets get * updated. The raised events will be processed immediately, before this * call is ended. Intended to be used when a document gets edited/changed. * * @param docType * @return events fired */ public static List<String> raiseEventsOnDocumentChange(DocumentModel document) { List<String> eventsFired = new ArrayList<String>(); // TODO: parameterize on document type Events evtManager = Events.instance(); log.debug("Fire Event: " + EventNames.DOCUMENT_CHANGED); evtManager.raiseEvent(EventNames.DOCUMENT_CHANGED, document); eventsFired.add(EventNames.DOCUMENT_CHANGED); log.debug("Fire Event: " + EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); evtManager.raiseEvent( EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); eventsFired.add(EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); return eventsFired; } /** * Dispatch an event to get interested components informed when a changeable * document was created (thus not saved) and before the form is displayed. * * @param changeableDocument */ public static void raiseEventsOnDocumentCreate(DocumentModel document) { Events.instance().raiseEvent(EventNames.NEW_DOCUMENT_CREATED); } /** * Fires the necessary events so that the nuxeo infrastructure components get * updated. The raised events will be processed immediately, before this * call is ended. Intended to be used when a the content of a folderish * document gets changed. * * @param docType * @return events fired */ public static List<String> raiseEventsOnDocumentChildrenChange(DocumentModel document) { List<String> eventsFired = new ArrayList<String>(); Events.instance().raiseEvent(EventNames.DOCUMENT_CHILDREN_CHANGED, document); eventsFired.add(EventNames.DOCUMENT_CHILDREN_CHANGED); return eventsFired; } }
false
true
public static List<String> raiseEventsOnDocumentSelected(DocumentModel document) { List<String> eventsFired = new ArrayList<String>(); if (document == null) { // XXX AT: kind of BBB, not sure why this was used like this eventsFired = raiseEventsOnLocationSelectionChanged(); } else { Events evtManager = Events.instance(); String docType = document.getType(); String eventName; if ("Domain".equals(docType)) { eventName = EventNames.DOMAIN_SELECTION_CHANGED; } else if ("WorkspaceRoot".equals(docType) || "SectionRoot".equals(docType)) { eventName = EventNames.CONTENT_ROOT_SELECTION_CHANGED; } else { // regular document is selected eventName = EventNames.DOCUMENT_SELECTION_CHANGED; } if (document.isFolder()) { evtManager.raiseEvent( EventNames.FOLDERISHDOCUMENT_SELECTION_CHANGED, document); } log.debug("Fire Event: " + eventName); evtManager.raiseEvent(eventName, document); eventsFired.add(eventName); log.debug("Fire Event: " + EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); evtManager.raiseEvent( EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); eventsFired.add(EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); } return eventsFired; }
public static List<String> raiseEventsOnDocumentSelected(DocumentModel document) { List<String> eventsFired = new ArrayList<String>(); if (document == null) { // XXX AT: kind of BBB, not sure why this was used like this eventsFired = raiseEventsOnLocationSelectionChanged(); } else { Events evtManager = Events.instance(); String docType = document.getType(); String eventName; if ("Domain".equals(docType)) { eventName = EventNames.DOMAIN_SELECTION_CHANGED; } else if ("Root".equals(docType)) { eventName = EventNames.GO_HOME; } else if ("WorkspaceRoot".equals(docType) || "SectionRoot".equals(docType)) { eventName = EventNames.CONTENT_ROOT_SELECTION_CHANGED; } else { // regular document is selected eventName = EventNames.DOCUMENT_SELECTION_CHANGED; } if (document.isFolder()) { evtManager.raiseEvent( EventNames.FOLDERISHDOCUMENT_SELECTION_CHANGED, document); } log.debug("Fire Event: " + eventName); evtManager.raiseEvent(eventName, document); eventsFired.add(eventName); log.debug("Fire Event: " + EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); evtManager.raiseEvent( EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); eventsFired.add(EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED); } return eventsFired; }
diff --git a/src/com/djdch/bukkit/onehundredgenerator/mc100/GenLayerSmoothZoom.java b/src/com/djdch/bukkit/onehundredgenerator/mc100/GenLayerSmoothZoom.java index 9467fe6..e545d92 100644 --- a/src/com/djdch/bukkit/onehundredgenerator/mc100/GenLayerSmoothZoom.java +++ b/src/com/djdch/bukkit/onehundredgenerator/mc100/GenLayerSmoothZoom.java @@ -1,56 +1,56 @@ package com.djdch.bukkit.onehundredgenerator.mc100; public class GenLayerSmoothZoom extends GenLayer { public GenLayerSmoothZoom(long paramLong, GenLayer paramGenLayer) { super(paramLong); this.a = paramGenLayer; } @Override public int[] a(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { int i = paramInt1 >> 1; int j = paramInt2 >> 1; int k = (paramInt3 >> 1) + 3; int m = (paramInt4 >> 1) + 3; int[] arrayOfInt1 = this.a.a(i, j, k, m); int[] arrayOfInt2 = IntCache.a(k * 2 * (m * 2)); int n = k << 1; for (int i1 = 0; i1 < m - 1; i1++) { - i2 = i1 << 1; + int i2 = i1 << 1; int i3 = i2 * n; int i4 = arrayOfInt1[(0 + (i1 + 0) * k)]; int i5 = arrayOfInt1[(0 + (i1 + 1) * k)]; for (int i6 = 0; i6 < k - 1; i6++) { a(i6 + i << 1, i1 + j << 1); int i7 = arrayOfInt1[(i6 + 1 + (i1 + 0) * k)]; int i8 = arrayOfInt1[(i6 + 1 + (i1 + 1) * k)]; arrayOfInt2[i3] = i4; arrayOfInt2[(i3++ + n)] = (i4 + (i5 - i4) * a(256) / 256); arrayOfInt2[i3] = (i4 + (i7 - i4) * a(256) / 256); int i9 = i4 + (i7 - i4) * a(256) / 256; int i10 = i5 + (i8 - i5) * a(256) / 256; arrayOfInt2[(i3++ + n)] = (i9 + (i10 - i9) * a(256) / 256); i4 = i7; i5 = i8; } } int[] arrayOfInt3 = IntCache.a(paramInt3 * paramInt4); for (int i2 = 0; i2 < paramInt4; i2++) { System.arraycopy(arrayOfInt2, (i2 + (paramInt2 & 0x1)) * (k << 1) + (paramInt1 & 0x1), arrayOfInt3, i2 * paramInt3, paramInt3); } return arrayOfInt3; } public static GenLayer a(long paramLong, GenLayer paramGenLayer, int paramInt) { Object localObject = paramGenLayer; for (int i = 0; i < paramInt; i++) { localObject = new GenLayerSmoothZoom(paramLong + i, (GenLayer) localObject); } return (GenLayer) localObject; } }
true
true
public int[] a(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { int i = paramInt1 >> 1; int j = paramInt2 >> 1; int k = (paramInt3 >> 1) + 3; int m = (paramInt4 >> 1) + 3; int[] arrayOfInt1 = this.a.a(i, j, k, m); int[] arrayOfInt2 = IntCache.a(k * 2 * (m * 2)); int n = k << 1; for (int i1 = 0; i1 < m - 1; i1++) { i2 = i1 << 1; int i3 = i2 * n; int i4 = arrayOfInt1[(0 + (i1 + 0) * k)]; int i5 = arrayOfInt1[(0 + (i1 + 1) * k)]; for (int i6 = 0; i6 < k - 1; i6++) { a(i6 + i << 1, i1 + j << 1); int i7 = arrayOfInt1[(i6 + 1 + (i1 + 0) * k)]; int i8 = arrayOfInt1[(i6 + 1 + (i1 + 1) * k)]; arrayOfInt2[i3] = i4; arrayOfInt2[(i3++ + n)] = (i4 + (i5 - i4) * a(256) / 256); arrayOfInt2[i3] = (i4 + (i7 - i4) * a(256) / 256); int i9 = i4 + (i7 - i4) * a(256) / 256; int i10 = i5 + (i8 - i5) * a(256) / 256; arrayOfInt2[(i3++ + n)] = (i9 + (i10 - i9) * a(256) / 256); i4 = i7; i5 = i8; } } int[] arrayOfInt3 = IntCache.a(paramInt3 * paramInt4); for (int i2 = 0; i2 < paramInt4; i2++) { System.arraycopy(arrayOfInt2, (i2 + (paramInt2 & 0x1)) * (k << 1) + (paramInt1 & 0x1), arrayOfInt3, i2 * paramInt3, paramInt3); } return arrayOfInt3; }
public int[] a(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { int i = paramInt1 >> 1; int j = paramInt2 >> 1; int k = (paramInt3 >> 1) + 3; int m = (paramInt4 >> 1) + 3; int[] arrayOfInt1 = this.a.a(i, j, k, m); int[] arrayOfInt2 = IntCache.a(k * 2 * (m * 2)); int n = k << 1; for (int i1 = 0; i1 < m - 1; i1++) { int i2 = i1 << 1; int i3 = i2 * n; int i4 = arrayOfInt1[(0 + (i1 + 0) * k)]; int i5 = arrayOfInt1[(0 + (i1 + 1) * k)]; for (int i6 = 0; i6 < k - 1; i6++) { a(i6 + i << 1, i1 + j << 1); int i7 = arrayOfInt1[(i6 + 1 + (i1 + 0) * k)]; int i8 = arrayOfInt1[(i6 + 1 + (i1 + 1) * k)]; arrayOfInt2[i3] = i4; arrayOfInt2[(i3++ + n)] = (i4 + (i5 - i4) * a(256) / 256); arrayOfInt2[i3] = (i4 + (i7 - i4) * a(256) / 256); int i9 = i4 + (i7 - i4) * a(256) / 256; int i10 = i5 + (i8 - i5) * a(256) / 256; arrayOfInt2[(i3++ + n)] = (i9 + (i10 - i9) * a(256) / 256); i4 = i7; i5 = i8; } } int[] arrayOfInt3 = IntCache.a(paramInt3 * paramInt4); for (int i2 = 0; i2 < paramInt4; i2++) { System.arraycopy(arrayOfInt2, (i2 + (paramInt2 & 0x1)) * (k << 1) + (paramInt1 & 0x1), arrayOfInt3, i2 * paramInt3, paramInt3); } return arrayOfInt3; }
diff --git a/samples/src/main/java/Main.java b/samples/src/main/java/Main.java index 0b7861c..4087124 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("[email protected]") .build(); - // Build 100 contacts with on of the given names and no email + // Build 100 contacts 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("[email protected]") .build(); // Build 100 contacts with on 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("[email protected]") .build(); // Build 100 contacts with one of the given names and no email Contact[] someContacts = new ContactBuilder() .withNameFrom("Alice", "Bob", "Charly") .buildArray( 100); }
diff --git a/BetterBatteryStats/src/com/asksven/betterbatterystats/adapters/ServicesAdapter.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/adapters/ServicesAdapter.java index 463ba70e..9f2ff5dd 100644 --- a/BetterBatteryStats/src/com/asksven/betterbatterystats/adapters/ServicesAdapter.java +++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/adapters/ServicesAdapter.java @@ -1,99 +1,101 @@ /* * Copyright (C) 2011-2012 asksven * * 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.asksven.betterbatterystats.adapters; import java.util.List; import java.util.Map; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PermissionInfo; import android.net.Uri; import android.preference.PreferenceManager; import android.provider.ContactsContract.Contacts; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.asksven.android.common.privateapiproxies.StatElement; import com.asksven.betterbatterystats.R; import com.asksven.betterbatterystats.data.Permission; public class ServicesAdapter extends BaseAdapter { private Context m_context; private List<String> m_listData; private static final String TAG = "ServicesAdapter"; int m_selectedPosition = 0; boolean m_expanded = false; public ServicesAdapter(Context context, List<String> listData) { this.m_context = context; this.m_listData = listData; } public void setSelectedPosition(int position) { m_selectedPosition = position; notifyDataSetChanged(); } public void toggleExpand() { m_expanded = !m_expanded; notifyDataSetChanged(); } public int getCount() { return m_listData.size(); } public Object getItem(int position) { return m_listData.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup viewGroup) { String entry = m_listData.get(position); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) m_context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.package_info_row, null); } TextView tvName = (TextView) convertView.findViewById(R.id.TextViewName); tvName.setText(entry); + LinearLayout descriptionLayout = (LinearLayout) convertView.findViewById(R.id.LayoutDescription); + descriptionLayout.setVisibility(View.GONE); return convertView; } }
false
true
public View getView(int position, View convertView, ViewGroup viewGroup) { String entry = m_listData.get(position); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) m_context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.package_info_row, null); } TextView tvName = (TextView) convertView.findViewById(R.id.TextViewName); tvName.setText(entry); return convertView; }
public View getView(int position, View convertView, ViewGroup viewGroup) { String entry = m_listData.get(position); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) m_context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.package_info_row, null); } TextView tvName = (TextView) convertView.findViewById(R.id.TextViewName); tvName.setText(entry); LinearLayout descriptionLayout = (LinearLayout) convertView.findViewById(R.id.LayoutDescription); descriptionLayout.setVisibility(View.GONE); return convertView; }
diff --git a/src/org/flowvisor/config/ConfDBHandler.java b/src/org/flowvisor/config/ConfDBHandler.java index 8c120ef..6ec7a6d 100644 --- a/src/org/flowvisor/config/ConfDBHandler.java +++ b/src/org/flowvisor/config/ConfDBHandler.java @@ -1,127 +1,127 @@ package org.flowvisor.config; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.commons.dbcp.ConnectionFactory; import org.apache.commons.dbcp.DriverManagerConnectionFactory; import org.apache.commons.dbcp.PoolableConnectionFactory; import org.apache.commons.dbcp.PoolingDataSource; import org.apache.commons.pool.impl.GenericObjectPool; import org.apache.derby.jdbc.EmbeddedDataSource; import org.flowvisor.log.FVLog; import org.flowvisor.log.LogLevel; /** * Defines a connection pool to derby. * Guarantees that the status of a returned connection * is valid. * * * @author ash * */ public class ConfDBHandler implements ConfDBSettings { private String protocol = null; private String dbName = null; private String username = null; private String password = null; private ConnectionFactory cf = null; @SuppressWarnings("unused") private PoolableConnectionFactory pcf = null; private GenericObjectPool gop = null; private PoolingDataSource pds = null; private Boolean autoCommit = false; public ConfDBHandler(String protocol, String dbName, String username, String password, Boolean autoCommit) { this.protocol = protocol; this.dbName = System.getProperty("derby.system.home") + "/" + dbName; this.username = username; this.password = password; this.autoCommit = autoCommit; } public ConfDBHandler() { this("jdbc:derby:", "FlowVisorDB", "", "", true); } private DataSource getDataSource() { if (pds != null) return pds; gop = new GenericObjectPool(null); gop.setTestOnBorrow(true); gop.setTestWhileIdle(true); cf = new DriverManagerConnectionFactory(this.protocol + this.dbName, this.username, this.password); - pcf = new PoolableConnectionFactory(cf, gop, null, "SELECT 1",false, autoCommit); + pcf = new PoolableConnectionFactory(cf, gop, null, null,false, autoCommit); pds = new PoolingDataSource(pcf.getPool()); return pds; } @Override public Connection getConnection() throws SQLException { return getDataSource().getConnection(); } @Override public Connection getConnection(String user, String pass) throws SQLException { return getDataSource().getConnection(user, pass); } @Override public void returnConnection(Connection conn) { try { gop.returnObject(conn); } catch (Exception e) { FVLog.log(LogLevel.CRIT, null, "Unable to return connection"); } } @Override public int getNumActive() { return gop.getNumActive(); } @Override public int getNumIdle() { return gop.getNumIdle(); } @Override public int getMaxActive() { return gop.getMaxActive(); } @Override public int getMaxIdle() { return gop.getMaxIdle(); } @Override public Boolean getDefaultAutoCommit() { return autoCommit; } @Override public void shutdown() { try { gop.close(); ((EmbeddedDataSource) getDataSource()).setShutdownDatabase("shutdown"); } catch (ClassCastException cce) { //Isn't this a derby db? } catch (Exception e) { FVLog.log(LogLevel.WARN, null, "Error on closing connection pool to derby"); } } }
true
true
private DataSource getDataSource() { if (pds != null) return pds; gop = new GenericObjectPool(null); gop.setTestOnBorrow(true); gop.setTestWhileIdle(true); cf = new DriverManagerConnectionFactory(this.protocol + this.dbName, this.username, this.password); pcf = new PoolableConnectionFactory(cf, gop, null, "SELECT 1",false, autoCommit); pds = new PoolingDataSource(pcf.getPool()); return pds; }
private DataSource getDataSource() { if (pds != null) return pds; gop = new GenericObjectPool(null); gop.setTestOnBorrow(true); gop.setTestWhileIdle(true); cf = new DriverManagerConnectionFactory(this.protocol + this.dbName, this.username, this.password); pcf = new PoolableConnectionFactory(cf, gop, null, null,false, autoCommit); pds = new PoolingDataSource(pcf.getPool()); return pds; }
diff --git a/DotMatrixView/src/com/escapeindustries/numericdisplay/BaseGrid.java b/DotMatrixView/src/com/escapeindustries/numericdisplay/BaseGrid.java index 81f6611..d939038 100644 --- a/DotMatrixView/src/com/escapeindustries/numericdisplay/BaseGrid.java +++ b/DotMatrixView/src/com/escapeindustries/numericdisplay/BaseGrid.java @@ -1,129 +1,129 @@ package com.escapeindustries.numericdisplay; import java.util.ArrayList; import java.util.List; public abstract class BaseGrid implements Grid { protected int columns = 0; protected int rows = 0; private int paddingTop = 0; private int paddingLeft = 0; private int paddingBottom = 0; private int paddingRight = 0; private boolean active; private Glyph[] glyphs; private Digit[] digits; @Override public int getColumns() { return columns; } @Override public void setColumns(int columns) { this.columns = columns; } @Override public int getRows() { return rows; } @Override public void setRows(int rows) { this.rows = rows; } @Override public int getPaddingRowsTop() { return paddingTop; } @Override public int getPaddingColumnsLeft() { return paddingLeft; } @Override public int getPaddingRowsBottom() { return paddingBottom; } @Override public int getPaddingColumnsRight() { return paddingRight; } @Override public void setPaddingDots(int top, int left, int bottom, int right) { this.paddingTop = top; this.paddingLeft = left; this.paddingBottom = bottom; this.paddingRight = right; } @Override public void setActive(boolean active) { this.active = active; } @Override public boolean isActive() { return active; } @Override public void setFormat(String format) { GlyphFactory factory = new GlyphFactory(this); FormatStringParser parser = new FormatStringParser(factory); glyphs = parser.parse(format); digits = extractDigits(glyphs); int gridHeight = 0; int column = getPaddingColumnsLeft(); for (Glyph glyph : glyphs) { glyph.setColumn(column); glyph.setRow(getPaddingRowsTop()); column += glyph.getWidth(); gridHeight = Math.max(gridHeight, glyph.getHeight()); } - setColumns(column); - setRows(gridHeight); + setColumns(column + paddingRight); + setRows(paddingTop + gridHeight + paddingBottom); initializeGrid(); for (Glyph glyph : glyphs) { glyph.draw(); } setActive(true); // TODO Is this really supposed to be here? } @Override public void setValue(String value) { DigitsParser parser = new DigitsParser(); int[] values = parser.parse(value); int digitsOffset = digits.length - values.length; int valuesOffset = 0; if (digitsOffset < 0) { valuesOffset = digitsOffset * -1; digitsOffset = 0; } int limit = Math.min(digits.length, values.length); for (int i = 0; i < limit; i++) { digits[i + digitsOffset].setNumber(values[i + valuesOffset]); } } @Override public abstract void changeDot(int x, int y, boolean on); public abstract void initializeGrid(); private Digit[] extractDigits(Glyph[] glyphs) { List<Digit> digits = new ArrayList<Digit>(); for (int i = 0; i < glyphs.length; i++) { if (glyphs[i] instanceof Digit) { digits.add((Digit) glyphs[i]); } } return digits.toArray(new Digit[digits.size()]); } }
true
true
public void setFormat(String format) { GlyphFactory factory = new GlyphFactory(this); FormatStringParser parser = new FormatStringParser(factory); glyphs = parser.parse(format); digits = extractDigits(glyphs); int gridHeight = 0; int column = getPaddingColumnsLeft(); for (Glyph glyph : glyphs) { glyph.setColumn(column); glyph.setRow(getPaddingRowsTop()); column += glyph.getWidth(); gridHeight = Math.max(gridHeight, glyph.getHeight()); } setColumns(column); setRows(gridHeight); initializeGrid(); for (Glyph glyph : glyphs) { glyph.draw(); } setActive(true); // TODO Is this really supposed to be here? }
public void setFormat(String format) { GlyphFactory factory = new GlyphFactory(this); FormatStringParser parser = new FormatStringParser(factory); glyphs = parser.parse(format); digits = extractDigits(glyphs); int gridHeight = 0; int column = getPaddingColumnsLeft(); for (Glyph glyph : glyphs) { glyph.setColumn(column); glyph.setRow(getPaddingRowsTop()); column += glyph.getWidth(); gridHeight = Math.max(gridHeight, glyph.getHeight()); } setColumns(column + paddingRight); setRows(paddingTop + gridHeight + paddingBottom); initializeGrid(); for (Glyph glyph : glyphs) { glyph.draw(); } setActive(true); // TODO Is this really supposed to be here? }
diff --git a/src/com/android/launcher2/Launcher.java b/src/com/android/launcher2/Launcher.java index 28dfd652..54324844 100644 --- a/src/com/android/launcher2/Launcher.java +++ b/src/com/android/launcher2/Launcher.java @@ -1,3714 +1,3714 @@ /* * 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.launcher2; import android.accounts.Account; import android.accounts.AccountManager; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityOptions; import android.app.SearchManager; import android.appwidget.AppWidgetHostView; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentCallbacks2; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.content.res.Resources; import android.database.ContentObserver; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StrictMode; import android.os.SystemClock; import android.os.SystemProperties; import android.provider.Settings; import android.speech.RecognizerIntent; import android.text.Selection; import android.text.SpannableStringBuilder; import android.text.method.TextKeyListener; import android.util.Log; import android.view.Display; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.Surface; import android.view.View; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.inputmethod.InputMethodManager; import android.widget.Advanceable; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.common.Search; import com.android.launcher.R; import com.android.launcher2.DropTarget.DragObject; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Default launcher application. */ public final class Launcher extends Activity implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks, AllAppsView.Watcher, View.OnTouchListener { static final String TAG = "Launcher"; static final boolean LOGD = false; static final boolean PROFILE_STARTUP = false; static final boolean DEBUG_WIDGETS = false; static final boolean DEBUG_STRICT_MODE = false; private static final int MENU_GROUP_WALLPAPER = 1; private static final int MENU_WALLPAPER_SETTINGS = Menu.FIRST + 1; private static final int MENU_MANAGE_APPS = MENU_WALLPAPER_SETTINGS + 1; private static final int MENU_SYSTEM_SETTINGS = MENU_MANAGE_APPS + 1; private static final int MENU_HELP = MENU_SYSTEM_SETTINGS + 1; private static final int REQUEST_CREATE_SHORTCUT = 1; private static final int REQUEST_CREATE_APPWIDGET = 5; private static final int REQUEST_PICK_APPLICATION = 6; private static final int REQUEST_PICK_SHORTCUT = 7; private static final int REQUEST_PICK_APPWIDGET = 9; private static final int REQUEST_PICK_WALLPAPER = 10; private static final int REQUEST_BIND_APPWIDGET = 11; static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate"; static final int SCREEN_COUNT = 5; static final int DEFAULT_SCREEN = 2; private static final String PREFERENCES = "launcher.preferences"; static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher.force_enable_rotation"; // The Intent extra that defines whether to ignore the launch animation static final String INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION = "com.android.launcher.intent.extra.shortcut.INGORE_LAUNCH_ANIMATION"; // Type: int private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen"; // Type: int private static final String RUNTIME_STATE = "launcher.state"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y"; // Type: boolean private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder"; // Type: long private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_span_x"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_span_y"; // Type: parcelable private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_INFO = "launcher.add_widget_info"; private static final String TOOLBAR_ICON_METADATA_NAME = "com.android.launcher.toolbar_icon"; private static final String TOOLBAR_SEARCH_ICON_METADATA_NAME = "com.android.launcher.toolbar_search_icon"; private static final String TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME = "com.android.launcher.toolbar_voice_search_icon"; /** The different states that Launcher can be in. */ private enum State { WORKSPACE, APPS_CUSTOMIZE, APPS_CUSTOMIZE_SPRING_LOADED }; private State mState = State.WORKSPACE; private AnimatorSet mStateAnimation; private AnimatorSet mDividerAnimator; static final int APPWIDGET_HOST_ID = 1024; private static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300; private static final int EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT = 600; private static final int SHOW_CLING_DURATION = 550; private static final int DISMISS_CLING_DURATION = 250; private static final Object sLock = new Object(); private static int sScreen = DEFAULT_SCREEN; // How long to wait before the new-shortcut animation automatically pans the workspace private static int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 10; private final BroadcastReceiver mCloseSystemDialogsReceiver = new CloseSystemDialogsIntentReceiver(); private final ContentObserver mWidgetObserver = new AppWidgetResetObserver(); private LayoutInflater mInflater; private Workspace mWorkspace; private View mQsbDivider; private View mDockDivider; private DragLayer mDragLayer; private DragController mDragController; private AppWidgetManager mAppWidgetManager; private LauncherAppWidgetHost mAppWidgetHost; private ItemInfo mPendingAddInfo = new ItemInfo(); private AppWidgetProviderInfo mPendingAddWidgetInfo; private int[] mTmpAddItemCellCoordinates = new int[2]; private FolderInfo mFolderInfo; private Hotseat mHotseat; private View mAllAppsButton; private SearchDropTargetBar mSearchDropTargetBar; private AppsCustomizeTabHost mAppsCustomizeTabHost; private AppsCustomizePagedView mAppsCustomizeContent; private boolean mAutoAdvanceRunning = false; private Bundle mSavedState; private SpannableStringBuilder mDefaultKeySsb = null; private boolean mWorkspaceLoading = true; private boolean mPaused = true; private boolean mRestoring; private boolean mWaitingForResult; private boolean mOnResumeNeedsLoad; private Bundle mSavedInstanceState; private LauncherModel mModel; private IconCache mIconCache; private boolean mUserPresent = true; private boolean mVisible = false; private boolean mAttached = false; private static LocaleConfiguration sLocaleConfiguration = null; private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>(); private Intent mAppMarketIntent = null; // Related to the auto-advancing of widgets private final int ADVANCE_MSG = 1; private final int mAdvanceInterval = 20000; private final int mAdvanceStagger = 250; private long mAutoAdvanceSentTime; private long mAutoAdvanceTimeLeft = -1; private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance = new HashMap<View, AppWidgetProviderInfo>(); // Determines how long to wait after a rotation before restoring the screen orientation to // match the sensor state. private final int mRestoreScreenOrientationDelay = 500; // External icons saved in case of resource changes, orientation, etc. private static Drawable.ConstantState[] sGlobalSearchIcon = new Drawable.ConstantState[2]; private static Drawable.ConstantState[] sVoiceSearchIcon = new Drawable.ConstantState[2]; private static Drawable.ConstantState[] sAppMarketIcon = new Drawable.ConstantState[2]; static final ArrayList<String> sDumpLogs = new ArrayList<String>(); // We only want to get the SharedPreferences once since it does an FS stat each time we get // it from the context. private SharedPreferences mSharedPrefs; // Holds the page that we need to animate to, and the icon views that we need to animate up // when we scroll to that page on resume. private int mNewShortcutAnimatePage = -1; private ArrayList<View> mNewShortcutAnimateViews = new ArrayList<View>(); private ImageView mFolderIconImageView; private Bitmap mFolderIconBitmap; private Canvas mFolderIconCanvas; private Rect mRectForFolderAnimation = new Rect(); private BubbleTextView mWaitingForResume; private Runnable mBuildLayersRunnable = new Runnable() { public void run() { if (mWorkspace != null) { mWorkspace.buildPageHardwareLayers(); } } }; private static ArrayList<PendingAddArguments> sPendingAddList = new ArrayList<PendingAddArguments>(); private static class PendingAddArguments { int requestCode; Intent intent; long container; int screen; int cellX; int cellY; } @Override protected void onCreate(Bundle savedInstanceState) { if (DEBUG_STRICT_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } super.onCreate(savedInstanceState); LauncherApplication app = ((LauncherApplication)getApplication()); mSharedPrefs = getSharedPreferences(LauncherApplication.getSharedPreferencesKey(), Context.MODE_PRIVATE); mModel = app.setLauncher(this); mIconCache = app.getIconCache(); mDragController = new DragController(this); mInflater = getLayoutInflater(); mAppWidgetManager = AppWidgetManager.getInstance(this); mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID); mAppWidgetHost.startListening(); if (PROFILE_STARTUP) { android.os.Debug.startMethodTracing( Environment.getExternalStorageDirectory() + "/launcher"); } checkForLocaleChange(); setContentView(R.layout.launcher); setupViews(); showFirstRunWorkspaceCling(); registerContentObservers(); lockAllApps(); mSavedState = savedInstanceState; restoreState(mSavedState); // Update customization drawer _after_ restoring the states if (mAppsCustomizeContent != null) { Log.d(TAG, "6549598 Launcher.onCreate()"); mAppsCustomizeContent.onPackagesUpdated(); } if (PROFILE_STARTUP) { android.os.Debug.stopMethodTracing(); } if (!mRestoring) { mModel.startLoader(true); } if (!mModel.isAllAppsLoaded()) { ViewGroup appsCustomizeContentParent = (ViewGroup) mAppsCustomizeContent.getParent(); mInflater.inflate(R.layout.apps_customize_progressbar, appsCustomizeContentParent); } // For handling default keys mDefaultKeySsb = new SpannableStringBuilder(); Selection.setSelection(mDefaultKeySsb, 0); IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(mCloseSystemDialogsReceiver, filter); updateGlobalIcons(); // On large interfaces, we want the screen to auto-rotate based on the current orientation unlockScreenOrientation(true); } private void updateGlobalIcons() { boolean searchVisible = false; boolean voiceVisible = false; // If we have a saved version of these external icons, we load them up immediately int coi = getCurrentOrientationIndexForGlobalIcons(); if (sGlobalSearchIcon[coi] == null || sVoiceSearchIcon[coi] == null || sAppMarketIcon[coi] == null) { updateAppMarketIcon(); searchVisible = updateGlobalSearchIcon(); voiceVisible = updateVoiceSearchIcon(searchVisible); } if (sGlobalSearchIcon[coi] != null) { updateGlobalSearchIcon(sGlobalSearchIcon[coi]); searchVisible = true; } if (sVoiceSearchIcon[coi] != null) { updateVoiceSearchIcon(sVoiceSearchIcon[coi]); voiceVisible = true; } if (sAppMarketIcon[coi] != null) { updateAppMarketIcon(sAppMarketIcon[coi]); } mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible); } private void checkForLocaleChange() { if (sLocaleConfiguration == null) { new AsyncTask<Void, Void, LocaleConfiguration>() { @Override protected LocaleConfiguration doInBackground(Void... unused) { LocaleConfiguration localeConfiguration = new LocaleConfiguration(); readConfiguration(Launcher.this, localeConfiguration); return localeConfiguration; } @Override protected void onPostExecute(LocaleConfiguration result) { sLocaleConfiguration = result; checkForLocaleChange(); // recursive, but now with a locale configuration } }.execute(); return; } final Configuration configuration = getResources().getConfiguration(); final String previousLocale = sLocaleConfiguration.locale; final String locale = configuration.locale.toString(); final int previousMcc = sLocaleConfiguration.mcc; final int mcc = configuration.mcc; final int previousMnc = sLocaleConfiguration.mnc; final int mnc = configuration.mnc; boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc; if (localeChanged) { sLocaleConfiguration.locale = locale; sLocaleConfiguration.mcc = mcc; sLocaleConfiguration.mnc = mnc; mIconCache.flush(); final LocaleConfiguration localeConfiguration = sLocaleConfiguration; new Thread("WriteLocaleConfiguration") { @Override public void run() { writeConfiguration(Launcher.this, localeConfiguration); } }.start(); } } private static class LocaleConfiguration { public String locale; public int mcc = -1; public int mnc = -1; } private static void readConfiguration(Context context, LocaleConfiguration configuration) { DataInputStream in = null; try { in = new DataInputStream(context.openFileInput(PREFERENCES)); configuration.locale = in.readUTF(); configuration.mcc = in.readInt(); configuration.mnc = in.readInt(); } catch (FileNotFoundException e) { // Ignore } catch (IOException e) { // Ignore } finally { if (in != null) { try { in.close(); } catch (IOException e) { // Ignore } } } } private static void writeConfiguration(Context context, LocaleConfiguration configuration) { DataOutputStream out = null; try { out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE)); out.writeUTF(configuration.locale); out.writeInt(configuration.mcc); out.writeInt(configuration.mnc); out.flush(); } catch (FileNotFoundException e) { // Ignore } catch (IOException e) { //noinspection ResultOfMethodCallIgnored context.getFileStreamPath(PREFERENCES).delete(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore } } } } public DragLayer getDragLayer() { return mDragLayer; } boolean isDraggingEnabled() { // We prevent dragging when we are loading the workspace as it is possible to pick up a view // that is subsequently removed from the workspace in startBinding(). return !mModel.isLoadingWorkspace(); } static int getScreen() { synchronized (sLock) { return sScreen; } } static void setScreen(int screen) { synchronized (sLock) { sScreen = screen; } } /** * Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have * a configuration step, this allows the proper animations to run after other transitions. */ private boolean completeAdd(PendingAddArguments args) { boolean result = false; switch (args.requestCode) { case REQUEST_PICK_APPLICATION: completeAddApplication(args.intent, args.container, args.screen, args.cellX, args.cellY); break; case REQUEST_PICK_SHORTCUT: processShortcut(args.intent); break; case REQUEST_CREATE_SHORTCUT: completeAddShortcut(args.intent, args.container, args.screen, args.cellX, args.cellY); result = true; break; case REQUEST_CREATE_APPWIDGET: int appWidgetId = args.intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); completeAddAppWidget(appWidgetId, args.container, args.screen, null, null); result = true; break; case REQUEST_PICK_WALLPAPER: // We just wanted the activity result here so we can clear mWaitingForResult break; } // Before adding this resetAddInfo(), after a shortcut was added to a workspace screen, // if you turned the screen off and then back while in All Apps, Launcher would not // return to the workspace. Clearing mAddInfo.container here fixes this issue resetAddInfo(); return result; } @Override protected void onActivityResult( final int requestCode, final int resultCode, final Intent data) { if (requestCode == REQUEST_BIND_APPWIDGET) { int appWidgetId = data != null ? data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1; if (resultCode == RESULT_CANCELED) { completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId); } else if (resultCode == RESULT_OK) { addAppWidgetImpl(appWidgetId, mPendingAddInfo, null, mPendingAddWidgetInfo); } return; } boolean delayExitSpringLoadedMode = false; boolean isWidgetDrop = (requestCode == REQUEST_PICK_APPWIDGET || requestCode == REQUEST_CREATE_APPWIDGET); mWaitingForResult = false; // We have special handling for widgets if (isWidgetDrop) { int appWidgetId = data != null ? data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1; if (appWidgetId < 0) { Log.e(TAG, "Error: appWidgetId (EXTRA_APPWIDGET_ID) was not returned from the \\" + "widget configuration activity."); completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId); } else { completeTwoStageWidgetDrop(resultCode, appWidgetId); } return; } // The pattern used here is that a user PICKs a specific application, // which, depending on the target, might need to CREATE the actual target. // For example, the user would PICK_SHORTCUT for "Music playlist", and we // launch over to the Music app to actually CREATE_SHORTCUT. if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) { final PendingAddArguments args = new PendingAddArguments(); args.requestCode = requestCode; args.intent = data; args.container = mPendingAddInfo.container; args.screen = mPendingAddInfo.screen; args.cellX = mPendingAddInfo.cellX; args.cellY = mPendingAddInfo.cellY; if (isWorkspaceLocked()) { sPendingAddList.add(args); } else { delayExitSpringLoadedMode = completeAdd(args); } } mDragLayer.clearAnimatedView(); // Exit spring loaded mode if necessary after cancelling the configuration of a widget exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), delayExitSpringLoadedMode, null); } private void completeTwoStageWidgetDrop(final int resultCode, final int appWidgetId) { CellLayout cellLayout = (CellLayout) mWorkspace.getChildAt(mPendingAddInfo.screen); Runnable onCompleteRunnable = null; int animationType = 0; AppWidgetHostView boundWidget = null; if (resultCode == RESULT_OK) { animationType = Workspace.COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION; final AppWidgetHostView layout = mAppWidgetHost.createView(this, appWidgetId, mPendingAddWidgetInfo); boundWidget = layout; onCompleteRunnable = new Runnable() { @Override public void run() { completeAddAppWidget(appWidgetId, mPendingAddInfo.container, mPendingAddInfo.screen, layout, null); exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false, null); } }; } else if (resultCode == RESULT_CANCELED) { animationType = Workspace.CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION; onCompleteRunnable = new Runnable() { @Override public void run() { exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false, null); } }; } if (mDragLayer.getAnimatedView() != null) { mWorkspace.animateWidgetDrop(mPendingAddInfo, cellLayout, (DragView) mDragLayer.getAnimatedView(), onCompleteRunnable, animationType, boundWidget, true); } else { // The animated view may be null in the case of a rotation during widget configuration onCompleteRunnable.run(); } } @Override protected void onResume() { super.onResume(); // Process any items that were added while Launcher was away InstallShortcutReceiver.flushInstallQueue(this); mPaused = false; if (mRestoring || mOnResumeNeedsLoad) { mWorkspaceLoading = true; mModel.startLoader(true); mRestoring = false; mOnResumeNeedsLoad = false; } // Reset the pressed state of icons that were locked in the press state while activities // were launching if (mWaitingForResume != null) { // Resets the previous workspace icon press state mWaitingForResume.setStayPressed(false); } if (mAppsCustomizeContent != null) { // Resets the previous all apps icon press state mAppsCustomizeContent.resetDrawableState(); } // It is possible that widgets can receive updates while launcher is not in the foreground. // Consequently, the widgets will be inflated in the orientation of the foreground activity // (framework issue). On resuming, we ensure that any widgets are inflated for the current // orientation. getWorkspace().reinflateWidgetsIfNecessary(); // Again, as with the above scenario, it's possible that one or more of the global icons // were updated in the wrong orientation. updateGlobalIcons(); } @Override protected void onPause() { // NOTE: We want all transitions from launcher to act as if the wallpaper were enabled // to be consistent. So re-enable the flag here, and we will re-disable it as necessary // when Launcher resumes and we are still in AllApps. updateWallpaperVisibility(true); super.onPause(); mPaused = true; mDragController.cancelDrag(); mDragController.resetLastGestureUpTime(); } @Override public Object onRetainNonConfigurationInstance() { // Flag the loader to stop early before switching mModel.stopLoader(); if (mAppsCustomizeContent != null) { mAppsCustomizeContent.surrender(); } return Boolean.TRUE; } // We can't hide the IME if it was forced open. So don't bother /* @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); WindowManager.LayoutParams lp = getWindow().getAttributes(); inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new android.os.Handler()) { protected void onReceiveResult(int resultCode, Bundle resultData) { Log.d(TAG, "ResultReceiver got resultCode=" + resultCode); } }); Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged"); } } */ private boolean acceptFilter() { final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); return !inputManager.isFullscreenMode(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { final int uniChar = event.getUnicodeChar(); final boolean handled = super.onKeyDown(keyCode, event); final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar); if (!handled && acceptFilter() && isKeyNotWhitespace) { boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb, keyCode, event); if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) { // something usable has been typed - start a search // the typed text will be retrieved and cleared by // showSearchDialog() // If there are multiple keystrokes before the search dialog takes focus, // onSearchRequested() will be called for every keystroke, // but it is idempotent, so it's fine. return onSearchRequested(); } } // Eat the long press event so the keyboard doesn't come up. if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) { return true; } return handled; } private String getTypedText() { return mDefaultKeySsb.toString(); } private void clearTypedText() { mDefaultKeySsb.clear(); mDefaultKeySsb.clearSpans(); Selection.setSelection(mDefaultKeySsb, 0); } /** * Given the integer (ordinal) value of a State enum instance, convert it to a variable of type * State */ private static State intToState(int stateOrdinal) { State state = State.WORKSPACE; final State[] stateValues = State.values(); for (int i = 0; i < stateValues.length; i++) { if (stateValues[i].ordinal() == stateOrdinal) { state = stateValues[i]; break; } } return state; } /** * Restores the previous state, if it exists. * * @param savedState The previous state. */ private void restoreState(Bundle savedState) { if (savedState == null) { return; } State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal())); if (state == State.APPS_CUSTOMIZE) { showAllApps(false); } int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1); if (currentScreen > -1) { mWorkspace.setCurrentPage(currentScreen); } final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1); final int pendingAddScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1); if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) { mPendingAddInfo.container = pendingAddContainer; mPendingAddInfo.screen = pendingAddScreen; mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X); mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y); mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X); mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y); mPendingAddWidgetInfo = savedState.getParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO); mWaitingForResult = true; mRestoring = true; } boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false); if (renameFolder) { long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID); mFolderInfo = mModel.getFolderById(this, sFolders, id); mRestoring = true; } // Restore the AppsCustomize tab if (mAppsCustomizeTabHost != null) { String curTab = savedState.getString("apps_customize_currentTab"); if (curTab != null) { // We set this directly so that there is no delay before the tab is set mAppsCustomizeContent.setContentType( mAppsCustomizeTabHost.getContentTypeForTabTag(curTab)); mAppsCustomizeTabHost.setCurrentTabByTag(curTab); mAppsCustomizeContent.loadAssociatedPages( mAppsCustomizeContent.getCurrentPage()); } int currentIndex = savedState.getInt("apps_customize_currentIndex"); mAppsCustomizeContent.restorePageForIndex(currentIndex); } } /** * Finds all the views we need and configure them properly. */ private void setupViews() { final DragController dragController = mDragController; mDragLayer = (DragLayer) findViewById(R.id.drag_layer); mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace); mQsbDivider = (ImageView) findViewById(R.id.qsb_divider); mDockDivider = (ImageView) findViewById(R.id.dock_divider); // Setup the drag layer mDragLayer.setup(this, dragController); // Setup the hotseat mHotseat = (Hotseat) findViewById(R.id.hotseat); if (mHotseat != null) { mHotseat.setup(this); } // Setup the workspace mWorkspace.setHapticFeedbackEnabled(false); mWorkspace.setOnLongClickListener(this); mWorkspace.setup(dragController); dragController.addDragListener(mWorkspace); // Get the search/delete bar mSearchDropTargetBar = (SearchDropTargetBar) mDragLayer.findViewById(R.id.qsb_bar); // Setup AppsCustomize mAppsCustomizeTabHost = (AppsCustomizeTabHost) findViewById(R.id.apps_customize_pane); mAppsCustomizeContent = (AppsCustomizePagedView) mAppsCustomizeTabHost.findViewById(R.id.apps_customize_pane_content); mAppsCustomizeTabHost.setup(this); mAppsCustomizeContent.setup(this, dragController); // Get the all apps button mAllAppsButton = findViewById(R.id.all_apps_button); if (mAllAppsButton != null) { mAllAppsButton.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) { onTouchDownAllAppsButton(v); } return false; } }); } // Setup the drag controller (drop targets have to be added in reverse order in priority) dragController.setDragScoller(mWorkspace); dragController.setScrollView(mDragLayer); dragController.setMoveTarget(mWorkspace); dragController.addDropTarget(mWorkspace); if (mSearchDropTargetBar != null) { mSearchDropTargetBar.setup(this, dragController); } } /** * Creates a view representing a shortcut. * * @param info The data structure describing the shortcut. * * @return A View inflated from R.layout.application. */ View createShortcut(ShortcutInfo info) { return createShortcut(R.layout.application, (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info); } /** * Creates a view representing a shortcut inflated from the specified resource. * * @param layoutResId The id of the XML layout used to create the shortcut. * @param parent The group the shortcut belongs to. * @param info The data structure describing the shortcut. * * @return A View inflated from layoutResId. */ View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) { BubbleTextView favorite = (BubbleTextView) mInflater.inflate(layoutResId, parent, false); favorite.applyFromShortcutInfo(info, mIconCache); favorite.setOnClickListener(this); return favorite; } /** * Add an application shortcut to the workspace. * * @param data The intent describing the application. * @param cellInfo The position on screen where to create the shortcut. */ void completeAddApplication(Intent data, long container, int screen, int cellX, int cellY) { final int[] cellXY = mTmpAddItemCellCoordinates; final CellLayout layout = getCellLayout(container, screen); // First we check if we already know the exact location where we want to add this item. if (cellX >= 0 && cellY >= 0) { cellXY[0] = cellX; cellXY[1] = cellY; } else if (!layout.findCellForSpan(cellXY, 1, 1)) { showOutOfSpaceMessage(isHotseatLayout(layout)); return; } final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this); if (info != null) { info.setActivity(data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); info.container = ItemInfo.NO_ID; mWorkspace.addApplicationShortcut(info, layout, container, screen, cellXY[0], cellXY[1], isWorkspaceLocked(), cellX, cellY); } else { Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data); } } /** * Add a shortcut to the workspace. * * @param data The intent describing the shortcut. * @param cellInfo The position on screen where to create the shortcut. */ private void completeAddShortcut(Intent data, long container, int screen, int cellX, int cellY) { int[] cellXY = mTmpAddItemCellCoordinates; int[] touchXY = mPendingAddInfo.dropPos; CellLayout layout = getCellLayout(container, screen); boolean foundCellSpan = false; ShortcutInfo info = mModel.infoFromShortcutIntent(this, data, null); if (info == null) { return; } final View view = createShortcut(info); // First we check if we already know the exact location where we want to add this item. if (cellX >= 0 && cellY >= 0) { cellXY[0] = cellX; cellXY[1] = cellY; foundCellSpan = true; // If appropriate, either create a folder or add to an existing folder if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0, true, null,null)) { return; } DragObject dragObject = new DragObject(); dragObject.dragInfo = info; if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject, true)) { return; } } else if (touchXY != null) { // when dragging and dropping, just find the closest free spot int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY); foundCellSpan = (result != null); } else { foundCellSpan = layout.findCellForSpan(cellXY, 1, 1); } if (!foundCellSpan) { showOutOfSpaceMessage(isHotseatLayout(layout)); return; } LauncherModel.addItemToDatabase(this, info, container, screen, cellXY[0], cellXY[1], false); if (!mRestoring) { mWorkspace.addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, isWorkspaceLocked()); } } static int[] getSpanForWidget(Context context, ComponentName component, int minWidth, int minHeight) { Rect padding = AppWidgetHostView.getDefaultPaddingForWidget(context, component, null); // We want to account for the extra amount of padding that we are adding to the widget // to ensure that it gets the full amount of space that it has requested int requiredWidth = minWidth + padding.left + padding.right; int requiredHeight = minHeight + padding.top + padding.bottom; return CellLayout.rectToCell(context.getResources(), requiredWidth, requiredHeight, null); } static int[] getSpanForWidget(Context context, AppWidgetProviderInfo info) { return getSpanForWidget(context, info.provider, info.minWidth, info.minHeight); } static int[] getMinSpanForWidget(Context context, AppWidgetProviderInfo info) { return getSpanForWidget(context, info.provider, info.minResizeWidth, info.minResizeHeight); } static int[] getSpanForWidget(Context context, PendingAddWidgetInfo info) { return getSpanForWidget(context, info.componentName, info.minWidth, info.minHeight); } static int[] getMinSpanForWidget(Context context, PendingAddWidgetInfo info) { return getSpanForWidget(context, info.componentName, info.minResizeWidth, info.minResizeHeight); } /** * Add a widget to the workspace. * * @param appWidgetId The app widget id * @param cellInfo The position on screen where to create the widget. */ private void completeAddAppWidget(final int appWidgetId, long container, int screen, AppWidgetHostView hostView, AppWidgetProviderInfo appWidgetInfo) { if (appWidgetInfo == null) { appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); } // Calculate the grid spans needed to fit this widget CellLayout layout = getCellLayout(container, screen); int[] minSpanXY = getMinSpanForWidget(this, appWidgetInfo); int[] spanXY = getSpanForWidget(this, appWidgetInfo); // Try finding open space on Launcher screen // We have saved the position to which the widget was dragged-- this really only matters // if we are placing widgets on a "spring-loaded" screen int[] cellXY = mTmpAddItemCellCoordinates; int[] touchXY = mPendingAddInfo.dropPos; int[] finalSpan = new int[2]; boolean foundCellSpan = false; if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) { cellXY[0] = mPendingAddInfo.cellX; cellXY[1] = mPendingAddInfo.cellY; spanXY[0] = mPendingAddInfo.spanX; spanXY[1] = mPendingAddInfo.spanY; foundCellSpan = true; } else if (touchXY != null) { // when dragging and dropping, just find the closest free spot int[] result = layout.findNearestVacantArea( touchXY[0], touchXY[1], minSpanXY[0], minSpanXY[1], spanXY[0], spanXY[1], cellXY, finalSpan); spanXY[0] = finalSpan[0]; spanXY[1] = finalSpan[1]; foundCellSpan = (result != null); } else { foundCellSpan = layout.findCellForSpan(cellXY, minSpanXY[0], minSpanXY[1]); } if (!foundCellSpan) { if (appWidgetId != -1) { // Deleting an app widget ID is a void call but writes to disk before returning // to the caller... new Thread("deleteAppWidgetId") { public void run() { mAppWidgetHost.deleteAppWidgetId(appWidgetId); } }.start(); } showOutOfSpaceMessage(isHotseatLayout(layout)); return; } // Build Launcher-specific widget info and save to database LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId, appWidgetInfo.provider); launcherInfo.spanX = spanXY[0]; launcherInfo.spanY = spanXY[1]; launcherInfo.minSpanX = mPendingAddInfo.minSpanX; launcherInfo.minSpanY = mPendingAddInfo.minSpanY; LauncherModel.addItemToDatabase(this, launcherInfo, container, screen, cellXY[0], cellXY[1], false); if (!mRestoring) { if (hostView == null) { // Perform actual inflation because we're live launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo); launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo); } else { // The AppWidgetHostView has already been inflated and instantiated launcherInfo.hostView = hostView; } launcherInfo.hostView.setTag(launcherInfo); launcherInfo.hostView.setVisibility(View.VISIBLE); launcherInfo.notifyWidgetSizeChanged(this); mWorkspace.addInScreen(launcherInfo.hostView, container, screen, cellXY[0], cellXY[1], launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked()); addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo); } resetAddInfo(); } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (Intent.ACTION_SCREEN_OFF.equals(action)) { mUserPresent = false; mDragLayer.clearAllResizeFrames(); updateRunning(); // Reset AllApps to its initial state only if we are not in the middle of // processing a multi-step drop if (mAppsCustomizeTabHost != null && mPendingAddInfo.container == ItemInfo.NO_ID) { mAppsCustomizeTabHost.reset(); showWorkspace(false); } } else if (Intent.ACTION_USER_PRESENT.equals(action)) { mUserPresent = true; updateRunning(); } } }; @Override public void onAttachedToWindow() { super.onAttachedToWindow(); // Listen for broadcasts related to user-presence final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT); registerReceiver(mReceiver, filter); mAttached = true; mVisible = true; } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); mVisible = false; if (mAttached) { unregisterReceiver(mReceiver); mAttached = false; } updateRunning(); } public void onWindowVisibilityChanged(int visibility) { mVisible = visibility == View.VISIBLE; updateRunning(); // The following code used to be in onResume, but it turns out onResume is called when // you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged // is a more appropriate event to handle if (mVisible) { mAppsCustomizeTabHost.onWindowVisible(); if (!mWorkspaceLoading) { final ViewTreeObserver observer = mWorkspace.getViewTreeObserver(); // We want to let Launcher draw itself at least once before we force it to build // layers on all the workspace pages, so that transitioning to Launcher from other // apps is nice and speedy. Usually the first call to preDraw doesn't correspond to // a true draw so we wait until the second preDraw call to be safe observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { // We delay the layer building a bit in order to give // other message processing a time to run. In particular // this avoids a delay in hiding the IME if it was // currently shown, because doing that may involve // some communication back with the app. mWorkspace.postDelayed(mBuildLayersRunnable, 500); observer.removeOnPreDrawListener(this); return true; } }); } // When Launcher comes back to foreground, a different Activity might be responsible for // the app market intent, so refresh the icon updateAppMarketIcon(); clearTypedText(); } } private void sendAdvanceMessage(long delay) { mHandler.removeMessages(ADVANCE_MSG); Message msg = mHandler.obtainMessage(ADVANCE_MSG); mHandler.sendMessageDelayed(msg, delay); mAutoAdvanceSentTime = System.currentTimeMillis(); } private void updateRunning() { boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty(); if (autoAdvanceRunning != mAutoAdvanceRunning) { mAutoAdvanceRunning = autoAdvanceRunning; if (autoAdvanceRunning) { long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft; sendAdvanceMessage(delay); } else { if (!mWidgetsToAdvance.isEmpty()) { mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval - (System.currentTimeMillis() - mAutoAdvanceSentTime)); } mHandler.removeMessages(ADVANCE_MSG); mHandler.removeMessages(0); // Remove messages sent using postDelayed() } } } private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == ADVANCE_MSG) { int i = 0; for (View key: mWidgetsToAdvance.keySet()) { final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId); final int delay = mAdvanceStagger * i; if (v instanceof Advanceable) { postDelayed(new Runnable() { public void run() { ((Advanceable) v).advance(); } }, delay); } i++; } sendAdvanceMessage(mAdvanceInterval); } } }; void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) { if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return; View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId); if (v instanceof Advanceable) { mWidgetsToAdvance.put(hostView, appWidgetInfo); ((Advanceable) v).fyiWillBeAdvancedByHostKThx(); updateRunning(); } } void removeWidgetToAutoAdvance(View hostView) { if (mWidgetsToAdvance.containsKey(hostView)) { mWidgetsToAdvance.remove(hostView); updateRunning(); } } public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) { removeWidgetToAutoAdvance(launcherInfo.hostView); launcherInfo.hostView = null; } void showOutOfSpaceMessage(boolean isHotseatLayout) { int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space); Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show(); } public LauncherAppWidgetHost getAppWidgetHost() { return mAppWidgetHost; } public LauncherModel getModel() { return mModel; } void closeSystemDialogs() { getWindow().closeAllPanels(); // Whatever we were doing is hereby canceled. mWaitingForResult = false; } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); // Close the menu if (Intent.ACTION_MAIN.equals(intent.getAction())) { // also will cancel mWaitingForResult. closeSystemDialogs(); boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); Folder openFolder = mWorkspace.getOpenFolder(); // In all these cases, only animate if we're already on home mWorkspace.exitWidgetResizeMode(); if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() && openFolder == null) { mWorkspace.moveToDefaultScreen(true); } closeFolder(); exitSpringLoadedDragMode(); showWorkspace(alreadyOnHome); final View v = getWindow().peekDecorView(); if (v != null && v.getWindowToken() != null) { InputMethodManager imm = (InputMethodManager)getSystemService( INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } // Reset AllApps to its initial state if (!alreadyOnHome && mAppsCustomizeTabHost != null) { mAppsCustomizeTabHost.reset(); } } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { // Do not call super here mSavedInstanceState = savedInstanceState; } @Override protected void onSaveInstanceState(Bundle outState) { outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentPage()); super.onSaveInstanceState(outState); outState.putInt(RUNTIME_STATE, mState.ordinal()); // We close any open folder since it will not be re-opened, and we need to make sure // this state is reflected. closeFolder(); if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screen > -1 && mWaitingForResult) { outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container); outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screen); outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX); outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY); outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX); outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY); outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo); } if (mFolderInfo != null && mWaitingForResult) { outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true); outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id); } // Save the current AppsCustomize tab if (mAppsCustomizeTabHost != null) { String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag(); if (currentTabTag != null) { outState.putString("apps_customize_currentTab", currentTabTag); } int currentIndex = mAppsCustomizeContent.getSaveInstanceStateIndex(); outState.putInt("apps_customize_currentIndex", currentIndex); } } @Override public void onDestroy() { super.onDestroy(); // Remove all pending runnables mHandler.removeMessages(ADVANCE_MSG); mHandler.removeMessages(0); mWorkspace.removeCallbacks(mBuildLayersRunnable); // Stop callbacks from LauncherModel LauncherApplication app = ((LauncherApplication) getApplication()); mModel.stopLoader(); app.setLauncher(null); try { mAppWidgetHost.stopListening(); } catch (NullPointerException ex) { Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex); } mAppWidgetHost = null; mWidgetsToAdvance.clear(); TextKeyListener.getInstance().release(); unbindWorkspaceAndHotseatItems(); getContentResolver().unregisterContentObserver(mWidgetObserver); unregisterReceiver(mCloseSystemDialogsReceiver); mDragLayer.clearAllResizeFrames(); ((ViewGroup) mWorkspace.getParent()).removeAllViews(); mWorkspace.removeAllViews(); mWorkspace = null; mDragController = null; ValueAnimator.clearAllAnimations(); } public DragController getDragController() { return mDragController; } @Override public void startActivityForResult(Intent intent, int requestCode) { if (requestCode >= 0) mWaitingForResult = true; super.startActivityForResult(intent, requestCode); } /** * Indicates that we want global search for this activity by setting the globalSearch * argument for {@link #startSearch} to true. */ @Override public void startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch) { showWorkspace(true); if (initialQuery == null) { // Use any text typed in the launcher as the initial query initialQuery = getTypedText(); } if (appSearchData == null) { appSearchData = new Bundle(); appSearchData.putString(Search.SOURCE, "launcher-search"); } Rect sourceBounds = mSearchDropTargetBar.getSearchBarBounds(); final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(), appSearchData, globalSearch, sourceBounds); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (isWorkspaceLocked()) { return false; } super.onCreateOptionsMenu(menu); Intent manageApps = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS); manageApps.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS); settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); String helpUrl = getString(R.string.help_url); Intent help = new Intent(Intent.ACTION_VIEW, Uri.parse(helpUrl)); help.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper) .setIcon(android.R.drawable.ic_menu_gallery) .setAlphabeticShortcut('W'); menu.add(0, MENU_MANAGE_APPS, 0, R.string.menu_manage_apps) .setIcon(android.R.drawable.ic_menu_manage) .setIntent(manageApps) .setAlphabeticShortcut('M'); menu.add(0, MENU_SYSTEM_SETTINGS, 0, R.string.menu_settings) .setIcon(android.R.drawable.ic_menu_preferences) .setIntent(settings) .setAlphabeticShortcut('P'); if (!helpUrl.isEmpty()) { menu.add(0, MENU_HELP, 0, R.string.menu_help) .setIcon(android.R.drawable.ic_menu_help) .setIntent(help) .setAlphabeticShortcut('H'); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (mAppsCustomizeTabHost.isTransitioning()) { return false; } boolean allAppsVisible = (mAppsCustomizeTabHost.getVisibility() == View.VISIBLE); menu.setGroupVisible(MENU_GROUP_WALLPAPER, !allAppsVisible); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_WALLPAPER_SETTINGS: startWallpaper(); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onSearchRequested() { startSearch(null, false, null, true); // Use a custom animation for launching search overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast); return true; } public boolean isWorkspaceLocked() { return mWorkspaceLoading || mWaitingForResult; } private void resetAddInfo() { mPendingAddInfo.container = ItemInfo.NO_ID; mPendingAddInfo.screen = -1; mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1; mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1; mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = -1; mPendingAddInfo.dropPos = null; } void addAppWidgetImpl(final int appWidgetId, ItemInfo info, AppWidgetHostView boundWidget, AppWidgetProviderInfo appWidgetInfo) { if (appWidgetInfo.configure != null) { mPendingAddWidgetInfo = appWidgetInfo; // Launch over to configure widget, if needed Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE); intent.setComponent(appWidgetInfo.configure); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET); } else { // Otherwise just add it completeAddAppWidget(appWidgetId, info.container, info.screen, boundWidget, appWidgetInfo); // Exit spring loaded mode if necessary after adding the widget exitSpringLoadedDragModeDelayed(true, false, null); } } /** * Process a shortcut drop. * * @param componentName The name of the component * @param screen The screen where it should be added * @param cell The cell it should be added to, optional * @param position The location on the screen where it was dropped, optional */ void processShortcutFromDrop(ComponentName componentName, long container, int screen, int[] cell, int[] loc) { resetAddInfo(); mPendingAddInfo.container = container; mPendingAddInfo.screen = screen; mPendingAddInfo.dropPos = loc; if (cell != null) { mPendingAddInfo.cellX = cell[0]; mPendingAddInfo.cellY = cell[1]; } Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); createShortcutIntent.setComponent(componentName); processShortcut(createShortcutIntent); } /** * Process a widget drop. * * @param info The PendingAppWidgetInfo of the widget being added. * @param screen The screen where it should be added * @param cell The cell it should be added to, optional * @param position The location on the screen where it was dropped, optional */ void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, int screen, int[] cell, int[] span, int[] loc) { resetAddInfo(); mPendingAddInfo.container = info.container = container; mPendingAddInfo.screen = info.screen = screen; mPendingAddInfo.dropPos = loc; mPendingAddInfo.minSpanX = info.minSpanX; mPendingAddInfo.minSpanY = info.minSpanY; if (cell != null) { mPendingAddInfo.cellX = cell[0]; mPendingAddInfo.cellY = cell[1]; } if (span != null) { mPendingAddInfo.spanX = span[0]; mPendingAddInfo.spanY = span[1]; } AppWidgetHostView hostView = info.boundWidget; int appWidgetId; if (hostView != null) { appWidgetId = hostView.getAppWidgetId(); addAppWidgetImpl(appWidgetId, info, hostView, info.info); } else { // In this case, we either need to start an activity to get permission to bind // the widget, or we need to start an activity to configure the widget, or both. appWidgetId = getAppWidgetHost().allocateAppWidgetId(); if (mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, info.componentName)) { addAppWidgetImpl(appWidgetId, info, null, info.info); } else { mPendingAddWidgetInfo = info.info; Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.componentName); startActivityForResult(intent, REQUEST_BIND_APPWIDGET); } } } void processShortcut(Intent intent) { // Handle case where user selected "Applications" String applicationName = getResources().getString(R.string.group_applications); String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); if (applicationName != null && applicationName.equals(shortcutName)) { Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent); pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application)); startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION); } else { startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT); } } void processWallpaper(Intent intent) { startActivityForResult(intent, REQUEST_PICK_WALLPAPER); } FolderIcon addFolder(CellLayout layout, long container, final int screen, int cellX, int cellY) { final FolderInfo folderInfo = new FolderInfo(); folderInfo.title = getText(R.string.folder_name); // Update the model LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screen, cellX, cellY, false); sFolders.put(folderInfo.id, folderInfo); // Create the view FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache); mWorkspace.addInScreen(newFolder, container, screen, cellX, cellY, 1, 1, isWorkspaceLocked()); return newFolder; } void removeFolder(FolderInfo folder) { sFolders.remove(folder.id); } private void startWallpaper() { showWorkspace(true); final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER); Intent chooser = Intent.createChooser(pickWallpaper, getText(R.string.chooser_wallpaper)); // NOTE: Adds a configure option to the chooser if the wallpaper supports it // Removed in Eclair MR1 // WallpaperManager wm = (WallpaperManager) // getSystemService(Context.WALLPAPER_SERVICE); // WallpaperInfo wi = wm.getWallpaperInfo(); // if (wi != null && wi.getSettingsActivity() != null) { // LabeledIntent li = new LabeledIntent(getPackageName(), // R.string.configure_wallpaper, 0); // li.setClassName(wi.getPackageName(), wi.getSettingsActivity()); // chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li }); // } startActivityForResult(chooser, REQUEST_PICK_WALLPAPER); } /** * Registers various content observers. The current implementation registers * only a favorites observer to keep track of the favorites applications. */ private void registerContentObservers() { ContentResolver resolver = getContentResolver(); resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI, true, mWidgetObserver); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_HOME: return true; case KeyEvent.KEYCODE_VOLUME_DOWN: if (SystemProperties.getInt("debug.launcher2.dumpstate", 0) != 0) { dumpState(); return true; } break; } } else if (event.getAction() == KeyEvent.ACTION_UP) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_HOME: return true; } } return super.dispatchKeyEvent(event); } @Override public void onBackPressed() { if (mState == State.APPS_CUSTOMIZE) { showWorkspace(true); } else if (mWorkspace.getOpenFolder() != null) { Folder openFolder = mWorkspace.getOpenFolder(); if (openFolder.isEditingName()) { openFolder.dismissEditingName(); } else { closeFolder(); } } else { mWorkspace.exitWidgetResizeMode(); // Back button is a no-op here, but give at least some feedback for the button press mWorkspace.showOutlinesTemporarily(); } } /** * Re-listen when widgets are reset. */ private void onAppWidgetReset() { if (mAppWidgetHost != null) { mAppWidgetHost.startListening(); } } /** * Go through the and disconnect any of the callbacks in the drawables and the views or we * leak the previous Home screen on orientation change. */ private void unbindWorkspaceAndHotseatItems() { if (mModel != null) { mModel.unbindWorkspaceItems(); } } /** * Launches the intent referred by the clicked shortcut. * * @param v The view representing the clicked shortcut. */ public void onClick(View v) { // Make sure that rogue clicks don't get through while allapps is launching, or after the // view has detached (it's possible for this to happen if the view is removed mid touch). if (v.getWindowToken() == null) { return; } if (!mWorkspace.isFinishedSwitchingState()) { return; } Object tag = v.getTag(); if (tag instanceof ShortcutInfo) { // Open shortcut final Intent intent = ((ShortcutInfo) tag).intent; int[] pos = new int[2]; v.getLocationOnScreen(pos); intent.setSourceBounds(new Rect(pos[0], pos[1], pos[0] + v.getWidth(), pos[1] + v.getHeight())); boolean success = startActivitySafely(v, intent, tag); if (success && v instanceof BubbleTextView) { mWaitingForResume = (BubbleTextView) v; mWaitingForResume.setStayPressed(true); } } else if (tag instanceof FolderInfo) { if (v instanceof FolderIcon) { FolderIcon fi = (FolderIcon) v; handleFolderClick(fi); } } else if (v == mAllAppsButton) { if (mState == State.APPS_CUSTOMIZE) { showWorkspace(true); } else { onClickAllAppsButton(v); } } } public boolean onTouch(View v, MotionEvent event) { // this is an intercepted event being forwarded from mWorkspace; // clicking anywhere on the workspace causes the customization drawer to slide down showWorkspace(true); return false; } /** * Event handler for the search button * * @param v The view that was clicked. */ public void onClickSearchButton(View v) { v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); onSearchRequested(); } /** * Event handler for the voice button * * @param v The view that was clicked. */ public void onClickVoiceButton(View v) { v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); try { final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); ComponentName activityName = searchManager.getGlobalSearchActivity(); Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (activityName != null) { intent.setPackage(activityName.getPackageName()); } startActivity(null, intent, "onClickVoiceButton"); overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast); } catch (ActivityNotFoundException e) { Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivitySafely(null, intent, "onClickVoiceButton"); } } /** * Event handler for the "grid" button that appears on the home screen, which * enters all apps mode. * * @param v The view that was clicked. */ public void onClickAllAppsButton(View v) { showAllApps(true); } public void onTouchDownAllAppsButton(View v) { // Provide the same haptic feedback that the system offers for virtual keys. v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); } public void onClickAppMarketButton(View v) { if (mAppMarketIntent != null) { startActivitySafely(v, mAppMarketIntent, "app market"); } else { Log.e(TAG, "Invalid app market intent."); } } void startApplicationDetailsActivity(ComponentName componentName) { String packageName = componentName.getPackageName(); Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", packageName, null)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivitySafely(null, intent, "startApplicationDetailsActivity"); } void startApplicationUninstallActivity(ApplicationInfo appInfo) { if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) { // System applications cannot be installed. For now, show a toast explaining that. // We may give them the option of disabling apps this way. int messageId = R.string.uninstall_system_app_text; Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show(); } else { String packageName = appInfo.componentName.getPackageName(); String className = appInfo.componentName.getClassName(); Intent intent = new Intent( Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(intent); } } boolean startActivity(View v, Intent intent, Object tag) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { // Only launch using the new animation if the shortcut has not opted out (this is a // private contract between launcher and may be ignored in the future). boolean useLaunchAnimation = (v != null) && !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION); if (useLaunchAnimation) { ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); startActivity(intent, opts.toBundle()); } else { startActivity(intent); } return true; } catch (SecurityException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Launcher does not have the permission to launch " + intent + ". Make sure to create a MAIN intent-filter for the corresponding activity " + "or use the exported attribute for this activity. " + "tag="+ tag + " intent=" + intent, e); } return false; } boolean startActivitySafely(View v, Intent intent, Object tag) { boolean success = false; try { success = startActivity(v, intent, tag); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e); } return success; } void startActivityForResultSafely(Intent intent, int requestCode) { try { startActivityForResult(intent, requestCode); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); } catch (SecurityException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Launcher does not have the permission to launch " + intent + ". Make sure to create a MAIN intent-filter for the corresponding activity " + "or use the exported attribute for this activity.", e); } } private void handleFolderClick(FolderIcon folderIcon) { final FolderInfo info = folderIcon.mInfo; Folder openFolder = mWorkspace.getFolderForTag(info); // If the folder info reports that the associated folder is open, then verify that // it is actually opened. There have been a few instances where this gets out of sync. if (info.opened && openFolder == null) { Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: " + info.screen + " (" + info.cellX + ", " + info.cellY + ")"); info.opened = false; } if (!info.opened) { // Close any open folder closeFolder(); // Open the requested folder openFolder(folderIcon); } else { // Find the open folder... int folderScreen; if (openFolder != null) { folderScreen = mWorkspace.getPageForView(openFolder); // .. and close it closeFolder(openFolder); if (folderScreen != mWorkspace.getCurrentPage()) { // Close any folder open on the current screen closeFolder(); // Pull the folder onto this screen openFolder(folderIcon); } } } } /** * This method draws the FolderIcon to an ImageView and then adds and positions that ImageView * in the DragLayer in the exact absolute location of the original FolderIcon. */ private void copyFolderIconToImage(FolderIcon fi) { final int width = fi.getMeasuredWidth(); final int height = fi.getMeasuredHeight(); // Lazy load ImageView, Bitmap and Canvas if (mFolderIconImageView == null) { mFolderIconImageView = new ImageView(this); } if (mFolderIconBitmap == null || mFolderIconBitmap.getWidth() != width || mFolderIconBitmap.getHeight() != height) { mFolderIconBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mFolderIconCanvas = new Canvas(mFolderIconBitmap); } DragLayer.LayoutParams lp; if (mFolderIconImageView.getLayoutParams() instanceof DragLayer.LayoutParams) { lp = (DragLayer.LayoutParams) mFolderIconImageView.getLayoutParams(); } else { lp = new DragLayer.LayoutParams(width, height); } mDragLayer.getViewRectRelativeToSelf(fi, mRectForFolderAnimation); lp.customPosition = true; lp.x = mRectForFolderAnimation.left; lp.y = mRectForFolderAnimation.top; lp.width = width; lp.height = height; mFolderIconCanvas.drawColor(0, PorterDuff.Mode.CLEAR); fi.draw(mFolderIconCanvas); mFolderIconImageView.setImageBitmap(mFolderIconBitmap); if (fi.mFolder != null) { mFolderIconImageView.setPivotX(fi.mFolder.getPivotXForIconAnimation()); mFolderIconImageView.setPivotY(fi.mFolder.getPivotYForIconAnimation()); } // Just in case this image view is still in the drag layer from a previous animation, // we remove it and re-add it. if (mDragLayer.indexOfChild(mFolderIconImageView) != -1) { mDragLayer.removeView(mFolderIconImageView); } mDragLayer.addView(mFolderIconImageView, lp); if (fi.mFolder != null) { fi.mFolder.bringToFront(); } } private void growAndFadeOutFolderIcon(FolderIcon fi) { if (fi == null) return; PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0); PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f); PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f); FolderInfo info = (FolderInfo) fi.getTag(); if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { CellLayout cl = (CellLayout) fi.getParent().getParent(); CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams(); cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY); } // Push an ImageView copy of the FolderIcon into the DragLayer and hide the original copyFolderIconToImage(fi); fi.setVisibility(View.INVISIBLE); ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(mFolderIconImageView, alpha, scaleX, scaleY); oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration)); oa.start(); } private void shrinkAndFadeInFolderIcon(final FolderIcon fi) { if (fi == null) return; PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f); PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f); PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f); final CellLayout cl = (CellLayout) fi.getParent().getParent(); // We remove and re-draw the FolderIcon in-case it has changed mDragLayer.removeView(mFolderIconImageView); copyFolderIconToImage(fi); ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(mFolderIconImageView, alpha, scaleX, scaleY); oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration)); oa.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (cl != null) { cl.clearFolderLeaveBehind(); // Remove the ImageView copy of the FolderIcon and make the original visible. mDragLayer.removeView(mFolderIconImageView); fi.setVisibility(View.VISIBLE); } } }); oa.start(); } /** * Opens the user folder described by the specified tag. The opening of the folder * is animated relative to the specified View. If the View is null, no animation * is played. * * @param folderInfo The FolderInfo describing the folder to open. */ public void openFolder(FolderIcon folderIcon) { Folder folder = folderIcon.mFolder; FolderInfo info = folder.mInfo; info.opened = true; // Just verify that the folder hasn't already been added to the DragLayer. // There was a one-off crash where the folder had a parent already. if (folder.getParent() == null) { mDragLayer.addView(folder); mDragController.addDropTarget((DropTarget) folder); } else { Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" + folder.getParent() + ")."); } folder.animateOpen(); growAndFadeOutFolderIcon(folderIcon); } public void closeFolder() { Folder folder = mWorkspace.getOpenFolder(); if (folder != null) { if (folder.isEditingName()) { folder.dismissEditingName(); } closeFolder(folder); // Dismiss the folder cling dismissFolderCling(null); } } void closeFolder(Folder folder) { folder.getInfo().opened = false; ViewGroup parent = (ViewGroup) folder.getParent().getParent(); if (parent != null) { FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo); shrinkAndFadeInFolderIcon(fi); } folder.animateClosed(); } public boolean onLongClick(View v) { if (!isDraggingEnabled()) return false; if (isWorkspaceLocked()) return false; if (mState != State.WORKSPACE) return false; if (!(v instanceof CellLayout)) { v = (View) v.getParent().getParent(); } resetAddInfo(); CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag(); // This happens when long clicking an item with the dpad/trackball if (longClickCellInfo == null) { return true; } // The hotseat touch handling does not go through Workspace, and we always allow long press // on hotseat items. final View itemUnderLongClick = longClickCellInfo.cell; boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress(); if (allowLongPress && !mDragController.isDragging()) { if (itemUnderLongClick == null) { // User long pressed on empty space mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); startWallpaper(); } else { if (!(itemUnderLongClick instanceof Folder)) { // User long pressed on an item mWorkspace.startDrag(longClickCellInfo); } } } return true; } boolean isHotseatLayout(View layout) { return mHotseat != null && layout != null && (layout instanceof CellLayout) && (layout == mHotseat.getLayout()); } Hotseat getHotseat() { return mHotseat; } SearchDropTargetBar getSearchBar() { return mSearchDropTargetBar; } /** * Returns the CellLayout of the specified container at the specified screen. */ CellLayout getCellLayout(long container, int screen) { if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (mHotseat != null) { return mHotseat.getLayout(); } else { return null; } } else { return (CellLayout) mWorkspace.getChildAt(screen); } } Workspace getWorkspace() { return mWorkspace; } // Now a part of LauncherModel.Callbacks. Used to reorder loading steps. public boolean isAllAppsVisible() { return (mState == State.APPS_CUSTOMIZE); } public boolean isAllAppsButtonRank(int rank) { return mHotseat.isAllAppsButtonRank(rank); } // AllAppsView.Watcher public void zoomed(float zoom) { if (zoom == 1.0f) { mWorkspace.setVisibility(View.GONE); } } /** * Helper method for the cameraZoomIn/cameraZoomOut animations * @param view The view being animated * @param state The state that we are moving in or out of (eg. APPS_CUSTOMIZE) * @param scaleFactor The scale factor used for the zoom */ private void setPivotsForZoom(View view, float scaleFactor) { view.setPivotX(view.getWidth() / 2.0f); view.setPivotY(view.getHeight() / 2.0f); } void disableWallpaperIfInAllApps() { // Only disable it if we are in all apps if (mState == State.APPS_CUSTOMIZE) { if (mAppsCustomizeTabHost != null && !mAppsCustomizeTabHost.isTransitioning()) { updateWallpaperVisibility(false); } } } void updateWallpaperVisibility(boolean visible) { int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0; int curflags = getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER; if (wpflags != curflags) { getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER); } } private void dispatchOnLauncherTransitionPrepare(View v, boolean animated, boolean toWorkspace) { if (v instanceof LauncherTransitionable) { ((LauncherTransitionable) v).onLauncherTransitionPrepare(this, animated, toWorkspace); } } private void dispatchOnLauncherTransitionStart(View v, boolean animated, boolean toWorkspace) { if (toWorkspace) { Log.d(TAG, "6549598 Start animation to workspace"); } else { Log.d(TAG, "6549598 Start animation to all apps"); } if (v instanceof LauncherTransitionable) { ((LauncherTransitionable) v).onLauncherTransitionStart(this, animated, toWorkspace); } // Update the workspace transition step as well dispatchOnLauncherTransitionStep(v, 0f); } private void dispatchOnLauncherTransitionStep(View v, float t) { if (v instanceof LauncherTransitionable) { ((LauncherTransitionable) v).onLauncherTransitionStep(this, t); } } private void dispatchOnLauncherTransitionEnd(View v, boolean animated, boolean toWorkspace) { if (toWorkspace) { Log.d(TAG, "6549598 End animation to workspace"); } else { Log.d(TAG, "6549598 End animation to all apps"); } if (v instanceof LauncherTransitionable) { ((LauncherTransitionable) v).onLauncherTransitionEnd(this, animated, toWorkspace); } // Update the workspace transition step as well dispatchOnLauncherTransitionStep(v, 1f); } /** * Things to test when changing the following seven functions. * - Home from workspace * - from center screen * - from other screens * - Home from all apps * - from center screen * - from other screens * - Back from all apps * - from center screen * - from other screens * - Launch app from workspace and quit * - with back * - with home * - Launch app from all apps and quit * - with back * - with home * - Go to a screen that's not the default, then all * apps, and launch and app, and go back * - with back * -with home * - On workspace, long press power and go back * - with back * - with home * - On all apps, long press power and go back * - with back * - with home * - On workspace, power off * - On all apps, power off * - Launch an app and turn off the screen while in that app * - Go back with home key * - Go back with back key TODO: make this not go to workspace * - From all apps * - From workspace * - Enter and exit car mode (becuase it causes an extra configuration changed) * - From all apps * - From the center workspace * - From another workspace */ /** * Zoom the camera out from the workspace to reveal 'toView'. * Assumes that the view to show is anchored at either the very top or very bottom * of the screen. */ private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) { if (mStateAnimation != null) { mStateAnimation.cancel(); mStateAnimation = null; } final Resources res = getResources(); final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime); final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime); final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor); final View fromView = mWorkspace; final AppsCustomizeTabHost toView = mAppsCustomizeTabHost; final int startDelay = res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger); setPivotsForZoom(toView, scale); // Shrink workspaces away if going to AppsCustomize from workspace Animator workspaceAnim = mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated); if (animated) { toView.setScaleX(scale); toView.setScaleY(scale); final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView); scaleAnim. scaleX(1f).scaleY(1f). setDuration(duration). setInterpolator(new Workspace.ZoomOutInterpolator()); toView.setVisibility(View.VISIBLE); toView.setAlpha(0f); final ObjectAnimator alphaAnim = ObjectAnimator .ofFloat(toView, "alpha", 0f, 1f) .setDuration(fadeDuration); alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f)); alphaAnim.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float t = (Float) animation.getAnimatedValue(); dispatchOnLauncherTransitionStep(fromView, t); dispatchOnLauncherTransitionStep(toView, t); } }); // toView should appear right at the end of the workspace shrink // animation mStateAnimation = new AnimatorSet(); mStateAnimation.play(scaleAnim).after(startDelay); mStateAnimation.play(alphaAnim).after(startDelay); mStateAnimation.addListener(new AnimatorListenerAdapter() { boolean animationCancelled = false; @Override public void onAnimationStart(Animator animation) { updateWallpaperVisibility(true); // Prepare the position toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setVisibility(View.VISIBLE); toView.bringToFront(); } @Override public void onAnimationEnd(Animator animation) { dispatchOnLauncherTransitionEnd(fromView, animated, false); dispatchOnLauncherTransitionEnd(toView, animated, false); if (!springLoaded && !LauncherApplication.isScreenLarge()) { // Hide the workspace scrollbar mWorkspace.hideScrollingIndicator(true); hideDockDivider(); } if (!animationCancelled) { updateWallpaperVisibility(false); } // Hide the search bar mSearchDropTargetBar.hideSearchBar(false); } @Override public void onAnimationCancel(Animator animation) { animationCancelled = true; } }); if (workspaceAnim != null) { mStateAnimation.play(workspaceAnim); } boolean delayAnim = false; final ViewTreeObserver observer; dispatchOnLauncherTransitionPrepare(fromView, animated, false); dispatchOnLauncherTransitionPrepare(toView, animated, false); // If any of the objects being animated haven't been measured/laid out // yet, delay the animation until we get a layout pass if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) || (mWorkspace.getMeasuredWidth() == 0) || (toView.getMeasuredWidth() == 0)) { observer = mWorkspace.getViewTreeObserver(); delayAnim = true; } else { observer = null; } final AnimatorSet stateAnimation = mStateAnimation; final Runnable startAnimRunnable = new Runnable() { public void run() { // Check that mStateAnimation hasn't changed while // we waited for a layout/draw pass if (mStateAnimation != stateAnimation) return; setPivotsForZoom(toView, scale); dispatchOnLauncherTransitionStart(fromView, animated, false); dispatchOnLauncherTransitionStart(toView, animated, false); - mWorkspace.post(new Runnable() { + toView.post(new Runnable() { public void run() { // Check that mStateAnimation hasn't changed while // we waited for a layout/draw pass if (mStateAnimation != stateAnimation) return; mStateAnimation.start(); } }); } }; if (delayAnim) { final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() { public void onGlobalLayout() { - mWorkspace.post(startAnimRunnable); + toView.post(startAnimRunnable); observer.removeOnGlobalLayoutListener(this); } }; observer.addOnGlobalLayoutListener(delayedStart); } else { startAnimRunnable.run(); } } else { toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setScaleX(1.0f); toView.setScaleY(1.0f); toView.setVisibility(View.VISIBLE); toView.bringToFront(); if (!springLoaded && !LauncherApplication.isScreenLarge()) { // Hide the workspace scrollbar mWorkspace.hideScrollingIndicator(true); hideDockDivider(); // Hide the search bar mSearchDropTargetBar.hideSearchBar(false); } dispatchOnLauncherTransitionPrepare(fromView, animated, false); dispatchOnLauncherTransitionStart(fromView, animated, false); dispatchOnLauncherTransitionEnd(fromView, animated, false); dispatchOnLauncherTransitionPrepare(toView, animated, false); dispatchOnLauncherTransitionStart(toView, animated, false); dispatchOnLauncherTransitionEnd(toView, animated, false); updateWallpaperVisibility(false); } } /** * Zoom the camera back into the workspace, hiding 'fromView'. * This is the opposite of showAppsCustomizeHelper. * @param animated If true, the transition will be animated. */ private void hideAppsCustomizeHelper(State toState, final boolean animated, final boolean springLoaded, final Runnable onCompleteRunnable) { if (mStateAnimation != null) { mStateAnimation.cancel(); mStateAnimation = null; } Resources res = getResources(); final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime); final int fadeOutDuration = res.getInteger(R.integer.config_appsCustomizeFadeOutTime); final float scaleFactor = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor); final View fromView = mAppsCustomizeTabHost; final View toView = mWorkspace; Animator workspaceAnim = null; if (toState == State.WORKSPACE) { int stagger = res.getInteger(R.integer.config_appsCustomizeWorkspaceAnimationStagger); workspaceAnim = mWorkspace.getChangeStateAnimation( Workspace.State.NORMAL, animated, stagger); } else if (toState == State.APPS_CUSTOMIZE_SPRING_LOADED) { workspaceAnim = mWorkspace.getChangeStateAnimation( Workspace.State.SPRING_LOADED, animated); } setPivotsForZoom(fromView, scaleFactor); updateWallpaperVisibility(true); showHotseat(animated); if (animated) { final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(fromView); scaleAnim. scaleX(scaleFactor).scaleY(scaleFactor). setDuration(duration). setInterpolator(new Workspace.ZoomInInterpolator()); final ObjectAnimator alphaAnim = ObjectAnimator .ofFloat(fromView, "alpha", 1f, 0f) .setDuration(fadeOutDuration); alphaAnim.setInterpolator(new AccelerateDecelerateInterpolator()); alphaAnim.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float t = 1f - (Float) animation.getAnimatedValue(); dispatchOnLauncherTransitionStep(fromView, t); dispatchOnLauncherTransitionStep(toView, t); } }); mStateAnimation = new AnimatorSet(); dispatchOnLauncherTransitionPrepare(fromView, animated, true); dispatchOnLauncherTransitionPrepare(toView, animated, true); mStateAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { updateWallpaperVisibility(true); fromView.setVisibility(View.GONE); dispatchOnLauncherTransitionEnd(fromView, animated, true); dispatchOnLauncherTransitionEnd(toView, animated, true); if (mWorkspace != null) { mWorkspace.hideScrollingIndicator(false); } if (onCompleteRunnable != null) { onCompleteRunnable.run(); } } }); mStateAnimation.playTogether(scaleAnim, alphaAnim); if (workspaceAnim != null) { mStateAnimation.play(workspaceAnim); } dispatchOnLauncherTransitionStart(fromView, animated, true); dispatchOnLauncherTransitionStart(toView, animated, true); final Animator stateAnimation = mStateAnimation; mWorkspace.post(new Runnable() { public void run() { if (stateAnimation != mStateAnimation) return; mStateAnimation.start(); } }); } else { fromView.setVisibility(View.GONE); dispatchOnLauncherTransitionPrepare(fromView, animated, true); dispatchOnLauncherTransitionStart(fromView, animated, true); dispatchOnLauncherTransitionEnd(fromView, animated, true); dispatchOnLauncherTransitionPrepare(toView, animated, true); dispatchOnLauncherTransitionStart(toView, animated, true); dispatchOnLauncherTransitionEnd(toView, animated, true); mWorkspace.hideScrollingIndicator(false); } } @Override public void onTrimMemory(int level) { super.onTrimMemory(level); if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) { mAppsCustomizeTabHost.onTrimMemory(); } } @Override public void onWindowFocusChanged(boolean hasFocus) { if (!hasFocus) { // When another window occludes launcher (like the notification shade, or recents), // ensure that we enable the wallpaper flag so that transitions are done correctly. updateWallpaperVisibility(true); } else { // When launcher has focus again, disable the wallpaper if we are in AllApps mWorkspace.postDelayed(new Runnable() { @Override public void run() { disableWallpaperIfInAllApps(); } }, 500); } } void showWorkspace(boolean animated) { showWorkspace(animated, null); } void showWorkspace(boolean animated, Runnable onCompleteRunnable) { if (mState != State.WORKSPACE) { boolean wasInSpringLoadedMode = (mState == State.APPS_CUSTOMIZE_SPRING_LOADED); mWorkspace.setVisibility(View.VISIBLE); hideAppsCustomizeHelper(State.WORKSPACE, animated, false, onCompleteRunnable); // Show the search bar (only animate if we were showing the drop target bar in spring // loaded mode) mSearchDropTargetBar.showSearchBar(wasInSpringLoadedMode); // We only need to animate in the dock divider if we're going from spring loaded mode showDockDivider(animated && wasInSpringLoadedMode); // Set focus to the AppsCustomize button if (mAllAppsButton != null) { mAllAppsButton.requestFocus(); } } mWorkspace.flashScrollingIndicator(animated); // Change the state *after* we've called all the transition code mState = State.WORKSPACE; // Resume the auto-advance of widgets mUserPresent = true; updateRunning(); // send an accessibility event to announce the context change getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } void showAllApps(boolean animated) { if (mState != State.WORKSPACE) return; showAppsCustomizeHelper(animated, false); mAppsCustomizeTabHost.requestFocus(); // Change the state *after* we've called all the transition code mState = State.APPS_CUSTOMIZE; // Pause the auto-advance of widgets until we are out of AllApps mUserPresent = false; updateRunning(); closeFolder(); // Send an accessibility event to announce the context change getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } void enterSpringLoadedDragMode() { if (mState == State.APPS_CUSTOMIZE) { hideAppsCustomizeHelper(State.APPS_CUSTOMIZE_SPRING_LOADED, true, true, null); hideDockDivider(); mState = State.APPS_CUSTOMIZE_SPRING_LOADED; } } void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, boolean extendedDelay, final Runnable onCompleteRunnable) { if (mState != State.APPS_CUSTOMIZE_SPRING_LOADED) return; mHandler.postDelayed(new Runnable() { @Override public void run() { if (successfulDrop) { // Before we show workspace, hide all apps again because // exitSpringLoadedDragMode made it visible. This is a bit hacky; we should // clean up our state transition functions mAppsCustomizeTabHost.setVisibility(View.GONE); showWorkspace(true, onCompleteRunnable); } else { exitSpringLoadedDragMode(); } } }, (extendedDelay ? EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT : EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT)); } void exitSpringLoadedDragMode() { if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) { final boolean animated = true; final boolean springLoaded = true; showAppsCustomizeHelper(animated, springLoaded); mState = State.APPS_CUSTOMIZE; } // Otherwise, we are not in spring loaded mode, so don't do anything. } void hideDockDivider() { if (mQsbDivider != null && mDockDivider != null) { mQsbDivider.setVisibility(View.INVISIBLE); mDockDivider.setVisibility(View.INVISIBLE); } } void showDockDivider(boolean animated) { if (mQsbDivider != null && mDockDivider != null) { mQsbDivider.setVisibility(View.VISIBLE); mDockDivider.setVisibility(View.VISIBLE); if (mDividerAnimator != null) { mDividerAnimator.cancel(); mQsbDivider.setAlpha(1f); mDockDivider.setAlpha(1f); mDividerAnimator = null; } if (animated) { mDividerAnimator = new AnimatorSet(); mDividerAnimator.playTogether(ObjectAnimator.ofFloat(mQsbDivider, "alpha", 1f), ObjectAnimator.ofFloat(mDockDivider, "alpha", 1f)); mDividerAnimator.setDuration(mSearchDropTargetBar.getTransitionInDuration()); mDividerAnimator.start(); } } } void lockAllApps() { // TODO } void unlockAllApps() { // TODO } public boolean isAllAppsCustomizeOpen() { return mState == State.APPS_CUSTOMIZE; } /** * Shows the hotseat area. */ void showHotseat(boolean animated) { if (!LauncherApplication.isScreenLarge()) { if (animated) { if (mHotseat.getAlpha() != 1f) { int duration = mSearchDropTargetBar.getTransitionInDuration(); mHotseat.animate().alpha(1f).setDuration(duration); } } else { mHotseat.setAlpha(1f); } } } /** * Hides the hotseat area. */ void hideHotseat(boolean animated) { if (!LauncherApplication.isScreenLarge()) { if (animated) { if (mHotseat.getAlpha() != 0f) { int duration = mSearchDropTargetBar.getTransitionOutDuration(); mHotseat.animate().alpha(0f).setDuration(duration); } } else { mHotseat.setAlpha(0f); } } } /** * Add an item from all apps or customize onto the given workspace screen. * If layout is null, add to the current screen. */ void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) { if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) { showOutOfSpaceMessage(isHotseatLayout(layout)); } } /** Maps the current orientation to an index for referencing orientation correct global icons */ private int getCurrentOrientationIndexForGlobalIcons() { // default - 0, landscape - 1 switch (getResources().getConfiguration().orientation) { case Configuration.ORIENTATION_LANDSCAPE: return 1; default: return 0; } } private Drawable getExternalPackageToolbarIcon(ComponentName activityName, String resourceName) { try { PackageManager packageManager = getPackageManager(); // Look for the toolbar icon specified in the activity meta-data Bundle metaData = packageManager.getActivityInfo( activityName, PackageManager.GET_META_DATA).metaData; if (metaData != null) { int iconResId = metaData.getInt(resourceName); if (iconResId != 0) { Resources res = packageManager.getResourcesForActivity(activityName); return res.getDrawable(iconResId); } } } catch (NameNotFoundException e) { // This can happen if the activity defines an invalid drawable Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() + " not found", e); } catch (Resources.NotFoundException nfe) { // This can happen if the activity defines an invalid drawable Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(), nfe); } return null; } // if successful in getting icon, return it; otherwise, set button to use default drawable private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity( int buttonId, ComponentName activityName, int fallbackDrawableId, String toolbarResourceName) { Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName); Resources r = getResources(); int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width); int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height); TextView button = (TextView) findViewById(buttonId); // If we were unable to find the icon via the meta-data, use a generic one if (toolbarIcon == null) { toolbarIcon = r.getDrawable(fallbackDrawableId); toolbarIcon.setBounds(0, 0, w, h); if (button != null) { button.setCompoundDrawables(toolbarIcon, null, null, null); } return null; } else { toolbarIcon.setBounds(0, 0, w, h); if (button != null) { button.setCompoundDrawables(toolbarIcon, null, null, null); } return toolbarIcon.getConstantState(); } } // if successful in getting icon, return it; otherwise, set button to use default drawable private Drawable.ConstantState updateButtonWithIconFromExternalActivity( int buttonId, ComponentName activityName, int fallbackDrawableId, String toolbarResourceName) { ImageView button = (ImageView) findViewById(buttonId); Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName); if (button != null) { // If we were unable to find the icon via the meta-data, use a // generic one if (toolbarIcon == null) { button.setImageResource(fallbackDrawableId); } else { button.setImageDrawable(toolbarIcon); } } return toolbarIcon != null ? toolbarIcon.getConstantState() : null; } private void updateTextButtonWithDrawable(int buttonId, Drawable.ConstantState d) { TextView button = (TextView) findViewById(buttonId); button.setCompoundDrawables(d.newDrawable(getResources()), null, null, null); } private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) { ImageView button = (ImageView) findViewById(buttonId); button.setImageDrawable(d.newDrawable(getResources())); } private void invalidatePressedFocusedStates(View container, View button) { if (container instanceof HolographicLinearLayout) { HolographicLinearLayout layout = (HolographicLinearLayout) container; layout.invalidatePressedFocusedStates(); } else if (button instanceof HolographicImageView) { HolographicImageView view = (HolographicImageView) button; view.invalidatePressedFocusedStates(); } } private boolean updateGlobalSearchIcon() { final View searchButtonContainer = findViewById(R.id.search_button_container); final ImageView searchButton = (ImageView) findViewById(R.id.search_button); final View searchDivider = findViewById(R.id.search_divider); final View voiceButtonContainer = findViewById(R.id.voice_button_container); final View voiceButton = findViewById(R.id.voice_button); final View voiceButtonProxy = findViewById(R.id.voice_button_proxy); final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); ComponentName activityName = searchManager.getGlobalSearchActivity(); if (activityName != null) { int coi = getCurrentOrientationIndexForGlobalIcons(); sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity( R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo, TOOLBAR_SEARCH_ICON_METADATA_NAME); if (sGlobalSearchIcon[coi] == null) { sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity( R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo, TOOLBAR_ICON_METADATA_NAME); } if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE); if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.VISIBLE); searchButton.setVisibility(View.VISIBLE); invalidatePressedFocusedStates(searchButtonContainer, searchButton); return true; } else { // We disable both search and voice search when there is no global search provider if (searchDivider != null) searchDivider.setVisibility(View.GONE); if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.GONE); if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE); searchButton.setVisibility(View.GONE); voiceButton.setVisibility(View.GONE); if (voiceButtonProxy != null) { voiceButtonProxy.setVisibility(View.GONE); } return false; } } private void updateGlobalSearchIcon(Drawable.ConstantState d) { final View searchButtonContainer = findViewById(R.id.search_button_container); final View searchButton = (ImageView) findViewById(R.id.search_button); updateButtonWithDrawable(R.id.search_button, d); invalidatePressedFocusedStates(searchButtonContainer, searchButton); } private boolean updateVoiceSearchIcon(boolean searchVisible) { final View searchDivider = findViewById(R.id.search_divider); final View voiceButtonContainer = findViewById(R.id.voice_button_container); final View voiceButton = findViewById(R.id.voice_button); final View voiceButtonProxy = findViewById(R.id.voice_button_proxy); // We only show/update the voice search icon if the search icon is enabled as well final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity(); ComponentName activityName = null; if (globalSearchActivity != null) { // Check if the global search activity handles voice search Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); intent.setPackage(globalSearchActivity.getPackageName()); activityName = intent.resolveActivity(getPackageManager()); } if (activityName == null) { // Fallback: check if an activity other than the global search activity // resolves this Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); activityName = intent.resolveActivity(getPackageManager()); } if (searchVisible && activityName != null) { int coi = getCurrentOrientationIndexForGlobalIcons(); sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity( R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo, TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME); if (sVoiceSearchIcon[coi] == null) { sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity( R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo, TOOLBAR_ICON_METADATA_NAME); } if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE); if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.VISIBLE); voiceButton.setVisibility(View.VISIBLE); if (voiceButtonProxy != null) { voiceButtonProxy.setVisibility(View.VISIBLE); } invalidatePressedFocusedStates(voiceButtonContainer, voiceButton); return true; } else { if (searchDivider != null) searchDivider.setVisibility(View.GONE); if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE); voiceButton.setVisibility(View.GONE); if (voiceButtonProxy != null) { voiceButtonProxy.setVisibility(View.GONE); } return false; } } private void updateVoiceSearchIcon(Drawable.ConstantState d) { final View voiceButtonContainer = findViewById(R.id.voice_button_container); final View voiceButton = findViewById(R.id.voice_button); updateButtonWithDrawable(R.id.voice_button, d); invalidatePressedFocusedStates(voiceButtonContainer, voiceButton); } /** * Sets the app market icon */ private void updateAppMarketIcon() { final View marketButton = findViewById(R.id.market_button); Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET); // Find the app market activity by resolving an intent. // (If multiple app markets are installed, it will return the ResolverActivity.) ComponentName activityName = intent.resolveActivity(getPackageManager()); if (activityName != null) { int coi = getCurrentOrientationIndexForGlobalIcons(); mAppMarketIntent = intent; sAppMarketIcon[coi] = updateTextButtonWithIconFromExternalActivity( R.id.market_button, activityName, R.drawable.ic_launcher_market_holo, TOOLBAR_ICON_METADATA_NAME); marketButton.setVisibility(View.VISIBLE); } else { // We should hide and disable the view so that we don't try and restore the visibility // of it when we swap between drag & normal states from IconDropTarget subclasses. marketButton.setVisibility(View.GONE); marketButton.setEnabled(false); } } private void updateAppMarketIcon(Drawable.ConstantState d) { updateTextButtonWithDrawable(R.id.market_button, d); } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { boolean result = super.dispatchPopulateAccessibilityEvent(event); final List<CharSequence> text = event.getText(); text.clear(); text.add(getString(R.string.home)); return result; } /** * Receives notifications when system dialogs are to be closed. */ private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { closeSystemDialogs(); } } /** * Receives notifications whenever the appwidgets are reset. */ private class AppWidgetResetObserver extends ContentObserver { public AppWidgetResetObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { onAppWidgetReset(); } } /** * If the activity is currently paused, signal that we need to re-run the loader * in onResume. * * This needs to be called from incoming places where resources might have been loaded * while we are paused. That is becaues the Configuration might be wrong * when we're not running, and if it comes back to what it was when we * were paused, we are not restarted. * * Implementation of the method from LauncherModel.Callbacks. * * @return true if we are currently paused. The caller might be able to * skip some work in that case since we will come back again. */ public boolean setLoadOnResume() { if (mPaused) { Log.i(TAG, "setLoadOnResume"); mOnResumeNeedsLoad = true; return true; } else { return false; } } /** * Implementation of the method from LauncherModel.Callbacks. */ public int getCurrentWorkspaceScreen() { if (mWorkspace != null) { return mWorkspace.getCurrentPage(); } else { return SCREEN_COUNT / 2; } } /** * Refreshes the shortcuts shown on the workspace. * * Implementation of the method from LauncherModel.Callbacks. */ public void startBinding() { final Workspace workspace = mWorkspace; mNewShortcutAnimatePage = -1; mNewShortcutAnimateViews.clear(); mWorkspace.clearDropTargets(); int count = workspace.getChildCount(); for (int i = 0; i < count; i++) { // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate(). final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i); layoutParent.removeAllViewsInLayout(); } mWidgetsToAdvance.clear(); if (mHotseat != null) { mHotseat.resetLayout(); } } /** * Bind the items start-end from the list. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) { setLoadOnResume(); // Get the list of added shortcuts and intersect them with the set of shortcuts here Set<String> newApps = new HashSet<String>(); newApps = mSharedPrefs.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, newApps); Workspace workspace = mWorkspace; for (int i = start; i < end; i++) { final ItemInfo item = shortcuts.get(i); // Short circuit if we are loading dock items for a configuration which has no dock if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT && mHotseat == null) { continue; } switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: ShortcutInfo info = (ShortcutInfo) item; String uri = info.intent.toUri(0).toString(); View shortcut = createShortcut(info); workspace.addInScreen(shortcut, item.container, item.screen, item.cellX, item.cellY, 1, 1, false); boolean animateIconUp = false; synchronized (newApps) { if (newApps.contains(uri)) { animateIconUp = newApps.remove(uri); } } if (animateIconUp) { // Prepare the view to be animated up shortcut.setAlpha(0f); shortcut.setScaleX(0f); shortcut.setScaleY(0f); mNewShortcutAnimatePage = item.screen; if (!mNewShortcutAnimateViews.contains(shortcut)) { mNewShortcutAnimateViews.add(shortcut); } } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this, (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()), (FolderInfo) item, mIconCache); workspace.addInScreen(newFolder, item.container, item.screen, item.cellX, item.cellY, 1, 1, false); break; } } workspace.requestLayout(); } /** * Implementation of the method from LauncherModel.Callbacks. */ public void bindFolders(HashMap<Long, FolderInfo> folders) { setLoadOnResume(); sFolders.clear(); sFolders.putAll(folders); } /** * Add the views for a widget to the workspace. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindAppWidget(LauncherAppWidgetInfo item) { setLoadOnResume(); final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0; if (DEBUG_WIDGETS) { Log.d(TAG, "bindAppWidget: " + item); } final Workspace workspace = mWorkspace; final int appWidgetId = item.appWidgetId; final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); if (DEBUG_WIDGETS) { Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider); } item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo); item.hostView.setTag(item); item.onBindAppWidget(this); workspace.addInScreen(item.hostView, item.container, item.screen, item.cellX, item.cellY, item.spanX, item.spanY, false); addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo); workspace.requestLayout(); if (DEBUG_WIDGETS) { Log.d(TAG, "bound widget id="+item.appWidgetId+" in " + (SystemClock.uptimeMillis()-start) + "ms"); } } /** * Callback saying that there aren't any more items to bind. * * Implementation of the method from LauncherModel.Callbacks. */ public void finishBindingItems() { setLoadOnResume(); if (mSavedState != null) { if (!mWorkspace.hasFocus()) { mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus(); } mSavedState = null; } if (mSavedInstanceState != null) { super.onRestoreInstanceState(mSavedInstanceState); mSavedInstanceState = null; } // If we received the result of any pending adds while the loader was running (e.g. the // widget configuration forced an orientation change), process them now. for (int i = 0; i < sPendingAddList.size(); i++) { completeAdd(sPendingAddList.get(i)); } sPendingAddList.clear(); // Update the market app icon as necessary (the other icons will be managed in response to // package changes in bindSearchablesChanged() updateAppMarketIcon(); // Animate up any icons as necessary if (mVisible || mWorkspaceLoading) { Runnable newAppsRunnable = new Runnable() { @Override public void run() { runNewAppsAnimation(false); } }; boolean willSnapPage = mNewShortcutAnimatePage > -1 && mNewShortcutAnimatePage != mWorkspace.getCurrentPage(); if (canRunNewAppsAnimation()) { // If the user has not interacted recently, then either snap to the new page to show // the new-apps animation or just run them if they are to appear on the current page if (willSnapPage) { mWorkspace.snapToPage(mNewShortcutAnimatePage, newAppsRunnable); } else { runNewAppsAnimation(false); } } else { // If the user has interacted recently, then just add the items in place if they // are on another page (or just normally if they are added to the current page) runNewAppsAnimation(willSnapPage); } } mWorkspaceLoading = false; } private boolean canRunNewAppsAnimation() { long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime(); return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000); } /** * Runs a new animation that scales up icons that were added while Launcher was in the * background. * * @param immediate whether to run the animation or show the results immediately */ private void runNewAppsAnimation(boolean immediate) { AnimatorSet anim = new AnimatorSet(); Collection<Animator> bounceAnims = new ArrayList<Animator>(); // Order these new views spatially so that they animate in order Collections.sort(mNewShortcutAnimateViews, new Comparator<View>() { @Override public int compare(View a, View b) { CellLayout.LayoutParams alp = (CellLayout.LayoutParams) a.getLayoutParams(); CellLayout.LayoutParams blp = (CellLayout.LayoutParams) b.getLayoutParams(); int cellCountX = LauncherModel.getCellCountX(); return (alp.cellY * cellCountX + alp.cellX) - (blp.cellY * cellCountX + blp.cellX); } }); // Animate each of the views in place (or show them immediately if requested) if (immediate) { for (View v : mNewShortcutAnimateViews) { v.setAlpha(1f); v.setScaleX(1f); v.setScaleY(1f); } } else { for (int i = 0; i < mNewShortcutAnimateViews.size(); ++i) { View v = mNewShortcutAnimateViews.get(i); ValueAnimator bounceAnim = ObjectAnimator.ofPropertyValuesHolder(v, PropertyValuesHolder.ofFloat("alpha", 1f), PropertyValuesHolder.ofFloat("scaleX", 1f), PropertyValuesHolder.ofFloat("scaleY", 1f)); bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION); bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY); bounceAnim.setInterpolator(new SmoothPagedView.OvershootInterpolator()); bounceAnims.add(bounceAnim); } anim.playTogether(bounceAnims); anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mWorkspace.postDelayed(mBuildLayersRunnable, 500); } }); anim.start(); } // Clean up mNewShortcutAnimatePage = -1; mNewShortcutAnimateViews.clear(); new Thread("clearNewAppsThread") { public void run() { mSharedPrefs.edit() .putInt(InstallShortcutReceiver.NEW_APPS_PAGE_KEY, -1) .putStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, null) .commit(); } }.start(); } @Override public void bindSearchablesChanged() { boolean searchVisible = updateGlobalSearchIcon(); boolean voiceVisible = updateVoiceSearchIcon(searchVisible); mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible); } /** * Add the icons for all apps. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindAllApplications(final ArrayList<ApplicationInfo> apps) { // Remove the progress bar entirely; we could also make it GONE // but better to remove it since we know it's not going to be used View progressBar = mAppsCustomizeTabHost. findViewById(R.id.apps_customize_progress_bar); if (progressBar != null) { ((ViewGroup)progressBar.getParent()).removeView(progressBar); } // We just post the call to setApps so the user sees the progress bar // disappear-- otherwise, it just looks like the progress bar froze // which doesn't look great mAppsCustomizeTabHost.post(new Runnable() { public void run() { if (mAppsCustomizeContent != null) { mAppsCustomizeContent.setApps(apps); } } }); } /** * A package was installed. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindAppsAdded(ArrayList<ApplicationInfo> apps) { setLoadOnResume(); if (mAppsCustomizeContent != null) { mAppsCustomizeContent.addApps(apps); } } /** * A package was updated. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) { setLoadOnResume(); if (mWorkspace != null) { mWorkspace.updateShortcuts(apps); } if (mAppsCustomizeContent != null) { mAppsCustomizeContent.updateApps(apps); } } /** * A package was uninstalled. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent) { if (permanent) { mWorkspace.removeItems(apps); } if (mAppsCustomizeContent != null) { mAppsCustomizeContent.removeApps(apps); } // Notify the drag controller mDragController.onAppsRemoved(apps, this); } /** * A number of packages were updated. */ public void bindPackagesUpdated() { if (mAppsCustomizeContent != null) { mAppsCustomizeContent.onPackagesUpdated(); } } private int mapConfigurationOriActivityInfoOri(int configOri) { final Display d = getWindowManager().getDefaultDisplay(); int naturalOri = Configuration.ORIENTATION_LANDSCAPE; switch (d.getRotation()) { case Surface.ROTATION_0: case Surface.ROTATION_180: // We are currently in the same basic orientation as the natural orientation naturalOri = configOri; break; case Surface.ROTATION_90: case Surface.ROTATION_270: // We are currently in the other basic orientation to the natural orientation naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ? Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE; break; } int[] oriMap = { ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE }; // Since the map starts at portrait, we need to offset if this device's natural orientation // is landscape. int indexOffset = 0; if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) { indexOffset = 1; } return oriMap[(d.getRotation() + indexOffset) % 4]; } public boolean isRotationEnabled() { boolean forceEnableRotation = "true".equalsIgnoreCase(SystemProperties.get( FORCE_ENABLE_ROTATION_PROPERTY, "false")); boolean enableRotation = forceEnableRotation || getResources().getBoolean(R.bool.allow_rotation); return enableRotation; } public void lockScreenOrientation() { if (isRotationEnabled()) { setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources() .getConfiguration().orientation)); } } public void unlockScreenOrientation(boolean immediate) { if (isRotationEnabled()) { if (immediate) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } else { mHandler.postDelayed(new Runnable() { public void run() { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } }, mRestoreScreenOrientationDelay); } } } /* Cling related */ private boolean isClingsEnabled() { // disable clings when running in a test harness if(ActivityManager.isRunningInTestHarness()) return false; return true; } private Cling initCling(int clingId, int[] positionData, boolean animate, int delay) { Cling cling = (Cling) findViewById(clingId); if (cling != null) { cling.init(this, positionData); cling.setVisibility(View.VISIBLE); cling.setLayerType(View.LAYER_TYPE_HARDWARE, null); cling.requestAccessibilityFocus(); if (animate) { cling.buildLayer(); cling.setAlpha(0f); cling.animate() .alpha(1f) .setInterpolator(new AccelerateInterpolator()) .setDuration(SHOW_CLING_DURATION) .setStartDelay(delay) .start(); } else { cling.setAlpha(1f); } } return cling; } private void dismissCling(final Cling cling, final String flag, int duration) { if (cling != null) { ObjectAnimator anim = ObjectAnimator.ofFloat(cling, "alpha", 0f); anim.setDuration(duration); anim.addListener(new AnimatorListenerAdapter() { public void onAnimationEnd(Animator animation) { cling.setVisibility(View.GONE); cling.cleanup(); // We should update the shared preferences on a background thread new Thread("dismissClingThread") { public void run() { SharedPreferences.Editor editor = mSharedPrefs.edit(); editor.putBoolean(flag, true); editor.commit(); } }.start(); }; }); anim.start(); } } private void removeCling(int id) { final View cling = findViewById(id); if (cling != null) { final ViewGroup parent = (ViewGroup) cling.getParent(); parent.post(new Runnable() { @Override public void run() { parent.removeView(cling); } }); } } private boolean skipCustomClingIfNoAccounts() { Cling cling = (Cling) findViewById(R.id.workspace_cling); boolean customCling = cling.getDrawIdentifier().equals("workspace_custom"); if (customCling) { AccountManager am = AccountManager.get(this); Account[] accounts = am.getAccountsByType("com.google"); return accounts.length == 0; } return false; } public void showFirstRunWorkspaceCling() { // Enable the clings only if they have not been dismissed before if (isClingsEnabled() && !mSharedPrefs.getBoolean(Cling.WORKSPACE_CLING_DISMISSED_KEY, false) && !skipCustomClingIfNoAccounts() ) { initCling(R.id.workspace_cling, null, false, 0); } else { removeCling(R.id.workspace_cling); } } public void showFirstRunAllAppsCling(int[] position) { // Enable the clings only if they have not been dismissed before if (isClingsEnabled() && !mSharedPrefs.getBoolean(Cling.ALLAPPS_CLING_DISMISSED_KEY, false)) { initCling(R.id.all_apps_cling, position, true, 0); } else { removeCling(R.id.all_apps_cling); } } public Cling showFirstRunFoldersCling() { // Enable the clings only if they have not been dismissed before if (isClingsEnabled() && !mSharedPrefs.getBoolean(Cling.FOLDER_CLING_DISMISSED_KEY, false)) { return initCling(R.id.folder_cling, null, true, 0); } else { removeCling(R.id.folder_cling); return null; } } public boolean isFolderClingVisible() { Cling cling = (Cling) findViewById(R.id.folder_cling); if (cling != null) { return cling.getVisibility() == View.VISIBLE; } return false; } public void dismissWorkspaceCling(View v) { Cling cling = (Cling) findViewById(R.id.workspace_cling); dismissCling(cling, Cling.WORKSPACE_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION); } public void dismissAllAppsCling(View v) { Cling cling = (Cling) findViewById(R.id.all_apps_cling); dismissCling(cling, Cling.ALLAPPS_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION); } public void dismissFolderCling(View v) { Cling cling = (Cling) findViewById(R.id.folder_cling); dismissCling(cling, Cling.FOLDER_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION); } /** * Prints out out state for debugging. */ public void dumpState() { Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this); Log.d(TAG, "mSavedState=" + mSavedState); Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading); Log.d(TAG, "mRestoring=" + mRestoring); Log.d(TAG, "mWaitingForResult=" + mWaitingForResult); Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState); Log.d(TAG, "sFolders.size=" + sFolders.size()); mModel.dumpState(); if (mAppsCustomizeContent != null) { mAppsCustomizeContent.dumpState(); } Log.d(TAG, "END launcher2 dump state"); } @Override public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { super.dump(prefix, fd, writer, args); writer.println(" "); writer.println("Debug logs: "); for (int i = 0; i < sDumpLogs.size(); i++) { writer.println(" " + sDumpLogs.get(i)); } } } interface LauncherTransitionable { View getContent(); void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace); void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace); void onLauncherTransitionStep(Launcher l, float t); void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace); }
false
true
private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) { if (mStateAnimation != null) { mStateAnimation.cancel(); mStateAnimation = null; } final Resources res = getResources(); final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime); final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime); final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor); final View fromView = mWorkspace; final AppsCustomizeTabHost toView = mAppsCustomizeTabHost; final int startDelay = res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger); setPivotsForZoom(toView, scale); // Shrink workspaces away if going to AppsCustomize from workspace Animator workspaceAnim = mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated); if (animated) { toView.setScaleX(scale); toView.setScaleY(scale); final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView); scaleAnim. scaleX(1f).scaleY(1f). setDuration(duration). setInterpolator(new Workspace.ZoomOutInterpolator()); toView.setVisibility(View.VISIBLE); toView.setAlpha(0f); final ObjectAnimator alphaAnim = ObjectAnimator .ofFloat(toView, "alpha", 0f, 1f) .setDuration(fadeDuration); alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f)); alphaAnim.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float t = (Float) animation.getAnimatedValue(); dispatchOnLauncherTransitionStep(fromView, t); dispatchOnLauncherTransitionStep(toView, t); } }); // toView should appear right at the end of the workspace shrink // animation mStateAnimation = new AnimatorSet(); mStateAnimation.play(scaleAnim).after(startDelay); mStateAnimation.play(alphaAnim).after(startDelay); mStateAnimation.addListener(new AnimatorListenerAdapter() { boolean animationCancelled = false; @Override public void onAnimationStart(Animator animation) { updateWallpaperVisibility(true); // Prepare the position toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setVisibility(View.VISIBLE); toView.bringToFront(); } @Override public void onAnimationEnd(Animator animation) { dispatchOnLauncherTransitionEnd(fromView, animated, false); dispatchOnLauncherTransitionEnd(toView, animated, false); if (!springLoaded && !LauncherApplication.isScreenLarge()) { // Hide the workspace scrollbar mWorkspace.hideScrollingIndicator(true); hideDockDivider(); } if (!animationCancelled) { updateWallpaperVisibility(false); } // Hide the search bar mSearchDropTargetBar.hideSearchBar(false); } @Override public void onAnimationCancel(Animator animation) { animationCancelled = true; } }); if (workspaceAnim != null) { mStateAnimation.play(workspaceAnim); } boolean delayAnim = false; final ViewTreeObserver observer; dispatchOnLauncherTransitionPrepare(fromView, animated, false); dispatchOnLauncherTransitionPrepare(toView, animated, false); // If any of the objects being animated haven't been measured/laid out // yet, delay the animation until we get a layout pass if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) || (mWorkspace.getMeasuredWidth() == 0) || (toView.getMeasuredWidth() == 0)) { observer = mWorkspace.getViewTreeObserver(); delayAnim = true; } else { observer = null; } final AnimatorSet stateAnimation = mStateAnimation; final Runnable startAnimRunnable = new Runnable() { public void run() { // Check that mStateAnimation hasn't changed while // we waited for a layout/draw pass if (mStateAnimation != stateAnimation) return; setPivotsForZoom(toView, scale); dispatchOnLauncherTransitionStart(fromView, animated, false); dispatchOnLauncherTransitionStart(toView, animated, false); mWorkspace.post(new Runnable() { public void run() { // Check that mStateAnimation hasn't changed while // we waited for a layout/draw pass if (mStateAnimation != stateAnimation) return; mStateAnimation.start(); } }); } }; if (delayAnim) { final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() { public void onGlobalLayout() { mWorkspace.post(startAnimRunnable); observer.removeOnGlobalLayoutListener(this); } }; observer.addOnGlobalLayoutListener(delayedStart); } else { startAnimRunnable.run(); } } else { toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setScaleX(1.0f); toView.setScaleY(1.0f); toView.setVisibility(View.VISIBLE); toView.bringToFront(); if (!springLoaded && !LauncherApplication.isScreenLarge()) { // Hide the workspace scrollbar mWorkspace.hideScrollingIndicator(true); hideDockDivider(); // Hide the search bar mSearchDropTargetBar.hideSearchBar(false); } dispatchOnLauncherTransitionPrepare(fromView, animated, false); dispatchOnLauncherTransitionStart(fromView, animated, false); dispatchOnLauncherTransitionEnd(fromView, animated, false); dispatchOnLauncherTransitionPrepare(toView, animated, false); dispatchOnLauncherTransitionStart(toView, animated, false); dispatchOnLauncherTransitionEnd(toView, animated, false); updateWallpaperVisibility(false); } }
private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) { if (mStateAnimation != null) { mStateAnimation.cancel(); mStateAnimation = null; } final Resources res = getResources(); final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime); final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime); final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor); final View fromView = mWorkspace; final AppsCustomizeTabHost toView = mAppsCustomizeTabHost; final int startDelay = res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger); setPivotsForZoom(toView, scale); // Shrink workspaces away if going to AppsCustomize from workspace Animator workspaceAnim = mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated); if (animated) { toView.setScaleX(scale); toView.setScaleY(scale); final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView); scaleAnim. scaleX(1f).scaleY(1f). setDuration(duration). setInterpolator(new Workspace.ZoomOutInterpolator()); toView.setVisibility(View.VISIBLE); toView.setAlpha(0f); final ObjectAnimator alphaAnim = ObjectAnimator .ofFloat(toView, "alpha", 0f, 1f) .setDuration(fadeDuration); alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f)); alphaAnim.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float t = (Float) animation.getAnimatedValue(); dispatchOnLauncherTransitionStep(fromView, t); dispatchOnLauncherTransitionStep(toView, t); } }); // toView should appear right at the end of the workspace shrink // animation mStateAnimation = new AnimatorSet(); mStateAnimation.play(scaleAnim).after(startDelay); mStateAnimation.play(alphaAnim).after(startDelay); mStateAnimation.addListener(new AnimatorListenerAdapter() { boolean animationCancelled = false; @Override public void onAnimationStart(Animator animation) { updateWallpaperVisibility(true); // Prepare the position toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setVisibility(View.VISIBLE); toView.bringToFront(); } @Override public void onAnimationEnd(Animator animation) { dispatchOnLauncherTransitionEnd(fromView, animated, false); dispatchOnLauncherTransitionEnd(toView, animated, false); if (!springLoaded && !LauncherApplication.isScreenLarge()) { // Hide the workspace scrollbar mWorkspace.hideScrollingIndicator(true); hideDockDivider(); } if (!animationCancelled) { updateWallpaperVisibility(false); } // Hide the search bar mSearchDropTargetBar.hideSearchBar(false); } @Override public void onAnimationCancel(Animator animation) { animationCancelled = true; } }); if (workspaceAnim != null) { mStateAnimation.play(workspaceAnim); } boolean delayAnim = false; final ViewTreeObserver observer; dispatchOnLauncherTransitionPrepare(fromView, animated, false); dispatchOnLauncherTransitionPrepare(toView, animated, false); // If any of the objects being animated haven't been measured/laid out // yet, delay the animation until we get a layout pass if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) || (mWorkspace.getMeasuredWidth() == 0) || (toView.getMeasuredWidth() == 0)) { observer = mWorkspace.getViewTreeObserver(); delayAnim = true; } else { observer = null; } final AnimatorSet stateAnimation = mStateAnimation; final Runnable startAnimRunnable = new Runnable() { public void run() { // Check that mStateAnimation hasn't changed while // we waited for a layout/draw pass if (mStateAnimation != stateAnimation) return; setPivotsForZoom(toView, scale); dispatchOnLauncherTransitionStart(fromView, animated, false); dispatchOnLauncherTransitionStart(toView, animated, false); toView.post(new Runnable() { public void run() { // Check that mStateAnimation hasn't changed while // we waited for a layout/draw pass if (mStateAnimation != stateAnimation) return; mStateAnimation.start(); } }); } }; if (delayAnim) { final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() { public void onGlobalLayout() { toView.post(startAnimRunnable); observer.removeOnGlobalLayoutListener(this); } }; observer.addOnGlobalLayoutListener(delayedStart); } else { startAnimRunnable.run(); } } else { toView.setTranslationX(0.0f); toView.setTranslationY(0.0f); toView.setScaleX(1.0f); toView.setScaleY(1.0f); toView.setVisibility(View.VISIBLE); toView.bringToFront(); if (!springLoaded && !LauncherApplication.isScreenLarge()) { // Hide the workspace scrollbar mWorkspace.hideScrollingIndicator(true); hideDockDivider(); // Hide the search bar mSearchDropTargetBar.hideSearchBar(false); } dispatchOnLauncherTransitionPrepare(fromView, animated, false); dispatchOnLauncherTransitionStart(fromView, animated, false); dispatchOnLauncherTransitionEnd(fromView, animated, false); dispatchOnLauncherTransitionPrepare(toView, animated, false); dispatchOnLauncherTransitionStart(toView, animated, false); dispatchOnLauncherTransitionEnd(toView, animated, false); updateWallpaperVisibility(false); } }
diff --git a/raven/src/main/java/net/kencochrane/raven/event/EventBuilder.java b/raven/src/main/java/net/kencochrane/raven/event/EventBuilder.java index 96b48c4c..a1ce5272 100644 --- a/raven/src/main/java/net/kencochrane/raven/event/EventBuilder.java +++ b/raven/src/main/java/net/kencochrane/raven/event/EventBuilder.java @@ -1,313 +1,313 @@ package net.kencochrane.raven.event; import net.kencochrane.raven.event.interfaces.SentryInterface; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; import java.util.zip.CRC32; import java.util.zip.Checksum; /** * Builder to assist the creation of {@link Event}s. */ public class EventBuilder { /** * Default platform if it isn't set manually. */ public static final String DEFAULT_PLATFORM = "java"; /** * Default hostname if it isn't set manually (or can't be determined). */ public static final String DEFAULT_HOSTNAME = "unavailable"; private final Event event; private boolean alreadyBuilt = false; /** * Creates a new EventBuilder to prepare a new {@link Event}. * <p> * Automatically generates the id of the new event. * </p> */ public EventBuilder() { this(UUID.randomUUID()); } /** * Creates a new EventBuilder to prepare a new {@link Event}. * * @param eventId unique identifier for the new event. */ public EventBuilder(UUID eventId) { this.event = new Event(eventId); } /** * Calculates a checksum for a given string. * * @param string string from which a checksum should be obtained * @return a checksum allowing two events with the same properties to be grouped later. */ private static String calculateChecksum(String string) { byte[] bytes = string.getBytes(); Checksum checksum = new CRC32(); checksum.update(bytes, 0, bytes.length); return String.valueOf(checksum.getValue()); } /** * Obtains the current hostname. * * @return the current hostname, or {@link #DEFAULT_HOSTNAME} if it couldn't be determined. */ private static String getHostname() { try { // TODO: Cache this info return InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { return DEFAULT_HOSTNAME; } } /** * Sets default values for each field that hasn't been provided manually. * * @param event currently handled event. */ private static void autoSetMissingValues(Event event) { // Ensure that a timestamp is set (to now at least!) if (event.getTimestamp() == null) event.setTimestamp(new Date()); // Ensure that a platform is set if (event.getPlatform() == null) event.setPlatform(DEFAULT_PLATFORM); // Ensure that a hostname is set if (event.getServerName() == null) event.setServerName(getHostname()); } /** * Ensures that every field in the {@code Event} are immutable to avoid confusion later. * * @param event event to make immutable. */ private static void makeImmutable(Event event) { // Make the tags unmodifiable - Map<String, Set<String>> unmodifiablesTags = new HashMap<String, Set<String>>(event.getTags().size()); + Map<String, Set<String>> unmodifiableTags = new HashMap<String, Set<String>>(event.getTags().size()); for (Map.Entry<String, Set<String>> tag : event.getTags().entrySet()) { - unmodifiablesTags.put(tag.getKey(), Collections.unmodifiableSet(tag.getValue())); + unmodifiableTags.put(tag.getKey(), Collections.unmodifiableSet(tag.getValue())); } - event.setTags(Collections.unmodifiableMap(unmodifiablesTags)); + event.setTags(Collections.unmodifiableMap(unmodifiableTags)); // Make the extra properties unmodifiable (everything in it is still mutable though) event.setExtra(Collections.unmodifiableMap(event.getExtra())); // Make the SentryInterfaces unmodifiable event.setSentryInterfaces(Collections.unmodifiableMap(event.getSentryInterfaces())); } /** * Determines the culprit value for an event based on a {@code Throwable}. * * @param throwable throwable caught, responsible of the event. * @return the name of the method/class responsible for the event, based on the {@code Throwable}. */ private static String determineCulprit(Throwable throwable) { Throwable currentThrowable = throwable; String culprit = null; // Attempts to go through each cause, in case the last ones do not provide a stacktrace. while (currentThrowable != null) { StackTraceElement[] elements = currentThrowable.getStackTrace(); if (elements.length > 0) { StackTraceElement trace = elements[0]; culprit = trace.getClassName() + "." + trace.getMethodName(); } currentThrowable = currentThrowable.getCause(); } return culprit; } /** * Sets the message in the event. * * @param message message of the event. * @return the current {@code EventBuilder} for chained calls. */ public EventBuilder setMessage(String message) { event.setMessage(message); return this; } /** * Sets the timestamp in the event. * * @param timestamp timestamp of the event. * @return the current {@code EventBuilder} for chained calls. */ public EventBuilder setTimestamp(Date timestamp) { event.setTimestamp(timestamp); return this; } /** * Sets the log level in the event. * * @param level log level of the event. * @return the current {@code EventBuilder} for chained calls. */ public EventBuilder setLevel(Event.Level level) { event.setLevel(level); return this; } /** * Sets the logger in the event. * * @param logger logger of the event. * @return the current {@code EventBuilder} for chained calls. */ public EventBuilder setLogger(String logger) { event.setLogger(logger); return this; } /** * Sets the platform in the event. * * @param platform platform of the event. * @return the current {@code EventBuilder} for chained calls. */ public EventBuilder setPlatform(String platform) { event.setPlatform(platform); return this; } /** * Sets the culprit in the event based on a {@code Throwable}. * * @param throwable throwable responsible of the event. * @return the current {@code EventBuilder} for chained calls. */ public EventBuilder setCulprit(Throwable throwable) { return setCulprit(determineCulprit(throwable)); } /** * Sets the culprit in the event. * * @param culprit culprit. * @return the current {@code EventBuilder} for chained calls. */ public EventBuilder setCulprit(String culprit) { event.setCulprit(culprit); return this; } /** * Adds a tag to an event. * <p> * Multiple calls to {@code addTag} allow to have more that one value for a single tag.<br /> * This allows to set a tag value in different contexts. * </p> * * @param tagKey name of the tag. * @param tagValue value of the tag. * @return the current {@code EventBuilder} for chained calls. */ //TODO: Check that the tag system works indeed this way. public EventBuilder addTag(String tagKey, String tagValue) { Set<String> tagValues = event.getTags().get(tagKey); if (tagValues == null) { tagValues = new HashSet<String>(); event.getTags().put(tagKey, tagValues); } tagValues.add(tagValue); return this; } /** * Sets the serverName in the event. * * @param serverName name of the server responsible for the event. * @return the current {@code EventBuilder} for chained calls. */ public EventBuilder setServerName(String serverName) { event.setServerName(serverName); return this; } /** * Adds an extra property to the event. * * @param extraName name of the extra property. * @param extraValue value of the extra property. * @return the current {@code EventBuilder} for chained calls. */ public EventBuilder addExtra(String extraName, Object extraValue) { event.getExtra().put(extraName, extraValue); return this; } /** * Generates a checksum from a given content and set it to the current event. * * @param contentToChecksum content to checksum. * @return the current {@code EventBuilder} for chained calls. */ public EventBuilder generateChecksum(String contentToChecksum) { return setChecksum(calculateChecksum(contentToChecksum)); } /** * Sets the checksum for the current event. * <p> * It's recommended to rely instead on the checksum system provided by Sentry. * </p> * * @param checksum checksum for the event. * @return the current {@code EventBuilder} for chained calls. */ public EventBuilder setChecksum(String checksum) { event.setChecksum(checksum); return this; } /** * Adds a {@link SentryInterface} to the event. * <p> * If a {@code SentryInterface} with the same interface name has already been added, the new one will replace * the old one. * </p> * * @param sentryInterface sentry interface to add to the event. * @return the current {@code EventBuilder} for chained calls. */ public EventBuilder addSentryInterface(SentryInterface sentryInterface) { event.getSentryInterfaces().put(sentryInterface.getInterfaceName(), sentryInterface); return this; } /** * Finalises the {@link Event} and returns it. * <p> * This operations will automatically set the missing values and make the mutable values immutable. * </p> * * @return an immutable event. */ public Event build() { if (alreadyBuilt) throw new IllegalStateException("A message can't be built twice"); autoSetMissingValues(event); makeImmutable(event); // Lock it only when everything has been set, in case of exception it should be possible to try to build again. alreadyBuilt = true; return event; } }
false
true
private static void makeImmutable(Event event) { // Make the tags unmodifiable Map<String, Set<String>> unmodifiablesTags = new HashMap<String, Set<String>>(event.getTags().size()); for (Map.Entry<String, Set<String>> tag : event.getTags().entrySet()) { unmodifiablesTags.put(tag.getKey(), Collections.unmodifiableSet(tag.getValue())); } event.setTags(Collections.unmodifiableMap(unmodifiablesTags)); // Make the extra properties unmodifiable (everything in it is still mutable though) event.setExtra(Collections.unmodifiableMap(event.getExtra())); // Make the SentryInterfaces unmodifiable event.setSentryInterfaces(Collections.unmodifiableMap(event.getSentryInterfaces())); }
private static void makeImmutable(Event event) { // Make the tags unmodifiable Map<String, Set<String>> unmodifiableTags = new HashMap<String, Set<String>>(event.getTags().size()); for (Map.Entry<String, Set<String>> tag : event.getTags().entrySet()) { unmodifiableTags.put(tag.getKey(), Collections.unmodifiableSet(tag.getValue())); } event.setTags(Collections.unmodifiableMap(unmodifiableTags)); // Make the extra properties unmodifiable (everything in it is still mutable though) event.setExtra(Collections.unmodifiableMap(event.getExtra())); // Make the SentryInterfaces unmodifiable event.setSentryInterfaces(Collections.unmodifiableMap(event.getSentryInterfaces())); }
diff --git a/MPesaXlsImporter/src/main/java/ke/co/safaricom/MPesaXlsImporter.java b/MPesaXlsImporter/src/main/java/ke/co/safaricom/MPesaXlsImporter.java index c28e085..cfd200b 100644 --- a/MPesaXlsImporter/src/main/java/ke/co/safaricom/MPesaXlsImporter.java +++ b/MPesaXlsImporter/src/main/java/ke/co/safaricom/MPesaXlsImporter.java @@ -1,672 +1,682 @@ /* * Copyright (c) 2005-2010 Grameen Foundation USA * All rights reserved. * * 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. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package ke.co.safaricom; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.joda.time.LocalDate; import org.mifos.StandardImport; import org.mifos.accounts.api.AccountPaymentParametersDto; import org.mifos.accounts.api.AccountReferenceDto; import org.mifos.accounts.api.CustomerDto; import org.mifos.accounts.api.InvalidPaymentReason; import org.mifos.accounts.api.PaymentTypeDto; import org.mifos.spi.ParseResultDto; /** * This class implements mpesa plugin which export transactions from an XLS sheet to Mifos database. * It uses the standard mifos API/SPI. <br> * <a href='http://www.mifos.org/developers/wiki/PluginManagement'>http://www.mifos.org/developers/wiki/PluginManagement</a> * * * */ public class MPesaXlsImporter extends StandardImport { private static final String DIGITS_AFTER_DECIMAL = "AccountingRules.DigitsAfterDecimal"; private static final String IMPORT_TRANSACTION_ORDER = "ImportTransactionOrder"; private static final String EXPECTED_STATUS = "Completed"; protected static final String PAYMENT_TYPE = "MPESA"; protected static final String EXPECTED_TRANSACTION_TYPE = "Pay Utility"; protected static final int RECEIPT = 0; protected static final int TRANSACTION_DATE = 1; protected static final int DETAILS = 2; protected static final int STATUS = 3; protected static final int WITHDRAWN = 4; protected static final int PAID_IN = 5; protected static final int BALANCE = 6; protected static final int BALANCE_CONFIRMED = 7; protected static final int TRANSACTION_TYPE = 8; protected static final int OTHER_PARTY_INFO = 9; protected static final int TRANSACTION_PARTY_DETAILS = 10; protected static final int MAX_CELL_NUM = 11; private static Map<AccountReferenceDto, BigDecimal> cumulativeAmountByAccount; private static List<AccountPaymentParametersDto> pmts; private static List<String> errorsList; private static List<String> importTransactionOrder; private static int successfullyParsedRows; private Set<Integer> ignoredRowNums; private Set<Integer> errorRowNums; private BigDecimal totalAmountOfErrorRows; @Override public String getDisplayName() { return "M-PESA Excel 97(-2007)"; } @Override public String getPropertyNameForAdminDisplay() { return "MPESA transaction order"; } @Override public String getPropertyValueForAdminDisplay() { List<String> order = getImportTransactionOrder(); if (order == null || order.isEmpty()) return "NOT DEFINED"; return StringUtils.join(order, ", "); } @SuppressWarnings("unchecked") protected List<String> getImportTransactionOrder() { if (importTransactionOrder == null) { final String importTransactionOrderKey = MPesaXlsImporter.class.getCanonicalName() + "." + IMPORT_TRANSACTION_ORDER; importTransactionOrder = (List<String>) getAccountService() .getMifosConfiguration(importTransactionOrderKey); if (importTransactionOrder == null) { importTransactionOrder = new ArrayList<String>(); } } return importTransactionOrder; } private String cellStringValue(Cell cell) { if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { return Double.toString(cell.getNumericCellValue()); } else { return cell.getStringCellValue(); } } private String formatErrorMessage(Row row, String message) { if (row == null) { return String.format("Error - %s", message); } if (row.getCell(RECEIPT) == null) { return String.format("Row <%d> error - %s", row.getRowNum() + 1, message); } return String.format("Row <%d> error - %s - %s", row.getRowNum() + 1, cellStringValue(row.getCell(RECEIPT)), message); } private String formatIgnoredErrorMessage(Row row, String message) { return String.format("Row <%d> ignored - %s - %s", row.getRowNum() + 1, cellStringValue(row.getCell(RECEIPT)), message); } private void addError(Row row, String message) { errorsList.add(formatErrorMessage(row, message)); if (!errorRowNums.contains(row.getRowNum())) { try { BigDecimal paidIn = BigDecimal.valueOf(row.getCell(PAID_IN).getNumericCellValue()); totalAmountOfErrorRows = totalAmountOfErrorRows.add(paidIn); } catch (Exception e) { // paid in couldn't be extracted, so skip this row } } errorRowNums.add(row.getRowNum()); } private void addIgnoredMessage(Row row, String message) { errorsList.add(formatIgnoredErrorMessage(row, message)); ignoredRowNums.add(row.getRowNum()); } private ByteArrayInputStream copyInputIntoByteInput(InputStream input) throws IOException { return new ByteArrayInputStream(IOUtils.toByteArray(input)); } private String getPhoneNumberCandidate(Row row) { String cellContents = cellStringValue(row.getCell(OTHER_PARTY_INFO)); String[] splitted = cellContents.split(" "); if (splitted == null || splitted.length == 0) { return null; } return splitted[0]; } /** * Returns validated phone number or null if there is no valid phone number in the row */ private String validatePhoneNumber(Row row) { String phoneNumber = getPhoneNumberCandidate(row); if (phoneNumber == null || phoneNumber.trim().isEmpty()) { addError(row, "Cannot read client's phone number"); return null; } List<CustomerDto> customers = getCustomerSearchService().findCustomersWithGivenPhoneNumber(phoneNumber); if (customers == null || customers.isEmpty()) { addError(row, String.format("Client with mobile number %s was not found", phoneNumber)); return null; } else if (customers.size() >= 2) { addError(row, String.format("More than 1 client with mobile number %s was found", phoneNumber)); return null; } return phoneNumber; } private CustomerDto customerWithPhoneNumber(String phoneNumber) { return getCustomerSearchService().findCustomersWithGivenPhoneNumber(phoneNumber).get(0); } private void initializeParser() { cumulativeAmountByAccount = new HashMap<AccountReferenceDto, BigDecimal>(); pmts = new ArrayList<AccountPaymentParametersDto>(); errorsList = new LinkedList<String>(); successfullyParsedRows = 0; errorRowNums = new HashSet<Integer>(); ignoredRowNums = new HashSet<Integer>(); totalAmountOfErrorRows = BigDecimal.ZERO; } protected boolean userDefinedProductValid(String userDefinedProduct, String phoneNumber) throws Exception { AccountReferenceDto userDefinedAcc = getSavingsAccount(phoneNumber, userDefinedProduct); if (userDefinedAcc != null) return true; userDefinedAcc = getLoanAccount(phoneNumber, userDefinedProduct); if (userDefinedAcc != null) return true; return false; } private boolean moreThanOneAccountMatchesProductCode(Row row, String phoneNumber, List<String> productNames) { for (String productName : productNames) { if (getAccountService().existsMoreThanOneLoanAccount(phoneNumber, productName) || getAccountService().existsMoreThanOneSavingsAccount(phoneNumber, productName)) { addError(row, "More than one account matches product code " + productName); return true; } } return false; } private int configuredDigitsAfterDecimal() { return Integer.parseInt((String)getAccountService().getMifosConfiguration(DIGITS_AFTER_DECIMAL)); } @Override public ParseResultDto parse(final InputStream input) { initializeParser(); try { Iterator<Row> rowIterator = null; // Copy input into byte input to try two implementations of POI parsers: HSSF and XSSF (XML formats) ByteArrayInputStream copiedInput = copyInputIntoByteInput(input); copiedInput.mark(0); try { rowIterator = new HSSFWorkbook(copiedInput).getSheetAt(0).iterator(); } catch (Exception e) { copiedInput.reset(); try { rowIterator = new XSSFWorkbook(copiedInput).getSheetAt(0).iterator(); } catch (Exception e2) { throw new MPesaXlsImporterException("Unknown file format. Supported file formats are: XLS (from Excel 2003 or older), XLSX"); } } int friendlyRowNum = 0; Row row = null; setPaymentType(); skipToTransactionData(rowIterator); if (!errorsList.isEmpty()) { return new ParseResultDto(errorsList, pmts); } /* Parse transaction data */ while (rowIterator.hasNext()) { try { row = rowIterator.next(); friendlyRowNum = row.getRowNum() + 1; if (!isRowValid(row, friendlyRowNum, errorsList)) { continue; } String receipt = cellStringValue(row.getCell(RECEIPT)); Date transDate; try { transDate = getDate(row.getCell(TRANSACTION_DATE)); } catch (Exception e) { addError(row, "Date does not begin with expected format (YYYY-MM-DD)"); continue; } String phoneNumber = validatePhoneNumber(row); if (phoneNumber == null) { continue; } final LocalDate paymentDate = LocalDate.fromDateFields(transDate); String transactionPartyDetails = null; if(row.getCell(TRANSACTION_PARTY_DETAILS).getCellType() == Cell.CELL_TYPE_NUMERIC) { transactionPartyDetails = row.getCell(TRANSACTION_PARTY_DETAILS).getNumericCellValue() +""; if(transactionPartyDetails.endsWith(".0")){ transactionPartyDetails = transactionPartyDetails.replace(".0", ""); } else { throw new IllegalArgumentException("Unknown format of cell "+ TRANSACTION_PARTY_DETAILS); } } else if (row.getCell(TRANSACTION_PARTY_DETAILS).getCellType() == Cell.CELL_TYPE_STRING) { transactionPartyDetails = row.getCell(TRANSACTION_PARTY_DETAILS).getStringCellValue(); } String userDefinedProduct = getUserDefinedProduct(transactionPartyDetails); List<String> parameters; if (userDefinedProduct != null && !userDefinedProduct.isEmpty() && userDefinedProductValid(userDefinedProduct, phoneNumber)) { parameters = Arrays.asList(userDefinedProduct); } else { parameters = getConfiguredProducts(); } if (moreThanOneAccountMatchesProductCode(row, phoneNumber, parameters)) { continue; } List<String> loanPrds = new LinkedList<String>(); String lastInTheOrderProdSName = parameters.get(parameters.size() - 1); loanPrds.addAll(parameters.subList(0, parameters.size() - 1)); checkBlank(lastInTheOrderProdSName, "Savings product short name", row); BigDecimal paidInAmount = BigDecimal.ZERO; // FIXME: possible data loss converting double to BigDecimal? paidInAmount = BigDecimal.valueOf(row.getCell(PAID_IN).getNumericCellValue()); if (paidInAmount.scale() > configuredDigitsAfterDecimal()) { - addError(row, - String.format("Number of fraction digits in the \"Paid In\" column - %d - is greater than configured for the currency - %d", - paidInAmount.scale(), configuredDigitsAfterDecimal())); - continue; + // when we create BigDecimal from double, then the scale is always greater than 0 + boolean nonZeroFractionalPart = false; + try { + paidInAmount.toBigIntegerExact(); + } + catch (ArithmeticException e) { + nonZeroFractionalPart = true; + } + if (paidInAmount.scale() > 1 || nonZeroFractionalPart) { + addError(row, + String.format("Number of fraction digits in the \"Paid In\" column - %d - is greater than configured for the currency - %d", + paidInAmount.scale(), configuredDigitsAfterDecimal())); + continue; + } } boolean cancelTransactionFlag = false; List<AccountPaymentParametersDto> loanPaymentList = new ArrayList<AccountPaymentParametersDto>(); for (String loanPrd : loanPrds) { BigDecimal loanAccountPaymentAmount = BigDecimal.ZERO; BigDecimal loanAccountTotalDueAmount = BigDecimal.ZERO; final AccountReferenceDto loanAccountReference = getLoanAccount(phoneNumber, loanPrd); // skip not found accounts as per specs P1 4.9 M-Pesa plugin if(loanAccountReference == null){ continue; } loanAccountTotalDueAmount = getTotalPaymentDueAmount(loanAccountReference); if (paidInAmount.compareTo(BigDecimal.ZERO) > 0) { if (paidInAmount.compareTo(loanAccountTotalDueAmount) > 0) { loanAccountPaymentAmount = loanAccountTotalDueAmount; paidInAmount = paidInAmount.subtract(loanAccountTotalDueAmount); } else { loanAccountPaymentAmount = paidInAmount; paidInAmount = BigDecimal.ZERO; } } else { loanAccountPaymentAmount = BigDecimal.ZERO; } AccountPaymentParametersDto cumulativeLoanPayment = createPaymentParametersDto( loanAccountReference, loanAccountPaymentAmount, paymentDate); if (!isPaymentValid(cumulativeLoanPayment, row)) { cancelTransactionFlag = true; break; } loanPaymentList.add(new AccountPaymentParametersDto(getUserReferenceDto(), loanAccountReference, loanAccountPaymentAmount, paymentDate, getPaymentTypeDto(), "", new LocalDate(), receipt, customerWithPhoneNumber(phoneNumber))); } if (cancelTransactionFlag) { continue; } BigDecimal lastInOrderAmount; AccountReferenceDto lastInOrderAcc; lastInOrderAcc = getSavingsAccount(phoneNumber, lastInTheOrderProdSName); if(lastInOrderAcc == null) { lastInOrderAcc = getLoanAccount(phoneNumber, lastInTheOrderProdSName); if (lastInOrderAcc != null) { BigDecimal totalPaymentDueAmount = getTotalPaymentDueAmount(lastInOrderAcc); if(paidInAmount.compareTo(totalPaymentDueAmount) > 0) { addError(row, "Last account is a loan account but the total paid in amount is greater than the total due amount"); continue; } } } if(lastInOrderAcc == null) { addError(row, "No valid accounts found with this transaction"); continue; } if (paidInAmount.compareTo(BigDecimal.ZERO) > 0) { lastInOrderAmount = paidInAmount; paidInAmount = BigDecimal.ZERO; } else { lastInOrderAmount = BigDecimal.ZERO; } final AccountPaymentParametersDto cumulativePaymentlastAcc = createPaymentParametersDto(lastInOrderAcc, lastInOrderAmount, paymentDate); final AccountPaymentParametersDto lastInTheOrderAccPayment = new AccountPaymentParametersDto( getUserReferenceDto(), lastInOrderAcc, lastInOrderAmount, paymentDate, getPaymentTypeDto(), "", new LocalDate(), receipt, customerWithPhoneNumber(phoneNumber)); if (!isPaymentValid(cumulativePaymentlastAcc, row)) { continue; } successfullyParsedRows+=1; for (AccountPaymentParametersDto loanPayment : loanPaymentList) { pmts.add(loanPayment); } pmts.add(lastInTheOrderAccPayment); } catch (Exception e) { /* catch row specific exception and continue for other rows */ e.printStackTrace(); addError(row, e.getMessage()); continue; } } } catch (Exception e) { /* Catch any exception in the process */ e.printStackTrace(); errorsList.add(e.getMessage() + ". Got error before reading rows"); } return parsingResult(); } private ParseResultDto parsingResult() { ParseResultDto result = new ParseResultDto(errorsList, pmts); result.setNumberOfErrorRows(errorRowNums.size()); result.setNumberOfIgnoredRows(ignoredRowNums.size()); result.setNumberOfReadRows(result.getNumberOfErrorRows() + result.getNumberOfIgnoredRows() + successfullyParsedRows); if (result.getNumberOfReadRows() == 0) { errorsList.add("No rows found with import data"); } result.setTotalAmountOfTransactionsWithError(totalAmountOfErrorRows); result.setTotalAmountOfTransactionsImported(sumAmountsOfPayments()); return result; } private BigDecimal sumAmountsOfPayments() { BigDecimal result = BigDecimal.ZERO; for (AccountPaymentParametersDto payment : pmts) { result = result.add(payment.getPaymentAmount()); } return result; } protected String getUserDefinedProduct(String transactionPartyDetails) { if (transactionPartyDetails == null || transactionPartyDetails.trim().isEmpty()) return null; String[] words = transactionPartyDetails.split(" "); if (words.length == 0) return null; return words[0]; } protected List<String> getConfiguredProducts() { List<String> products = getImportTransactionOrder(); if (products == null || products.isEmpty()) { throw new MPesaXlsImporterException("Account in \"Transaction Party Details\" field not found"); } return products; } private AccountPaymentParametersDto createPaymentParametersDto(final AccountReferenceDto accountReference, final BigDecimal paymentAmount, final LocalDate paymentDate) { BigDecimal totalPaymentAmountForAccount = addToRunningTotalForAccount(paymentAmount, cumulativeAmountByAccount, accountReference); return new AccountPaymentParametersDto(getUserReferenceDto(), accountReference, totalPaymentAmountForAccount, paymentDate, getPaymentTypeDto(), ""); } /** * @throws Exception */ private void setPaymentType() throws Exception { final PaymentTypeDto paymentType = findPaymentType(PAYMENT_TYPE); if (paymentType == null) { throw new MPesaXlsImporterException("Payment type " + PAYMENT_TYPE + " not found. Have you configured" + " this payment type?"); } setPaymentTypeDto(paymentType); } private boolean isRowValid(final Row row, final int friendlyRowNum, List<String> errorsList) throws Exception { if (row.getLastCellNum() < MAX_CELL_NUM) { addError(row, "Missing required data"); return false; } if (row.getCell(STATUS) == null || row.getCell(STATUS).getStringCellValue() == null) { addError(row, "Missing required data"); return false; } if (!row.getCell(STATUS).getStringCellValue().trim().equals(EXPECTED_STATUS)) { addIgnoredMessage(row, "Status of " + row.getCell(STATUS) + " instead of Completed"); return false; } if (!row.getCell(TRANSACTION_TYPE).getStringCellValue().trim().equalsIgnoreCase(EXPECTED_TRANSACTION_TYPE)) { addIgnoredMessage(row, "Transaction type \"" + row.getCell(TRANSACTION_TYPE) + "\" instead of \"" + EXPECTED_TRANSACTION_TYPE + "\""); return false; } if (null == row.getCell(TRANSACTION_DATE)) { addError(row, "Date field is empty"); return false; } if (null == row.getCell(TRANSACTION_PARTY_DETAILS)) { addError(row, "\"Transaction party details\" field is empty."); return false; } if (null == row.getCell(PAID_IN)) { addError(row, "\"Paid in\" field is empty."); return false; } if (row.getCell(STATUS) == null) { addError(row, "Status field is empty"); return false; } else { String receiptNumber = cellStringValue(row.getCell(RECEIPT)); if (receiptNumber != null && !receiptNumber.isEmpty()) { if (getAccountService().receiptExists(receiptNumber)) { addError(row, "Transactions with same Receipt ID have already been imported"); return false; } } } return true; } private void checkBlank(final String value, final String name, final Row row) { if (StringUtils.isBlank(value)) { addError(row, name + " could not be extracted"); } } private boolean isPaymentValid(final AccountPaymentParametersDto cumulativePayment, final Row row) throws Exception { final List<InvalidPaymentReason> errors = getAccountService().validatePayment(cumulativePayment); if (!errors.isEmpty()) { for (InvalidPaymentReason error : errors) { switch (error) { case INVALID_DATE: addError(row, "Invalid transaction date"); break; case UNSUPPORTED_PAYMENT_TYPE: addError(row, "Unsupported payment type"); break; case INVALID_PAYMENT_AMOUNT: addError(row, "Invalid payment amount"); break; case INVALID_LOAN_STATE: addError(row, "Invalid account state"); break; default: addError(row, "Invalid payment (reason unknown)"); break; } } return false; } return true; } private BigDecimal getTotalPaymentDueAmount(final AccountReferenceDto advanceLoanAccount) throws Exception { return getAccountService().getTotalPaymentDueAmount(advanceLoanAccount); } protected AccountReferenceDto getSavingsAccount(final String phoneNumber, final String savingsProductShortName) throws Exception { AccountReferenceDto account = null; try { account = getAccountService().lookupSavingsAccountReferenceFromClientPhoneNumberAndSavingsProductShortName(phoneNumber, savingsProductShortName); } catch (Exception e) { if (!e.getMessage().equals("savings not found for client phone number " + phoneNumber + " and savings product short name " + savingsProductShortName)) { throw e; } } return account; } protected AccountReferenceDto getLoanAccount(final String phoneNumber, final String loanProductShortName) throws Exception { AccountReferenceDto account = null; try { account = getAccountService().lookupLoanAccountReferenceFromClientPhoneNumberAndLoanProductShortName(phoneNumber, loanProductShortName); } catch (Exception e) { if(!e.getMessage().equals("loan not found for client phone number " + phoneNumber + " and loan product short name " + loanProductShortName)) { throw e; } } return account; } private void skipToTransactionData(final Iterator<Row> rowIterator) { boolean skippingRowsBeforeTransactionData = true; while (errorsList.isEmpty() && skippingRowsBeforeTransactionData) { if (!rowIterator.hasNext()) { errorsList.add("No rows found with import data."); break; } final Row row = rowIterator.next(); if (row.getCell(0) != null && row.getCell(0).getStringCellValue().trim().equals("Transactions")) { skippingRowsBeforeTransactionData = false; /* skip row with column descriptions */ rowIterator.next(); } } } protected static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; protected Date getDate(final Cell transDateCell) throws ParseException { Date date = null; if (transDateCell.getCellType() == Cell.CELL_TYPE_STRING) { final SimpleDateFormat dateAsText = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH); dateAsText.setLenient(false); date = dateAsText.parse(transDateCell.getStringCellValue()); } else if (transDateCell.getCellType() == Cell.CELL_TYPE_NUMERIC) { date = transDateCell.getDateCellValue(); } return date; } /** * M-PESA imports have multiple transactions per row. Two loan accounts and * one savings account, I think. * * See <a href="http://mifosforge.jira.com/browse/MIFOS-2909">MIFOS-2909</a>. */ @Override public int getSuccessfullyParsedRows() { return successfullyParsedRows; } class MPesaXlsImporterException extends RuntimeException { private static final long serialVersionUID = 731436914098659043L; MPesaXlsImporterException(final String msg) { super(msg); } } }
true
true
public ParseResultDto parse(final InputStream input) { initializeParser(); try { Iterator<Row> rowIterator = null; // Copy input into byte input to try two implementations of POI parsers: HSSF and XSSF (XML formats) ByteArrayInputStream copiedInput = copyInputIntoByteInput(input); copiedInput.mark(0); try { rowIterator = new HSSFWorkbook(copiedInput).getSheetAt(0).iterator(); } catch (Exception e) { copiedInput.reset(); try { rowIterator = new XSSFWorkbook(copiedInput).getSheetAt(0).iterator(); } catch (Exception e2) { throw new MPesaXlsImporterException("Unknown file format. Supported file formats are: XLS (from Excel 2003 or older), XLSX"); } } int friendlyRowNum = 0; Row row = null; setPaymentType(); skipToTransactionData(rowIterator); if (!errorsList.isEmpty()) { return new ParseResultDto(errorsList, pmts); } /* Parse transaction data */ while (rowIterator.hasNext()) { try { row = rowIterator.next(); friendlyRowNum = row.getRowNum() + 1; if (!isRowValid(row, friendlyRowNum, errorsList)) { continue; } String receipt = cellStringValue(row.getCell(RECEIPT)); Date transDate; try { transDate = getDate(row.getCell(TRANSACTION_DATE)); } catch (Exception e) { addError(row, "Date does not begin with expected format (YYYY-MM-DD)"); continue; } String phoneNumber = validatePhoneNumber(row); if (phoneNumber == null) { continue; } final LocalDate paymentDate = LocalDate.fromDateFields(transDate); String transactionPartyDetails = null; if(row.getCell(TRANSACTION_PARTY_DETAILS).getCellType() == Cell.CELL_TYPE_NUMERIC) { transactionPartyDetails = row.getCell(TRANSACTION_PARTY_DETAILS).getNumericCellValue() +""; if(transactionPartyDetails.endsWith(".0")){ transactionPartyDetails = transactionPartyDetails.replace(".0", ""); } else { throw new IllegalArgumentException("Unknown format of cell "+ TRANSACTION_PARTY_DETAILS); } } else if (row.getCell(TRANSACTION_PARTY_DETAILS).getCellType() == Cell.CELL_TYPE_STRING) { transactionPartyDetails = row.getCell(TRANSACTION_PARTY_DETAILS).getStringCellValue(); } String userDefinedProduct = getUserDefinedProduct(transactionPartyDetails); List<String> parameters; if (userDefinedProduct != null && !userDefinedProduct.isEmpty() && userDefinedProductValid(userDefinedProduct, phoneNumber)) { parameters = Arrays.asList(userDefinedProduct); } else { parameters = getConfiguredProducts(); } if (moreThanOneAccountMatchesProductCode(row, phoneNumber, parameters)) { continue; } List<String> loanPrds = new LinkedList<String>(); String lastInTheOrderProdSName = parameters.get(parameters.size() - 1); loanPrds.addAll(parameters.subList(0, parameters.size() - 1)); checkBlank(lastInTheOrderProdSName, "Savings product short name", row); BigDecimal paidInAmount = BigDecimal.ZERO; // FIXME: possible data loss converting double to BigDecimal? paidInAmount = BigDecimal.valueOf(row.getCell(PAID_IN).getNumericCellValue()); if (paidInAmount.scale() > configuredDigitsAfterDecimal()) { addError(row, String.format("Number of fraction digits in the \"Paid In\" column - %d - is greater than configured for the currency - %d", paidInAmount.scale(), configuredDigitsAfterDecimal())); continue; } boolean cancelTransactionFlag = false; List<AccountPaymentParametersDto> loanPaymentList = new ArrayList<AccountPaymentParametersDto>(); for (String loanPrd : loanPrds) { BigDecimal loanAccountPaymentAmount = BigDecimal.ZERO; BigDecimal loanAccountTotalDueAmount = BigDecimal.ZERO; final AccountReferenceDto loanAccountReference = getLoanAccount(phoneNumber, loanPrd); // skip not found accounts as per specs P1 4.9 M-Pesa plugin if(loanAccountReference == null){ continue; } loanAccountTotalDueAmount = getTotalPaymentDueAmount(loanAccountReference); if (paidInAmount.compareTo(BigDecimal.ZERO) > 0) { if (paidInAmount.compareTo(loanAccountTotalDueAmount) > 0) { loanAccountPaymentAmount = loanAccountTotalDueAmount; paidInAmount = paidInAmount.subtract(loanAccountTotalDueAmount); } else { loanAccountPaymentAmount = paidInAmount; paidInAmount = BigDecimal.ZERO; } } else { loanAccountPaymentAmount = BigDecimal.ZERO; } AccountPaymentParametersDto cumulativeLoanPayment = createPaymentParametersDto( loanAccountReference, loanAccountPaymentAmount, paymentDate); if (!isPaymentValid(cumulativeLoanPayment, row)) { cancelTransactionFlag = true; break; } loanPaymentList.add(new AccountPaymentParametersDto(getUserReferenceDto(), loanAccountReference, loanAccountPaymentAmount, paymentDate, getPaymentTypeDto(), "", new LocalDate(), receipt, customerWithPhoneNumber(phoneNumber))); } if (cancelTransactionFlag) { continue; } BigDecimal lastInOrderAmount; AccountReferenceDto lastInOrderAcc; lastInOrderAcc = getSavingsAccount(phoneNumber, lastInTheOrderProdSName); if(lastInOrderAcc == null) { lastInOrderAcc = getLoanAccount(phoneNumber, lastInTheOrderProdSName); if (lastInOrderAcc != null) { BigDecimal totalPaymentDueAmount = getTotalPaymentDueAmount(lastInOrderAcc); if(paidInAmount.compareTo(totalPaymentDueAmount) > 0) { addError(row, "Last account is a loan account but the total paid in amount is greater than the total due amount"); continue; } } } if(lastInOrderAcc == null) { addError(row, "No valid accounts found with this transaction"); continue; } if (paidInAmount.compareTo(BigDecimal.ZERO) > 0) { lastInOrderAmount = paidInAmount; paidInAmount = BigDecimal.ZERO; } else { lastInOrderAmount = BigDecimal.ZERO; } final AccountPaymentParametersDto cumulativePaymentlastAcc = createPaymentParametersDto(lastInOrderAcc, lastInOrderAmount, paymentDate); final AccountPaymentParametersDto lastInTheOrderAccPayment = new AccountPaymentParametersDto( getUserReferenceDto(), lastInOrderAcc, lastInOrderAmount, paymentDate, getPaymentTypeDto(), "", new LocalDate(), receipt, customerWithPhoneNumber(phoneNumber)); if (!isPaymentValid(cumulativePaymentlastAcc, row)) { continue; } successfullyParsedRows+=1; for (AccountPaymentParametersDto loanPayment : loanPaymentList) { pmts.add(loanPayment); } pmts.add(lastInTheOrderAccPayment); } catch (Exception e) { /* catch row specific exception and continue for other rows */ e.printStackTrace(); addError(row, e.getMessage()); continue; } } } catch (Exception e) { /* Catch any exception in the process */ e.printStackTrace(); errorsList.add(e.getMessage() + ". Got error before reading rows"); } return parsingResult(); }
public ParseResultDto parse(final InputStream input) { initializeParser(); try { Iterator<Row> rowIterator = null; // Copy input into byte input to try two implementations of POI parsers: HSSF and XSSF (XML formats) ByteArrayInputStream copiedInput = copyInputIntoByteInput(input); copiedInput.mark(0); try { rowIterator = new HSSFWorkbook(copiedInput).getSheetAt(0).iterator(); } catch (Exception e) { copiedInput.reset(); try { rowIterator = new XSSFWorkbook(copiedInput).getSheetAt(0).iterator(); } catch (Exception e2) { throw new MPesaXlsImporterException("Unknown file format. Supported file formats are: XLS (from Excel 2003 or older), XLSX"); } } int friendlyRowNum = 0; Row row = null; setPaymentType(); skipToTransactionData(rowIterator); if (!errorsList.isEmpty()) { return new ParseResultDto(errorsList, pmts); } /* Parse transaction data */ while (rowIterator.hasNext()) { try { row = rowIterator.next(); friendlyRowNum = row.getRowNum() + 1; if (!isRowValid(row, friendlyRowNum, errorsList)) { continue; } String receipt = cellStringValue(row.getCell(RECEIPT)); Date transDate; try { transDate = getDate(row.getCell(TRANSACTION_DATE)); } catch (Exception e) { addError(row, "Date does not begin with expected format (YYYY-MM-DD)"); continue; } String phoneNumber = validatePhoneNumber(row); if (phoneNumber == null) { continue; } final LocalDate paymentDate = LocalDate.fromDateFields(transDate); String transactionPartyDetails = null; if(row.getCell(TRANSACTION_PARTY_DETAILS).getCellType() == Cell.CELL_TYPE_NUMERIC) { transactionPartyDetails = row.getCell(TRANSACTION_PARTY_DETAILS).getNumericCellValue() +""; if(transactionPartyDetails.endsWith(".0")){ transactionPartyDetails = transactionPartyDetails.replace(".0", ""); } else { throw new IllegalArgumentException("Unknown format of cell "+ TRANSACTION_PARTY_DETAILS); } } else if (row.getCell(TRANSACTION_PARTY_DETAILS).getCellType() == Cell.CELL_TYPE_STRING) { transactionPartyDetails = row.getCell(TRANSACTION_PARTY_DETAILS).getStringCellValue(); } String userDefinedProduct = getUserDefinedProduct(transactionPartyDetails); List<String> parameters; if (userDefinedProduct != null && !userDefinedProduct.isEmpty() && userDefinedProductValid(userDefinedProduct, phoneNumber)) { parameters = Arrays.asList(userDefinedProduct); } else { parameters = getConfiguredProducts(); } if (moreThanOneAccountMatchesProductCode(row, phoneNumber, parameters)) { continue; } List<String> loanPrds = new LinkedList<String>(); String lastInTheOrderProdSName = parameters.get(parameters.size() - 1); loanPrds.addAll(parameters.subList(0, parameters.size() - 1)); checkBlank(lastInTheOrderProdSName, "Savings product short name", row); BigDecimal paidInAmount = BigDecimal.ZERO; // FIXME: possible data loss converting double to BigDecimal? paidInAmount = BigDecimal.valueOf(row.getCell(PAID_IN).getNumericCellValue()); if (paidInAmount.scale() > configuredDigitsAfterDecimal()) { // when we create BigDecimal from double, then the scale is always greater than 0 boolean nonZeroFractionalPart = false; try { paidInAmount.toBigIntegerExact(); } catch (ArithmeticException e) { nonZeroFractionalPart = true; } if (paidInAmount.scale() > 1 || nonZeroFractionalPart) { addError(row, String.format("Number of fraction digits in the \"Paid In\" column - %d - is greater than configured for the currency - %d", paidInAmount.scale(), configuredDigitsAfterDecimal())); continue; } } boolean cancelTransactionFlag = false; List<AccountPaymentParametersDto> loanPaymentList = new ArrayList<AccountPaymentParametersDto>(); for (String loanPrd : loanPrds) { BigDecimal loanAccountPaymentAmount = BigDecimal.ZERO; BigDecimal loanAccountTotalDueAmount = BigDecimal.ZERO; final AccountReferenceDto loanAccountReference = getLoanAccount(phoneNumber, loanPrd); // skip not found accounts as per specs P1 4.9 M-Pesa plugin if(loanAccountReference == null){ continue; } loanAccountTotalDueAmount = getTotalPaymentDueAmount(loanAccountReference); if (paidInAmount.compareTo(BigDecimal.ZERO) > 0) { if (paidInAmount.compareTo(loanAccountTotalDueAmount) > 0) { loanAccountPaymentAmount = loanAccountTotalDueAmount; paidInAmount = paidInAmount.subtract(loanAccountTotalDueAmount); } else { loanAccountPaymentAmount = paidInAmount; paidInAmount = BigDecimal.ZERO; } } else { loanAccountPaymentAmount = BigDecimal.ZERO; } AccountPaymentParametersDto cumulativeLoanPayment = createPaymentParametersDto( loanAccountReference, loanAccountPaymentAmount, paymentDate); if (!isPaymentValid(cumulativeLoanPayment, row)) { cancelTransactionFlag = true; break; } loanPaymentList.add(new AccountPaymentParametersDto(getUserReferenceDto(), loanAccountReference, loanAccountPaymentAmount, paymentDate, getPaymentTypeDto(), "", new LocalDate(), receipt, customerWithPhoneNumber(phoneNumber))); } if (cancelTransactionFlag) { continue; } BigDecimal lastInOrderAmount; AccountReferenceDto lastInOrderAcc; lastInOrderAcc = getSavingsAccount(phoneNumber, lastInTheOrderProdSName); if(lastInOrderAcc == null) { lastInOrderAcc = getLoanAccount(phoneNumber, lastInTheOrderProdSName); if (lastInOrderAcc != null) { BigDecimal totalPaymentDueAmount = getTotalPaymentDueAmount(lastInOrderAcc); if(paidInAmount.compareTo(totalPaymentDueAmount) > 0) { addError(row, "Last account is a loan account but the total paid in amount is greater than the total due amount"); continue; } } } if(lastInOrderAcc == null) { addError(row, "No valid accounts found with this transaction"); continue; } if (paidInAmount.compareTo(BigDecimal.ZERO) > 0) { lastInOrderAmount = paidInAmount; paidInAmount = BigDecimal.ZERO; } else { lastInOrderAmount = BigDecimal.ZERO; } final AccountPaymentParametersDto cumulativePaymentlastAcc = createPaymentParametersDto(lastInOrderAcc, lastInOrderAmount, paymentDate); final AccountPaymentParametersDto lastInTheOrderAccPayment = new AccountPaymentParametersDto( getUserReferenceDto(), lastInOrderAcc, lastInOrderAmount, paymentDate, getPaymentTypeDto(), "", new LocalDate(), receipt, customerWithPhoneNumber(phoneNumber)); if (!isPaymentValid(cumulativePaymentlastAcc, row)) { continue; } successfullyParsedRows+=1; for (AccountPaymentParametersDto loanPayment : loanPaymentList) { pmts.add(loanPayment); } pmts.add(lastInTheOrderAccPayment); } catch (Exception e) { /* catch row specific exception and continue for other rows */ e.printStackTrace(); addError(row, e.getMessage()); continue; } } } catch (Exception e) { /* Catch any exception in the process */ e.printStackTrace(); errorsList.add(e.getMessage() + ". Got error before reading rows"); } return parsingResult(); }
diff --git a/xfire-xmlbeans/src/test/org/codehaus/xfire/xmlbeans/weather/WeatherTest.java b/xfire-xmlbeans/src/test/org/codehaus/xfire/xmlbeans/weather/WeatherTest.java index 3bca5a82..547f539b 100644 --- a/xfire-xmlbeans/src/test/org/codehaus/xfire/xmlbeans/weather/WeatherTest.java +++ b/xfire-xmlbeans/src/test/org/codehaus/xfire/xmlbeans/weather/WeatherTest.java @@ -1,16 +1,16 @@ package org.codehaus.xfire.xmlbeans.weather; import junit.framework.TestCase; /** * @author <a href="mailto:[email protected]">Dan Diephouse</a> * @since Oct 26, 2004 */ public class WeatherTest extends TestCase { public void testWeather() throws Exception { - WeatherForecastSoapClient client = new WeatherForecastSoapClient(); + // WeatherForecastSoapClient client = new WeatherForecastSoapClient(); } }
true
true
public void testWeather() throws Exception { WeatherForecastSoapClient client = new WeatherForecastSoapClient(); }
public void testWeather() throws Exception { // WeatherForecastSoapClient client = new WeatherForecastSoapClient(); }
diff --git a/src/psywerx/platformGl/game/Square.java b/src/psywerx/platformGl/game/Square.java index 9d7a69a..8f52d92 100644 --- a/src/psywerx/platformGl/game/Square.java +++ b/src/psywerx/platformGl/game/Square.java @@ -1,68 +1,68 @@ package psywerx.platformGl.game; import java.nio.FloatBuffer; import javax.media.opengl.GL2ES2; import com.jogamp.common.nio.Buffers; public class Square implements Drawable { protected float size = 0.05f; protected Vector position = new Vector(0.0f, 0.0f); protected Vector velocity = new Vector(0f, 0.5f); protected float[] color = { 1f, 1f, 0f }; protected float z = 0.0f; public void update(double theta) { } public void draw(GL2ES2 gl) { float[] modelMatrix = new float[16]; Matrix.setIdentityM(modelMatrix, 0); Matrix.translateM(modelMatrix, 0, position.x, position.y, z); gl.glUniformMatrix4fv(Main.modelMatrix_location, 1, false, modelMatrix, 0); float[] vertices = { 1.0f, -1.0f, 0.0f, // Bottom Right -1.0f, -1.0f, 0.0f, // Bottom Left 1.0f, 1.0f, 0.0f, // Top Right -1.0f, 1.0f, 0.0f, // Top Left }; for (int i = 0; i < vertices.length; i++) { vertices[i] *= size; } // This is done so that the data doesn't get garbage collected FloatBuffer fbVertices = Buffers.newDirectFloatBuffer(vertices); gl.glVertexAttribPointer(0, 3, GL2ES2.GL_FLOAT, false, 0, fbVertices); gl.glEnableVertexAttribArray(0); float[] colors = { color[0], color[1], color[2], 1.0f, // Top color color[0], color[1], color[2], 1.0f, // Bottom Left color - color[0], color[1], color[2], 0.9f, // Bottom Right + color[0], color[1], color[2], 1.0f, // Bottom Right color[0], color[1], color[2], 1.0f, // Transparency }; FloatBuffer fbColors = Buffers.newDirectFloatBuffer(colors); gl.glVertexAttribPointer(1, 4, GL2ES2.GL_FLOAT, false, 0, fbColors); gl.glEnableVertexAttribArray(1); gl.glDrawArrays(GL2ES2.GL_TRIANGLE_STRIP, 0, 4); // Draw the vertices as gl.glDisableVertexAttribArray(0); // Allow release of vertex position // memory gl.glDisableVertexAttribArray(1); // Allow release of vertex color // memory // It is only safe to let the garbage collector collect the vertices and // colors // NIO buffers data after first calling glDisableVertexAttribArray. fbVertices = null; fbColors = null; } }
true
true
public void draw(GL2ES2 gl) { float[] modelMatrix = new float[16]; Matrix.setIdentityM(modelMatrix, 0); Matrix.translateM(modelMatrix, 0, position.x, position.y, z); gl.glUniformMatrix4fv(Main.modelMatrix_location, 1, false, modelMatrix, 0); float[] vertices = { 1.0f, -1.0f, 0.0f, // Bottom Right -1.0f, -1.0f, 0.0f, // Bottom Left 1.0f, 1.0f, 0.0f, // Top Right -1.0f, 1.0f, 0.0f, // Top Left }; for (int i = 0; i < vertices.length; i++) { vertices[i] *= size; } // This is done so that the data doesn't get garbage collected FloatBuffer fbVertices = Buffers.newDirectFloatBuffer(vertices); gl.glVertexAttribPointer(0, 3, GL2ES2.GL_FLOAT, false, 0, fbVertices); gl.glEnableVertexAttribArray(0); float[] colors = { color[0], color[1], color[2], 1.0f, // Top color color[0], color[1], color[2], 1.0f, // Bottom Left color color[0], color[1], color[2], 0.9f, // Bottom Right color[0], color[1], color[2], 1.0f, // Transparency }; FloatBuffer fbColors = Buffers.newDirectFloatBuffer(colors); gl.glVertexAttribPointer(1, 4, GL2ES2.GL_FLOAT, false, 0, fbColors); gl.glEnableVertexAttribArray(1); gl.glDrawArrays(GL2ES2.GL_TRIANGLE_STRIP, 0, 4); // Draw the vertices as gl.glDisableVertexAttribArray(0); // Allow release of vertex position // memory gl.glDisableVertexAttribArray(1); // Allow release of vertex color // memory // It is only safe to let the garbage collector collect the vertices and // colors // NIO buffers data after first calling glDisableVertexAttribArray. fbVertices = null; fbColors = null; }
public void draw(GL2ES2 gl) { float[] modelMatrix = new float[16]; Matrix.setIdentityM(modelMatrix, 0); Matrix.translateM(modelMatrix, 0, position.x, position.y, z); gl.glUniformMatrix4fv(Main.modelMatrix_location, 1, false, modelMatrix, 0); float[] vertices = { 1.0f, -1.0f, 0.0f, // Bottom Right -1.0f, -1.0f, 0.0f, // Bottom Left 1.0f, 1.0f, 0.0f, // Top Right -1.0f, 1.0f, 0.0f, // Top Left }; for (int i = 0; i < vertices.length; i++) { vertices[i] *= size; } // This is done so that the data doesn't get garbage collected FloatBuffer fbVertices = Buffers.newDirectFloatBuffer(vertices); gl.glVertexAttribPointer(0, 3, GL2ES2.GL_FLOAT, false, 0, fbVertices); gl.glEnableVertexAttribArray(0); float[] colors = { color[0], color[1], color[2], 1.0f, // Top color color[0], color[1], color[2], 1.0f, // Bottom Left color color[0], color[1], color[2], 1.0f, // Bottom Right color[0], color[1], color[2], 1.0f, // Transparency }; FloatBuffer fbColors = Buffers.newDirectFloatBuffer(colors); gl.glVertexAttribPointer(1, 4, GL2ES2.GL_FLOAT, false, 0, fbColors); gl.glEnableVertexAttribArray(1); gl.glDrawArrays(GL2ES2.GL_TRIANGLE_STRIP, 0, 4); // Draw the vertices as gl.glDisableVertexAttribArray(0); // Allow release of vertex position // memory gl.glDisableVertexAttribArray(1); // Allow release of vertex color // memory // It is only safe to let the garbage collector collect the vertices and // colors // NIO buffers data after first calling glDisableVertexAttribArray. fbVertices = null; fbColors = null; }
diff --git a/src/org/python/modules/_collections/PyDefaultDict.java b/src/org/python/modules/_collections/PyDefaultDict.java index a8013d72..7bf3b93f 100644 --- a/src/org/python/modules/_collections/PyDefaultDict.java +++ b/src/org/python/modules/_collections/PyDefaultDict.java @@ -1,142 +1,142 @@ /* Copyright (c) Jython Developers */ package org.python.modules._collections; import java.util.Map; import org.python.core.Py; import org.python.core.PyDictionary; import org.python.core.PyObject; import org.python.core.PyTuple; import org.python.core.PyType; import org.python.expose.ExposedDelete; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedSet; import org.python.expose.ExposedType; /** * PyDefaultDict - This is a subclass of the builtin dict(PyDictionary) class. It supports * one additional method __missing__ and adds one writable instance variable * defaultFactory. The remaining functionality is the same as for the dict class. * * collections.defaultdict([defaultFactory[, ...]]) - returns a new dictionary-like * object. The first argument provides the initial value for the defaultFactory attribute; * it defaults to None. All remaining arguments are treated the same as if they were * passed to the dict constructor, including keyword arguments. */ @ExposedType(name = "collections.defaultdict") public class PyDefaultDict extends PyDictionary { public static final PyType TYPE = PyType.fromClass(PyDefaultDict.class); /** * This attribute is used by the __missing__ method; it is initialized from the first * argument to the constructor, if present, or to None, if absent. */ private PyObject defaultFactory = Py.None; public PyDefaultDict() { this(TYPE); } public PyDefaultDict(PyType subtype) { super(subtype); } public PyDefaultDict(PyType subtype, Map<PyObject, PyObject> map) { super(subtype, map); } @ExposedMethod @ExposedNew final void defaultdict___init__(PyObject[] args, String[] kwds) { int nargs = args.length - kwds.length; if (nargs != 0) { defaultFactory = args[0]; - if (defaultFactory.__findattr__("__call__") == null) { + if (!defaultFactory.isCallable()) { throw Py.TypeError("first argument must be callable"); } PyObject newargs[] = new PyObject[args.length - 1]; System.arraycopy(args, 1, newargs, 0, newargs.length); dict___init__(newargs , kwds); } } @Override public PyObject __finditem__(PyObject key) { return dict___getitem__(key); } /** * This method is called by the __getitem__ method of the dict class when the * requested key is not found; whatever it returns or raises is then returned or * raised by __getitem__. */ @ExposedMethod final PyObject defaultdict___missing__(PyObject key) { if (defaultFactory == Py.None) { throw Py.KeyError(key); } PyObject value = defaultFactory.__call__(); if (value == null) { return value; } __setitem__(key, value); return value; } @Override public PyObject __reduce__() { return defaultdict___reduce__(); } @ExposedMethod final PyObject defaultdict___reduce__() { PyTuple args = null; if (defaultFactory == Py.None) { args = new PyTuple(); } else { PyObject[] ob = {defaultFactory}; args = new PyTuple(ob); } return new PyTuple(getType(), args, Py.None, Py.None, items()); } @Override public PyDictionary copy() { return defaultdict_copy(); } @ExposedMethod(names = {"copy", "__copy__"}) final PyDefaultDict defaultdict_copy() { PyDefaultDict ob = new PyDefaultDict(TYPE, table); ob.defaultFactory = defaultFactory; return ob; } @Override public String toString() { return defaultdict_toString(); } @ExposedMethod(names = "__repr__") final String defaultdict_toString() { return String.format("defaultdict(%s, %s)", defaultFactory, super.toString()); } @ExposedGet(name = "default_factory") public PyObject getDefaultFactory() { return defaultFactory; } @ExposedSet(name = "default_factory") public void setDefaultFactory(PyObject value) { defaultFactory = value; } @ExposedDelete(name = "default_factory") public void delDefaultFactory() { defaultFactory = Py.None; } }
true
true
final void defaultdict___init__(PyObject[] args, String[] kwds) { int nargs = args.length - kwds.length; if (nargs != 0) { defaultFactory = args[0]; if (defaultFactory.__findattr__("__call__") == null) { throw Py.TypeError("first argument must be callable"); } PyObject newargs[] = new PyObject[args.length - 1]; System.arraycopy(args, 1, newargs, 0, newargs.length); dict___init__(newargs , kwds); } }
final void defaultdict___init__(PyObject[] args, String[] kwds) { int nargs = args.length - kwds.length; if (nargs != 0) { defaultFactory = args[0]; if (!defaultFactory.isCallable()) { throw Py.TypeError("first argument must be callable"); } PyObject newargs[] = new PyObject[args.length - 1]; System.arraycopy(args, 1, newargs, 0, newargs.length); dict___init__(newargs , kwds); } }
diff --git a/Start.java b/Start.java index 09867fd..d03a970 100644 --- a/Start.java +++ b/Start.java @@ -1,188 +1,188 @@ /* * Copyright (c) 2011 Xamarin Inc. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package jar2xml; import java.io.File; import java.io.OutputStreamWriter; import java.io.FileOutputStream; import java.util.List; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Start { // FIXME: for future compatibility, they had better be scraped // from java/lang/annotated/Annotation.html (known *direct subclasses) static final String [] annotations = { "android.test.FlakyTest", "android.test.UiThreadTest", "android.test.suitebuilder.annotation.LargeTest", "android.test.suitebuilder.annotation.MediumTest", "android.test.suitebuilder.annotation.SmallTest", "android.test.suitebuilder.annotation.Smoke", "android.test.suitebuilder.annotation.Suppress", "android.view.ViewDebug$CapturedViewProperty", "android.view.ViewDebug$ExportedProperty", "android.view.ViewDebug$FlagToString", "android.view.ViewDebug$IntToString", "android.widget.RemoteViews$RemoteView", "dalvik.annotation.TestTarget", "dalvik.annotation.TestTargetClass", "java.lang.Deprecated", "java.lang.Override", "java.lang.SuppressWarnings", "java.lang.annotation.Documented", "java.lang.annotation.Inherited", "java.lang.annotation.Retention", "java.lang.annotation.Target", "java.lang.annotation.Documented" }; static Element createAnnotationMock (Document doc, String name) { Element e = doc.createElement ("class"); e.setAttribute ("abstract", "true"); e.setAttribute ("deprecated", "not deprecated"); e.setAttribute ("extends", "java.lang.Object"); e.setAttribute ("final", "false"); e.setAttribute ("name", name); e.setAttribute ("static", "false"); e.setAttribute ("visibility", "public"); Element i = doc.createElement ("implements"); i.setAttribute ("name", "java.lang.annotation.Annotation"); e.appendChild (i); return e; } public static void main (String[] args) { String droiddocs = null; String javadocs = null; String annots = null; List<String> jar_paths = new ArrayList<String> (); String out_path = null; List<String> additional_jar_paths = new ArrayList<String> (); String usage = "Usage: jar2xml --jar=<jarfile> --out=<file> [--javadocpath=<javadoc>] [--droiddocpath=<droiddoc>] [--annotations=<xmlfile>]"; for (String arg : args) { if (arg.startsWith ("--javadocpath=")) { javadocs = arg.substring (14); } else if (arg.startsWith ("--droiddocpath=")) { droiddocs = arg.substring (15); } else if (arg.startsWith ("--annotations=")) { annots = arg.substring (14); } else if (arg.startsWith ("--jar=")) { jar_paths.add (arg.substring (6)); } else if (arg.startsWith ("--ref=")) { additional_jar_paths.add (arg.substring (6)); } else if (arg.startsWith ("--out=")) { out_path = arg.substring (6); } else { System.err.println (usage); System.exit (1); } } if (jar_paths.size() == 0 || out_path == null) { System.err.println (usage); System.exit (1); } - File dir = new File (out_path).getParentFile (); + File dir = new File (out_path).getAbsoluteFile ().getParentFile (); if (!dir.exists ()) dir.mkdirs (); JavaArchive jar = null; try { jar = new JavaArchive (jar_paths, additional_jar_paths); } catch (Exception e) { System.err.println ("Couldn't open java archive : " + e); System.exit (1); } try { if (annots != null) AndroidDocScraper.loadXml (annots); if (droiddocs != null) JavaClass.addDocScraper (new DroidDocScraper (new File (droiddocs))); if (javadocs != null) JavaClass.addDocScraper (new JavaDocScraper (new File (javadocs))); } catch (Exception e) { System.err.println ("Couldn't access javadocs at specified docpath. Continuing without it..."); } Document doc = null; try { DocumentBuilderFactory builder_factory = DocumentBuilderFactory.newInstance (); DocumentBuilder builder = builder_factory.newDocumentBuilder (); doc = builder.newDocument (); } catch (Exception e) { System.err.println ("Couldn't create xml document - exception occurred:" + e.getMessage ()); } Element root = doc.createElement ("api"); doc.appendChild (root); for (JavaPackage pkg : jar.getPackages ()) pkg.appendToDocument (doc, root); for (String ann : annotations) { String pkg = ann.substring (0, ann.lastIndexOf ('.')); NodeList nl = root.getChildNodes (); for (int ind = 0; ind < nl.getLength (); ind++) { Node n = nl.item (ind); if (!(n instanceof Element)) continue; Element el = (Element) n; if (el.getAttribute ("name").equals (pkg)) { String local = ann.substring (pkg.length () + 1); el.appendChild (createAnnotationMock (doc, local.replace ("$", "."))); } } } try { TransformerFactory transformer_factory = TransformerFactory.newInstance (); Transformer transformer = transformer_factory.newTransformer (); transformer.setOutputProperty (OutputKeys.INDENT, "yes"); FileOutputStream stream = new FileOutputStream(out_path); OutputStreamWriter writer = new OutputStreamWriter(stream,"UTF-8"); StreamResult result = new StreamResult (writer); DOMSource source = new DOMSource (doc); transformer.transform (source, result); writer.close (); } catch (Exception e) { System.err.println ("Couldn't format xml file - exception occurred:" + e.getMessage ()); } } }
true
true
public static void main (String[] args) { String droiddocs = null; String javadocs = null; String annots = null; List<String> jar_paths = new ArrayList<String> (); String out_path = null; List<String> additional_jar_paths = new ArrayList<String> (); String usage = "Usage: jar2xml --jar=<jarfile> --out=<file> [--javadocpath=<javadoc>] [--droiddocpath=<droiddoc>] [--annotations=<xmlfile>]"; for (String arg : args) { if (arg.startsWith ("--javadocpath=")) { javadocs = arg.substring (14); } else if (arg.startsWith ("--droiddocpath=")) { droiddocs = arg.substring (15); } else if (arg.startsWith ("--annotations=")) { annots = arg.substring (14); } else if (arg.startsWith ("--jar=")) { jar_paths.add (arg.substring (6)); } else if (arg.startsWith ("--ref=")) { additional_jar_paths.add (arg.substring (6)); } else if (arg.startsWith ("--out=")) { out_path = arg.substring (6); } else { System.err.println (usage); System.exit (1); } } if (jar_paths.size() == 0 || out_path == null) { System.err.println (usage); System.exit (1); } File dir = new File (out_path).getParentFile (); if (!dir.exists ()) dir.mkdirs (); JavaArchive jar = null; try { jar = new JavaArchive (jar_paths, additional_jar_paths); } catch (Exception e) { System.err.println ("Couldn't open java archive : " + e); System.exit (1); } try { if (annots != null) AndroidDocScraper.loadXml (annots); if (droiddocs != null) JavaClass.addDocScraper (new DroidDocScraper (new File (droiddocs))); if (javadocs != null) JavaClass.addDocScraper (new JavaDocScraper (new File (javadocs))); } catch (Exception e) { System.err.println ("Couldn't access javadocs at specified docpath. Continuing without it..."); } Document doc = null; try { DocumentBuilderFactory builder_factory = DocumentBuilderFactory.newInstance (); DocumentBuilder builder = builder_factory.newDocumentBuilder (); doc = builder.newDocument (); } catch (Exception e) { System.err.println ("Couldn't create xml document - exception occurred:" + e.getMessage ()); } Element root = doc.createElement ("api"); doc.appendChild (root); for (JavaPackage pkg : jar.getPackages ()) pkg.appendToDocument (doc, root); for (String ann : annotations) { String pkg = ann.substring (0, ann.lastIndexOf ('.')); NodeList nl = root.getChildNodes (); for (int ind = 0; ind < nl.getLength (); ind++) { Node n = nl.item (ind); if (!(n instanceof Element)) continue; Element el = (Element) n; if (el.getAttribute ("name").equals (pkg)) { String local = ann.substring (pkg.length () + 1); el.appendChild (createAnnotationMock (doc, local.replace ("$", "."))); } } } try { TransformerFactory transformer_factory = TransformerFactory.newInstance (); Transformer transformer = transformer_factory.newTransformer (); transformer.setOutputProperty (OutputKeys.INDENT, "yes"); FileOutputStream stream = new FileOutputStream(out_path); OutputStreamWriter writer = new OutputStreamWriter(stream,"UTF-8"); StreamResult result = new StreamResult (writer); DOMSource source = new DOMSource (doc); transformer.transform (source, result); writer.close (); } catch (Exception e) { System.err.println ("Couldn't format xml file - exception occurred:" + e.getMessage ()); } }
public static void main (String[] args) { String droiddocs = null; String javadocs = null; String annots = null; List<String> jar_paths = new ArrayList<String> (); String out_path = null; List<String> additional_jar_paths = new ArrayList<String> (); String usage = "Usage: jar2xml --jar=<jarfile> --out=<file> [--javadocpath=<javadoc>] [--droiddocpath=<droiddoc>] [--annotations=<xmlfile>]"; for (String arg : args) { if (arg.startsWith ("--javadocpath=")) { javadocs = arg.substring (14); } else if (arg.startsWith ("--droiddocpath=")) { droiddocs = arg.substring (15); } else if (arg.startsWith ("--annotations=")) { annots = arg.substring (14); } else if (arg.startsWith ("--jar=")) { jar_paths.add (arg.substring (6)); } else if (arg.startsWith ("--ref=")) { additional_jar_paths.add (arg.substring (6)); } else if (arg.startsWith ("--out=")) { out_path = arg.substring (6); } else { System.err.println (usage); System.exit (1); } } if (jar_paths.size() == 0 || out_path == null) { System.err.println (usage); System.exit (1); } File dir = new File (out_path).getAbsoluteFile ().getParentFile (); if (!dir.exists ()) dir.mkdirs (); JavaArchive jar = null; try { jar = new JavaArchive (jar_paths, additional_jar_paths); } catch (Exception e) { System.err.println ("Couldn't open java archive : " + e); System.exit (1); } try { if (annots != null) AndroidDocScraper.loadXml (annots); if (droiddocs != null) JavaClass.addDocScraper (new DroidDocScraper (new File (droiddocs))); if (javadocs != null) JavaClass.addDocScraper (new JavaDocScraper (new File (javadocs))); } catch (Exception e) { System.err.println ("Couldn't access javadocs at specified docpath. Continuing without it..."); } Document doc = null; try { DocumentBuilderFactory builder_factory = DocumentBuilderFactory.newInstance (); DocumentBuilder builder = builder_factory.newDocumentBuilder (); doc = builder.newDocument (); } catch (Exception e) { System.err.println ("Couldn't create xml document - exception occurred:" + e.getMessage ()); } Element root = doc.createElement ("api"); doc.appendChild (root); for (JavaPackage pkg : jar.getPackages ()) pkg.appendToDocument (doc, root); for (String ann : annotations) { String pkg = ann.substring (0, ann.lastIndexOf ('.')); NodeList nl = root.getChildNodes (); for (int ind = 0; ind < nl.getLength (); ind++) { Node n = nl.item (ind); if (!(n instanceof Element)) continue; Element el = (Element) n; if (el.getAttribute ("name").equals (pkg)) { String local = ann.substring (pkg.length () + 1); el.appendChild (createAnnotationMock (doc, local.replace ("$", "."))); } } } try { TransformerFactory transformer_factory = TransformerFactory.newInstance (); Transformer transformer = transformer_factory.newTransformer (); transformer.setOutputProperty (OutputKeys.INDENT, "yes"); FileOutputStream stream = new FileOutputStream(out_path); OutputStreamWriter writer = new OutputStreamWriter(stream,"UTF-8"); StreamResult result = new StreamResult (writer); DOMSource source = new DOMSource (doc); transformer.transform (source, result); writer.close (); } catch (Exception e) { System.err.println ("Couldn't format xml file - exception occurred:" + e.getMessage ()); } }
diff --git a/src/java/nextgen/core/readers/PairedEndReader.java b/src/java/nextgen/core/readers/PairedEndReader.java index 21b062f..49a4eb4 100644 --- a/src/java/nextgen/core/readers/PairedEndReader.java +++ b/src/java/nextgen/core/readers/PairedEndReader.java @@ -1,417 +1,417 @@ package nextgen.core.readers; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.logging.Logger; import org.broad.igv.Globals; import broad.core.util.CLUtil; import broad.core.util.CLUtil.ArgumentMap; import net.sf.picard.util.Log; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMRecord; import net.sf.samtools.SAMRecordIterator; import net.sf.samtools.SAMSequenceRecord; import net.sf.samtools.util.CloseableIterator; import nextgen.core.alignment.Alignment; import nextgen.core.alignment.ChromosomeInconsistencyException; import nextgen.core.alignment.FragmentAlignment; import nextgen.core.alignment.AbstractPairedEndAlignment.TranscriptionRead; import nextgen.core.alignment.PairedEndAlignmentFactory; import nextgen.core.alignment.PairedReadAlignment; import nextgen.core.alignment.SingleEndAlignment; import nextgen.core.annotation.Annotation; import nextgen.core.writers.PairedEndWriter; //Reads the new PairedEnd BAM files into a queryable object public class PairedEndReader { private static final Log log = Log.getInstance(PairedEndReader.class); public static enum AlignmentType { PAIRED_END, SINGLE_END }; private boolean warned = false; private CloseableIterator<Alignment> mCurrentIterator = null; private SAMFileReader reader; private SAMFileHeader header; private AlignmentType alignmentType; private TranscriptionRead strand; private boolean fragment=true; public PairedEndReader(File bam){ //We are going to read the .pebam files with special attribute flags and create a new "Alignment" object this(bam,TranscriptionRead.UNSTRANDED); } public PairedEndReader(File bam,TranscriptionRead read){ //We are going to read the .pebam files with special attribute flags and create a new "Alignment" object this(bam,read,true); } public PairedEndReader(File bam,TranscriptionRead read,boolean fra){ //We are going to read the .pebam files with special attribute flags and create a new "Alignment" object this.reader=new SAMFileReader(bam); this.header=reader.getFileHeader(); alignmentType = getAlignmentType(this.header); strand = read; setFragmentFlag(fra); } private static AlignmentType getAlignmentType(SAMFileHeader header) { //check if it is paired end with our modified record Object isPairedEndFormat=header.getAttribute(PairedEndWriter.mateLineFlag); return (isPairedEndFormat != null) ? AlignmentType.PAIRED_END : AlignmentType.SINGLE_END; } public AlignmentType getAlignmentType() { return getAlignmentType(this.header); } public void setFragmentFlag(boolean fra){ fragment = fra; } public void close() throws IOException { mCurrentIterator.close(); reader.close(); } public SAMFileHeader getHeader() { if (header == null) { loadHeader(); } return header; } private void loadHeader() { header = reader.getFileHeader(); } public Set<String> getSequenceNames() { SAMFileHeader header = getHeader(); if (header == null) { return null; } Set<String> seqNames = new HashSet<String>(); List<SAMSequenceRecord> records = header.getSequenceDictionary().getSequences(); if (records.size() > 0) { for (SAMSequenceRecord rec : header.getSequenceDictionary().getSequences()) { String chr = rec.getSequenceName(); seqNames.add(chr); } } return seqNames; } public boolean hasIndex() { return reader.hasIndex(); } public CloseableIterator<Alignment> iterator() { if (mCurrentIterator != null) { throw new IllegalStateException("Iteration in progress"); } mCurrentIterator = new PairedEndIterator(); return mCurrentIterator; } public CloseableIterator<Alignment> query(Annotation a, boolean contained) { SAMRecordIterator query = null; query = reader.query(a.getReferenceName(), a.getSAMStart(), a.getSAMEnd(), contained); mCurrentIterator = new PairedEndIterator(query); return mCurrentIterator; } private class PairedEndIterator implements CloseableIterator<Alignment> { private Alignment mNextRecord = null; private boolean isClosed = false; private CloseableIterator<SAMRecord> itr; public PairedEndIterator() { this(reader.iterator()); } public PairedEndIterator(CloseableIterator<SAMRecord> itr) { this.itr = itr; advance(); } public void close() { if (!isClosed) { if (mCurrentIterator == null) { throw new IllegalStateException("Attempt to close non-current iterator"); } itr.close(); mCurrentIterator = null; isClosed = true; } } public void remove() { throw new UnsupportedOperationException("Not supported: remove"); } public boolean hasNext() { if (isClosed) throw new IllegalStateException("Iterator has been closed"); return (mNextRecord != null); } public Alignment next() { if (isClosed) throw new IllegalStateException("Iterator has been closed"); final Alignment result = mNextRecord; advance(); return result; } private void advance() { if (!itr.hasNext()) mNextRecord = null; // VERY IMPORTANT. Otherwise infinite loop while (itr.hasNext()) { SAMRecord r = itr.next(); mNextRecord = samRecordToAlignment(r,strand,fragment); if (mNextRecord != null) {break;} else {log.debug("samRecordToAlignment returned null for this record" + r.getSAMString() );} } } /** * @return The record that will be return by the next call to next() */ protected Alignment peek() { return mNextRecord; } } /** * Parse the record * Either it is our modified record with the mate information or a standard single end read * @param record SamRecord * @return Alignment * @throws ChromosomeInconsistencyException */ private Alignment samRecordToAlignment(SAMRecord record,TranscriptionRead transcriptionRead,boolean fragment) { Alignment rtrn; try { if (alignmentType == AlignmentType.PAIRED_END) { if (record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { //revised to read single end data @zhuxp String name=record.getReadName(); int mateStart=record.getMateAlignmentStart(); String mateCigar=record.getAttribute(PairedEndWriter.mateCigarFlag).toString(); String mateSequence=record.getAttribute(PairedEndWriter.mateSequenceFlag).toString(); boolean mateNegativeStrand=record.getMateNegativeStrandFlag(); String mateChr=record.getMateReferenceName(); int readStart=new Integer(record.getAttribute(PairedEndWriter.readStartFlag).toString()); String readCigar=record.getAttribute(PairedEndWriter.readCigarFlag).toString(); String readSequence=record.getReadString(); boolean readNegativeStrand=record.getReadNegativeStrandFlag(); String readChr=record.getReferenceName(); // Make the first mate record.setAlignmentStart(readStart); record.setReferenceName(readChr); record.setReadNegativeStrandFlag(readNegativeStrand); record.setCigarString(readCigar); record.setReadString(readSequence); record.setReadName(name); // Make the second mate SAMRecord record2=new SAMRecord(record.getHeader()); record2.setAlignmentStart(mateStart); record2.setReferenceName(mateChr); record2.setReadNegativeStrandFlag(mateNegativeStrand); record2.setCigarString(mateCigar); record2.setReadString(mateSequence); record2.setReadName(name); SingleEndAlignment firstMate=new SingleEndAlignment(record); SingleEndAlignment secondMate=new SingleEndAlignment(record2); rtrn=new PairedEndAlignmentFactory().getAlignment(fragment, firstMate, secondMate, transcriptionRead); rtrn.setProperPairFlag(record.getProperPairFlag()); } else { rtrn = new SingleEndAlignment(record,record.getFirstOfPairFlag()); } } else { //check if paired end without our modified record --> throw warning if (record.getReadPairedFlag() && !record.getMateUnmappedFlag() && !warned) { log.warn("DEBUG: Paired end reads were found but file is not in our paired end format. Processing as single-end reads ..."); warned = true; } //If first read is in direction of trasncription if(transcriptionRead.equals(TranscriptionRead.FIRST_OF_PAIR)){ //This is the first read if(record.getFirstOfPairFlag()){ //Orientation of fragment is same as that of read } //This is the other mate //Reverse its orientation else{ record.setReadNegativeStrandFlag(!record.getReadNegativeStrandFlag()); } } //Second read is the transcription read else if(transcriptionRead.equals(TranscriptionRead.SECOND_OF_PAIR)){ //This is the first read //Reverse orientation if(record.getFirstOfPairFlag()){ record.setReadNegativeStrandFlag(!record.getReadNegativeStrandFlag()); } //This is the other mate else{ //NOTHING } }//UNSTRANDED else{ //NOTHING } rtrn = new SingleEndAlignment(record, record.getReadPairedFlag() && record.getFirstOfPairFlag()); //rtrn=new SingleEndAlignment(record); } - } finally { - log.error("Failed on SAMRecord: " + record.toString()); + } catch(RuntimeException e) { + throw e; } return rtrn; } /** * Get the lengths of the reference sequences * @param chr the chromsoome to query size * @return Map associating each reference name with sequence length */ public int getRefSequenceLengths(String chr) { Set<String> seqNames = getSequenceNames(); for(String seq : seqNames) { SAMSequenceRecord rec = header.getSequence(seq); if(seq.equalsIgnoreCase(chr)){ return Integer.valueOf(rec.getSequenceLength()); } } return -99; } /** * Get the lengths of the reference sequences * @return Map associating each reference name with sequence length */ public Map<String, Integer> getRefSequenceLengths() { Map<String, Integer> rtrn=new TreeMap<String, Integer>(); Set<String> seqNames = getSequenceNames(); for(String seq : seqNames) { SAMSequenceRecord rec = header.getSequence(seq); rtrn.put(seq, Integer.valueOf(rec.getSequenceLength())); } return rtrn; } /** * Returns {@code true} if the given SAM file is in paired end format (has the mateLine) attribute. * Will also check the file with the default extension. * @param fileToCheck * @return */ public static boolean isPairedEndFormat(String fileToCheck) { return (getPairedEndFile(fileToCheck) != null); } /** * Returns the file itself or the file plus the default {@code PAIRED_END_EXTENSION} if either * is in paired end format. If neither is in paired end format, returns null. * @param fileToCheck * @return */ public static String getPairedEndFile(String fileToCheck) { //Check the header to see if it is "Paired End Format" SAMFileReader reader = new SAMFileReader(new File(fileToCheck)); if (getAlignmentType(reader.getFileHeader()) == AlignmentType.PAIRED_END) { return fileToCheck; } //else, lets make the logical extension and see if it is there String tmpBam = fileToCheck + PairedEndWriter.PAIRED_END_EXTENSION; boolean fileExists = new File(tmpBam).exists(); if (fileExists) { //Lets test to make sure it has the correct line reader = new SAMFileReader(new File(tmpBam)); if (getAlignmentType(reader.getFileHeader()) == AlignmentType.PAIRED_END) { return tmpBam; } } return null; } /** * Finds a paired end file or creates one if it doesn't exist * @param fileToCheck * @return */ public static String getOrCreatePairedEndFile(String fileToCheck,TranscriptionRead txnRead) { String result = PairedEndReader.getPairedEndFile(fileToCheck); if (result == null) { result = PairedEndWriter.getDefaultFile(fileToCheck); PairedEndWriter writer = new PairedEndWriter(new File(fileToCheck), result); writer.convertInputToPairedEnd(txnRead); } return result; } public static void main(String[] args){ Globals.setHeadless(true); /* * @param for ArgumentMap - size, usage, default task * argMap maps the command line arguments to the respective parameters */ ArgumentMap argMap = CLUtil.getParameters(args,usage,"makeFile"); TranscriptionRead strand = TranscriptionRead.UNSTRANDED; if(argMap.get("strand").equalsIgnoreCase("first")){ //System.out.println("First read"); strand = TranscriptionRead.FIRST_OF_PAIR; } else if(argMap.get("strand").equalsIgnoreCase("second")){ //System.out.println("Second read"); strand = TranscriptionRead.SECOND_OF_PAIR; } else log.info("no strand"); //String bamFile = argMap.getMandatory("alignment"); String bamFile = getOrCreatePairedEndFile(argMap.getMandatory("alignment"),strand); String file = PairedEndReader.getPairedEndFile(bamFile); if (file == null) { file = PairedEndWriter.getDefaultFile(bamFile); PairedEndWriter writer = new PairedEndWriter(new File(bamFile), file); writer.convertInputToPairedEnd(strand); } } static final String usage = "Usage: CreatePairedEndBamFile -task makeFile "+ "\n**************************************************************"+ "\n\t\tArguments"+ "\n**************************************************************"+ "\n\t\t-strand <VALUES: first, second, unstranded. Specifies the mate that is in the direction of transcription DEFAULT: Unstranded> "+ "\n\n\t\t-alignment <Alignment file to be used for reconstruction. Required.> "; }
true
true
private Alignment samRecordToAlignment(SAMRecord record,TranscriptionRead transcriptionRead,boolean fragment) { Alignment rtrn; try { if (alignmentType == AlignmentType.PAIRED_END) { if (record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { //revised to read single end data @zhuxp String name=record.getReadName(); int mateStart=record.getMateAlignmentStart(); String mateCigar=record.getAttribute(PairedEndWriter.mateCigarFlag).toString(); String mateSequence=record.getAttribute(PairedEndWriter.mateSequenceFlag).toString(); boolean mateNegativeStrand=record.getMateNegativeStrandFlag(); String mateChr=record.getMateReferenceName(); int readStart=new Integer(record.getAttribute(PairedEndWriter.readStartFlag).toString()); String readCigar=record.getAttribute(PairedEndWriter.readCigarFlag).toString(); String readSequence=record.getReadString(); boolean readNegativeStrand=record.getReadNegativeStrandFlag(); String readChr=record.getReferenceName(); // Make the first mate record.setAlignmentStart(readStart); record.setReferenceName(readChr); record.setReadNegativeStrandFlag(readNegativeStrand); record.setCigarString(readCigar); record.setReadString(readSequence); record.setReadName(name); // Make the second mate SAMRecord record2=new SAMRecord(record.getHeader()); record2.setAlignmentStart(mateStart); record2.setReferenceName(mateChr); record2.setReadNegativeStrandFlag(mateNegativeStrand); record2.setCigarString(mateCigar); record2.setReadString(mateSequence); record2.setReadName(name); SingleEndAlignment firstMate=new SingleEndAlignment(record); SingleEndAlignment secondMate=new SingleEndAlignment(record2); rtrn=new PairedEndAlignmentFactory().getAlignment(fragment, firstMate, secondMate, transcriptionRead); rtrn.setProperPairFlag(record.getProperPairFlag()); } else { rtrn = new SingleEndAlignment(record,record.getFirstOfPairFlag()); } } else { //check if paired end without our modified record --> throw warning if (record.getReadPairedFlag() && !record.getMateUnmappedFlag() && !warned) { log.warn("DEBUG: Paired end reads were found but file is not in our paired end format. Processing as single-end reads ..."); warned = true; } //If first read is in direction of trasncription if(transcriptionRead.equals(TranscriptionRead.FIRST_OF_PAIR)){ //This is the first read if(record.getFirstOfPairFlag()){ //Orientation of fragment is same as that of read } //This is the other mate //Reverse its orientation else{ record.setReadNegativeStrandFlag(!record.getReadNegativeStrandFlag()); } } //Second read is the transcription read else if(transcriptionRead.equals(TranscriptionRead.SECOND_OF_PAIR)){ //This is the first read //Reverse orientation if(record.getFirstOfPairFlag()){ record.setReadNegativeStrandFlag(!record.getReadNegativeStrandFlag()); } //This is the other mate else{ //NOTHING } }//UNSTRANDED else{ //NOTHING } rtrn = new SingleEndAlignment(record, record.getReadPairedFlag() && record.getFirstOfPairFlag()); //rtrn=new SingleEndAlignment(record); } } finally { log.error("Failed on SAMRecord: " + record.toString()); } return rtrn; }
private Alignment samRecordToAlignment(SAMRecord record,TranscriptionRead transcriptionRead,boolean fragment) { Alignment rtrn; try { if (alignmentType == AlignmentType.PAIRED_END) { if (record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { //revised to read single end data @zhuxp String name=record.getReadName(); int mateStart=record.getMateAlignmentStart(); String mateCigar=record.getAttribute(PairedEndWriter.mateCigarFlag).toString(); String mateSequence=record.getAttribute(PairedEndWriter.mateSequenceFlag).toString(); boolean mateNegativeStrand=record.getMateNegativeStrandFlag(); String mateChr=record.getMateReferenceName(); int readStart=new Integer(record.getAttribute(PairedEndWriter.readStartFlag).toString()); String readCigar=record.getAttribute(PairedEndWriter.readCigarFlag).toString(); String readSequence=record.getReadString(); boolean readNegativeStrand=record.getReadNegativeStrandFlag(); String readChr=record.getReferenceName(); // Make the first mate record.setAlignmentStart(readStart); record.setReferenceName(readChr); record.setReadNegativeStrandFlag(readNegativeStrand); record.setCigarString(readCigar); record.setReadString(readSequence); record.setReadName(name); // Make the second mate SAMRecord record2=new SAMRecord(record.getHeader()); record2.setAlignmentStart(mateStart); record2.setReferenceName(mateChr); record2.setReadNegativeStrandFlag(mateNegativeStrand); record2.setCigarString(mateCigar); record2.setReadString(mateSequence); record2.setReadName(name); SingleEndAlignment firstMate=new SingleEndAlignment(record); SingleEndAlignment secondMate=new SingleEndAlignment(record2); rtrn=new PairedEndAlignmentFactory().getAlignment(fragment, firstMate, secondMate, transcriptionRead); rtrn.setProperPairFlag(record.getProperPairFlag()); } else { rtrn = new SingleEndAlignment(record,record.getFirstOfPairFlag()); } } else { //check if paired end without our modified record --> throw warning if (record.getReadPairedFlag() && !record.getMateUnmappedFlag() && !warned) { log.warn("DEBUG: Paired end reads were found but file is not in our paired end format. Processing as single-end reads ..."); warned = true; } //If first read is in direction of trasncription if(transcriptionRead.equals(TranscriptionRead.FIRST_OF_PAIR)){ //This is the first read if(record.getFirstOfPairFlag()){ //Orientation of fragment is same as that of read } //This is the other mate //Reverse its orientation else{ record.setReadNegativeStrandFlag(!record.getReadNegativeStrandFlag()); } } //Second read is the transcription read else if(transcriptionRead.equals(TranscriptionRead.SECOND_OF_PAIR)){ //This is the first read //Reverse orientation if(record.getFirstOfPairFlag()){ record.setReadNegativeStrandFlag(!record.getReadNegativeStrandFlag()); } //This is the other mate else{ //NOTHING } }//UNSTRANDED else{ //NOTHING } rtrn = new SingleEndAlignment(record, record.getReadPairedFlag() && record.getFirstOfPairFlag()); //rtrn=new SingleEndAlignment(record); } } catch(RuntimeException e) { throw e; } return rtrn; }
diff --git a/src/main/java/edu/ucsf/rbvi/cddApp/internal/ui/DomainsPanel.java b/src/main/java/edu/ucsf/rbvi/cddApp/internal/ui/DomainsPanel.java index 6314634..189c373 100644 --- a/src/main/java/edu/ucsf/rbvi/cddApp/internal/ui/DomainsPanel.java +++ b/src/main/java/edu/ucsf/rbvi/cddApp/internal/ui/DomainsPanel.java @@ -1,166 +1,169 @@ package edu.ucsf.rbvi.cddApp.internal.ui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Desktop; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import javax.swing.Icon; import javax.swing.JEditorPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import org.cytoscape.application.CyApplicationManager; import org.cytoscape.application.swing.CytoPanelComponent; import org.cytoscape.application.swing.CytoPanelName; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyTable; import org.cytoscape.model.events.RowSetRecord; import org.cytoscape.model.events.RowsSetEvent; import org.cytoscape.model.events.RowsSetListener; import org.cytoscape.util.swing.OpenBrowser; /** * Displays information on the domains of a protein from the CDD in the Results panel. * @author Allan Wu * */ public class DomainsPanel extends JPanel implements CytoPanelComponent, RowsSetListener { private JEditorPane textArea; private JScrollPane scrollPane; private HashMap<Long, Boolean> selectedNodes; private CyApplicationManager manager; /** * */ private static final long serialVersionUID = 4255348824636450908L; /** * * @param manager CyApplication manager of this instance of Cytoscape * @param openBrowser class that opens the default browser from Cytoscape */ public DomainsPanel(CyApplicationManager manager, OpenBrowser openBrowser) { final OpenBrowser ob = openBrowser; setLayout(new BorderLayout()); textArea = new JEditorPane("text/html", null); textArea.setEditable(false); textArea.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { ob.openURL(e.getURL().toString()); } } }); scrollPane = new JScrollPane(textArea); add(BorderLayout.CENTER, scrollPane); selectedNodes = new HashMap<Long, Boolean>(); this.manager = manager; } public void handleEvent(RowsSetEvent arg0) { try { CyTable table; - if (manager.getCurrentNetwork() == null) return; + // If we're not getting selection, we're not interested + if (manager.getCurrentNetwork() == null || !arg0.containsColumn(CyNetwork.SELECTED)) return; table = manager.getCurrentNetwork().getDefaultNodeTable(); + // Oops, not relevant to us... + if (table.getColumn("PDB-Chain") == null) return; String message = ""; Collection<RowSetRecord> record = arg0.getPayloadCollection(); for (RowSetRecord r: record) { Long suid = r.getRow().get(CyNetwork.SUID, Long.class); if (suid != null && table.getRow(suid) != null && table.getRow(suid).getList("PDB-Chain", String.class) != null && table.getRow(suid).getList("PDB-Chain", String.class).size() > 0 && table.getRow(suid).getList("PDB-Chain-Features", String.class) != null && table.getRow(suid).getList("PDB-Chain-Features", String.class).size() > 0) selectedNodes.put(suid,r.getRow().get(CyNetwork.SELECTED, Boolean.class)); } for (long node: selectedNodes.keySet()) { if (table.getRow(node) != null && selectedNodes.get(node) != null && selectedNodes.get(node)) { List<String> pdbChains = table.getRow(node).getList("PDB-Chain", String.class), pdbChainFeatures = table.getRow(node).getList("PDB-Chain-Features", String.class), cddAccession = table.getRow(node).getList("CDD-Accession", String.class), domainType = table.getRow(node).getList("CDD-Hit-Type", String.class), cddFeature = table.getRow(node).getList("CDD-Feature", String.class), cddFeatureType = table.getRow(node).getList("CDD-Feature-Type", String.class), cddFeatureSite = table.getRow(node).getList("CDD-Feature-Site", String.class); List<Long> cddFrom = table.getRow(node).getList("CDD-From", Long.class), cddTo = table.getRow(node).getList("CDD-To", Long.class); if ((pdbChains == null || pdbChains.size() == 0 || pdbChains.get(0).equals("")) && (cddFeature == null || cddFeature.size() == 0 || cddFeature.get(0).equals(""))) continue; HashSet<String> chains = new HashSet<String>(); for (String s: pdbChains) if (!s.equals("")) chains.add(s); for (String s: pdbChainFeatures) if (!s.equals("")) chains.add(s); HashMap<String, List<Integer>> pdbChainPos = new HashMap<String, List<Integer>>(), pdbChainFeaturePos = new HashMap<String, List<Integer>>(); for (int i = 0; i < pdbChains.size(); i++) { String n = pdbChains.get(i); if (!pdbChainPos.containsKey(n)) pdbChainPos.put(n, new ArrayList<Integer>()); pdbChainPos.get(n).add(i); } for (int i = 0; i < pdbChainFeatures.size(); i++) { String n = pdbChainFeatures.get(i); if (!pdbChainFeaturePos.containsKey(n)) pdbChainFeaturePos.put(n, new ArrayList<Integer>()); pdbChainFeaturePos.get(n).add(i); } message = message + "<div>"; message = message + "<p><b>Node: \n" + table.getRow(node).get(CyNetwork.NAME, String.class) + "</b></p>\n\n"; for (String chain: chains) { message = message + "<p>Protein: " + chain + "</p>\n"; message = message + "<table border=\"1\">\n<tr><th>Domain Name</th><th>Domain Type</th><th>Domain Range</th></tr>\n"; if (pdbChains != null && pdbChains.size() != 0 && ! pdbChains.get(0).equals("") && pdbChainPos.get(chain) != null) for (int i: pdbChainPos.get(chain)) { message = message + "<tr><td><a href=\"http://www.ncbi.nlm.nih.gov/cdd/?term=" + cddAccession.get(i) + "\">" + cddAccession.get(i) + "</a></td>\n" + "<td>" + domainType.get(i) + "</td>\n" + "<td>" + cddFrom.get(i) + "-" + cddTo.get(i) + "</td></tr>\n\n"; } if (cddFeature != null && cddFeature.size() != 0 && ! cddFeature.get(0).equals("") && pdbChainFeaturePos.get(chain) != null) for (int i: pdbChainFeaturePos.get(chain)) { message = message + "<tr><td>" + cddFeature.get(i) + "</td>\n" + "<td>" + cddFeatureType.get(i) + "</td>\n" + "<td>" + cddFeatureSite.get(i) + "</td></tr>\n\n"; } message = message + "</table>"; } message = message + "</div>"; } } textArea.setText(message); } catch (Exception e){e.printStackTrace();} } public Component getComponent() { // TODO Auto-generated method stub return this; } public CytoPanelName getCytoPanelName() { // TODO Auto-generated method stub return CytoPanelName.EAST; } public Icon getIcon() { // TODO Auto-generated method stub return null; } public String getTitle() { // TODO Auto-generated method stub return "CDD Domains"; } }
false
true
public void handleEvent(RowsSetEvent arg0) { try { CyTable table; if (manager.getCurrentNetwork() == null) return; table = manager.getCurrentNetwork().getDefaultNodeTable(); String message = ""; Collection<RowSetRecord> record = arg0.getPayloadCollection(); for (RowSetRecord r: record) { Long suid = r.getRow().get(CyNetwork.SUID, Long.class); if (suid != null && table.getRow(suid) != null && table.getRow(suid).getList("PDB-Chain", String.class) != null && table.getRow(suid).getList("PDB-Chain", String.class).size() > 0 && table.getRow(suid).getList("PDB-Chain-Features", String.class) != null && table.getRow(suid).getList("PDB-Chain-Features", String.class).size() > 0) selectedNodes.put(suid,r.getRow().get(CyNetwork.SELECTED, Boolean.class)); } for (long node: selectedNodes.keySet()) { if (table.getRow(node) != null && selectedNodes.get(node) != null && selectedNodes.get(node)) { List<String> pdbChains = table.getRow(node).getList("PDB-Chain", String.class), pdbChainFeatures = table.getRow(node).getList("PDB-Chain-Features", String.class), cddAccession = table.getRow(node).getList("CDD-Accession", String.class), domainType = table.getRow(node).getList("CDD-Hit-Type", String.class), cddFeature = table.getRow(node).getList("CDD-Feature", String.class), cddFeatureType = table.getRow(node).getList("CDD-Feature-Type", String.class), cddFeatureSite = table.getRow(node).getList("CDD-Feature-Site", String.class); List<Long> cddFrom = table.getRow(node).getList("CDD-From", Long.class), cddTo = table.getRow(node).getList("CDD-To", Long.class); if ((pdbChains == null || pdbChains.size() == 0 || pdbChains.get(0).equals("")) && (cddFeature == null || cddFeature.size() == 0 || cddFeature.get(0).equals(""))) continue; HashSet<String> chains = new HashSet<String>(); for (String s: pdbChains) if (!s.equals("")) chains.add(s); for (String s: pdbChainFeatures) if (!s.equals("")) chains.add(s); HashMap<String, List<Integer>> pdbChainPos = new HashMap<String, List<Integer>>(), pdbChainFeaturePos = new HashMap<String, List<Integer>>(); for (int i = 0; i < pdbChains.size(); i++) { String n = pdbChains.get(i); if (!pdbChainPos.containsKey(n)) pdbChainPos.put(n, new ArrayList<Integer>()); pdbChainPos.get(n).add(i); } for (int i = 0; i < pdbChainFeatures.size(); i++) { String n = pdbChainFeatures.get(i); if (!pdbChainFeaturePos.containsKey(n)) pdbChainFeaturePos.put(n, new ArrayList<Integer>()); pdbChainFeaturePos.get(n).add(i); } message = message + "<div>"; message = message + "<p><b>Node: \n" + table.getRow(node).get(CyNetwork.NAME, String.class) + "</b></p>\n\n"; for (String chain: chains) { message = message + "<p>Protein: " + chain + "</p>\n"; message = message + "<table border=\"1\">\n<tr><th>Domain Name</th><th>Domain Type</th><th>Domain Range</th></tr>\n"; if (pdbChains != null && pdbChains.size() != 0 && ! pdbChains.get(0).equals("") && pdbChainPos.get(chain) != null) for (int i: pdbChainPos.get(chain)) { message = message + "<tr><td><a href=\"http://www.ncbi.nlm.nih.gov/cdd/?term=" + cddAccession.get(i) + "\">" + cddAccession.get(i) + "</a></td>\n" + "<td>" + domainType.get(i) + "</td>\n" + "<td>" + cddFrom.get(i) + "-" + cddTo.get(i) + "</td></tr>\n\n"; } if (cddFeature != null && cddFeature.size() != 0 && ! cddFeature.get(0).equals("") && pdbChainFeaturePos.get(chain) != null) for (int i: pdbChainFeaturePos.get(chain)) { message = message + "<tr><td>" + cddFeature.get(i) + "</td>\n" + "<td>" + cddFeatureType.get(i) + "</td>\n" + "<td>" + cddFeatureSite.get(i) + "</td></tr>\n\n"; } message = message + "</table>"; } message = message + "</div>"; } } textArea.setText(message); } catch (Exception e){e.printStackTrace();} }
public void handleEvent(RowsSetEvent arg0) { try { CyTable table; // If we're not getting selection, we're not interested if (manager.getCurrentNetwork() == null || !arg0.containsColumn(CyNetwork.SELECTED)) return; table = manager.getCurrentNetwork().getDefaultNodeTable(); // Oops, not relevant to us... if (table.getColumn("PDB-Chain") == null) return; String message = ""; Collection<RowSetRecord> record = arg0.getPayloadCollection(); for (RowSetRecord r: record) { Long suid = r.getRow().get(CyNetwork.SUID, Long.class); if (suid != null && table.getRow(suid) != null && table.getRow(suid).getList("PDB-Chain", String.class) != null && table.getRow(suid).getList("PDB-Chain", String.class).size() > 0 && table.getRow(suid).getList("PDB-Chain-Features", String.class) != null && table.getRow(suid).getList("PDB-Chain-Features", String.class).size() > 0) selectedNodes.put(suid,r.getRow().get(CyNetwork.SELECTED, Boolean.class)); } for (long node: selectedNodes.keySet()) { if (table.getRow(node) != null && selectedNodes.get(node) != null && selectedNodes.get(node)) { List<String> pdbChains = table.getRow(node).getList("PDB-Chain", String.class), pdbChainFeatures = table.getRow(node).getList("PDB-Chain-Features", String.class), cddAccession = table.getRow(node).getList("CDD-Accession", String.class), domainType = table.getRow(node).getList("CDD-Hit-Type", String.class), cddFeature = table.getRow(node).getList("CDD-Feature", String.class), cddFeatureType = table.getRow(node).getList("CDD-Feature-Type", String.class), cddFeatureSite = table.getRow(node).getList("CDD-Feature-Site", String.class); List<Long> cddFrom = table.getRow(node).getList("CDD-From", Long.class), cddTo = table.getRow(node).getList("CDD-To", Long.class); if ((pdbChains == null || pdbChains.size() == 0 || pdbChains.get(0).equals("")) && (cddFeature == null || cddFeature.size() == 0 || cddFeature.get(0).equals(""))) continue; HashSet<String> chains = new HashSet<String>(); for (String s: pdbChains) if (!s.equals("")) chains.add(s); for (String s: pdbChainFeatures) if (!s.equals("")) chains.add(s); HashMap<String, List<Integer>> pdbChainPos = new HashMap<String, List<Integer>>(), pdbChainFeaturePos = new HashMap<String, List<Integer>>(); for (int i = 0; i < pdbChains.size(); i++) { String n = pdbChains.get(i); if (!pdbChainPos.containsKey(n)) pdbChainPos.put(n, new ArrayList<Integer>()); pdbChainPos.get(n).add(i); } for (int i = 0; i < pdbChainFeatures.size(); i++) { String n = pdbChainFeatures.get(i); if (!pdbChainFeaturePos.containsKey(n)) pdbChainFeaturePos.put(n, new ArrayList<Integer>()); pdbChainFeaturePos.get(n).add(i); } message = message + "<div>"; message = message + "<p><b>Node: \n" + table.getRow(node).get(CyNetwork.NAME, String.class) + "</b></p>\n\n"; for (String chain: chains) { message = message + "<p>Protein: " + chain + "</p>\n"; message = message + "<table border=\"1\">\n<tr><th>Domain Name</th><th>Domain Type</th><th>Domain Range</th></tr>\n"; if (pdbChains != null && pdbChains.size() != 0 && ! pdbChains.get(0).equals("") && pdbChainPos.get(chain) != null) for (int i: pdbChainPos.get(chain)) { message = message + "<tr><td><a href=\"http://www.ncbi.nlm.nih.gov/cdd/?term=" + cddAccession.get(i) + "\">" + cddAccession.get(i) + "</a></td>\n" + "<td>" + domainType.get(i) + "</td>\n" + "<td>" + cddFrom.get(i) + "-" + cddTo.get(i) + "</td></tr>\n\n"; } if (cddFeature != null && cddFeature.size() != 0 && ! cddFeature.get(0).equals("") && pdbChainFeaturePos.get(chain) != null) for (int i: pdbChainFeaturePos.get(chain)) { message = message + "<tr><td>" + cddFeature.get(i) + "</td>\n" + "<td>" + cddFeatureType.get(i) + "</td>\n" + "<td>" + cddFeatureSite.get(i) + "</td></tr>\n\n"; } message = message + "</table>"; } message = message + "</div>"; } } textArea.setText(message); } catch (Exception e){e.printStackTrace();} }
diff --git a/Osm2GpsMid/src/de/ueller/osmToGpsMid/TriangulateRelations.java b/Osm2GpsMid/src/de/ueller/osmToGpsMid/TriangulateRelations.java index 055370a0..157cf699 100644 --- a/Osm2GpsMid/src/de/ueller/osmToGpsMid/TriangulateRelations.java +++ b/Osm2GpsMid/src/de/ueller/osmToGpsMid/TriangulateRelations.java @@ -1,159 +1,159 @@ /** * This file is part of OSM2GpsMid * * 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. * * Copyright (C) 2007 Harald Mueller * Copyright (C) 2007, 2008 Kai Krueger */ package de.ueller.osmToGpsMid; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import de.ueller.osmToGpsMid.area.Area; import de.ueller.osmToGpsMid.area.Outline; import de.ueller.osmToGpsMid.area.Triangle; import de.ueller.osmToGpsMid.area.Vertex; import de.ueller.osmToGpsMid.model.Member; import de.ueller.osmToGpsMid.model.Relation; import de.ueller.osmToGpsMid.model.Node; import de.ueller.osmToGpsMid.model.Way; /** * @author hmueller * */ public class TriangulateRelations { private final OxParser parser; private final Configuration conf; int triangles=0; int areas=0; public TriangulateRelations(OxParser parser, Configuration conf) { this.parser = parser; this.conf = conf; convertAreasToTriangles(); parser.resize(); System.out.println("Remaining after triangulation:"); System.out.println(" Nodes: " + parser.getNodes().size()); System.out.println(" Ways: " + parser.getWays().size()); System.out.println(" Relations: " + parser.getRelations().size()); System.out.println(" Areas: " + areas); System.out.println(" Triangles: " + triangles); } /** * */ private void convertAreasToTriangles() { HashMap<Long, Way> wayHashMap = parser.getWayHashMap(); ArrayList<Way> removeWays = new ArrayList<Way>(); Way firstWay = null; Iterator<Relation> i = parser.getRelations().iterator(); rel: while (i.hasNext()) { firstWay = null; Relation r = i.next(); // System.out.println("check relation " + r + "is valid()=" + r.isValid() ); if (r.isValid() && "multipolygon".equals(r.getAttribute("type"))) { if (r.getAttribute("admin_level") != null){ continue; } if (r.getWayIds(Member.ROLE_OUTER).size() == 0){ System.out.println("Relation has no outer member"); - System.out.println(" see http://www.openstreetmap.org/?relation=" + r.id + "I'll ignore this relation"); + System.out.println(" see " + r.toUrl() + " I'll ignore this relation"); continue; } // System.out.println("Triangulate relation " + r.id); Area a = new Area(); // if (r.id == 405925 ){ // a.debug=true; // } for (Long ref : r.getWayIds(Member.ROLE_OUTER)) { // if (ref == 39123631) { // a.debug = true; // } Way w = wayHashMap.get(ref); if (w == null) { - System.out.println("Way http://www.openstreetmap.org/?way=" + ref + " was not found but referred as outline in "); - System.out.println(" relation http://www.openstreetmap.org/?relation=" + r.id + " I'll ignore this relation"); + System.out.println("Way " + w.toUrl() + " was not found but referred as outline in "); + System.out.println(" relation " + r.toUrl() + " I'll ignore this relation"); continue rel; } Outline no = createOutline(w); if (no != null) { a.addOutline(no); if (firstWay == null) { if (w.triangles != null){ System.out.println("strange this outline is already triangulated ! maybe dublicate. I will ignore it"); - System.out.println("Way http://www.openstreetmap.org/?way=" + ref); - System.out.println("please see http://www.openstreetmap.org/?relation=" + r.id); + System.out.println("Way " + w.toUrl()); + System.out.println("please see " + r.toUrl()); continue rel; } firstWay = w; } else { removeWays.add(w); } } } for (Long ref : r.getWayIds(Member.ROLE_INNER)) { Way w = wayHashMap.get(ref); if (w == null) { - System.out.println("Way http://www.openstreetmap.org/?way=" + ref + " was not found but referred as INNER in "); - System.out.println(" relation http://www.openstreetmap.org/?relation=" + r.id + " I'll ignore this relation"); + System.out.println("Way " + w.toUrl() + " was not found but referred as INNER in "); + System.out.println(" relation "+ r.toUrl() + " I'll ignore this relation"); continue rel; } Outline no = createOutline(w); if (no != null) { a.addHole(no); if (w.getType(conf) < 1) { removeWays.add(w); } } } List<Triangle> areaTriangles = a.triangulate(); firstWay.triangles = areaTriangles; firstWay.recreatePath(); r.getTags().remove("type"); if (r.getTags().size() > 0){ firstWay.replaceTags(r); } triangles += areaTriangles.size(); areas += 1; i.remove(); } } for (Way w : removeWays) { parser.removeWay(w); } parser.resize(); } /** * @param wayHashMap * @param r */ private Outline createOutline(Way w) { Outline o = null; if (w != null) { Node last = null; o = new Outline(); o.setWayId(w.id); for (Node n : w.getNodes()) { if (last != n) { o.append(new Vertex(n, o)); } last = n; } } return o; } }
false
true
private void convertAreasToTriangles() { HashMap<Long, Way> wayHashMap = parser.getWayHashMap(); ArrayList<Way> removeWays = new ArrayList<Way>(); Way firstWay = null; Iterator<Relation> i = parser.getRelations().iterator(); rel: while (i.hasNext()) { firstWay = null; Relation r = i.next(); // System.out.println("check relation " + r + "is valid()=" + r.isValid() ); if (r.isValid() && "multipolygon".equals(r.getAttribute("type"))) { if (r.getAttribute("admin_level") != null){ continue; } if (r.getWayIds(Member.ROLE_OUTER).size() == 0){ System.out.println("Relation has no outer member"); System.out.println(" see http://www.openstreetmap.org/?relation=" + r.id + "I'll ignore this relation"); continue; } // System.out.println("Triangulate relation " + r.id); Area a = new Area(); // if (r.id == 405925 ){ // a.debug=true; // } for (Long ref : r.getWayIds(Member.ROLE_OUTER)) { // if (ref == 39123631) { // a.debug = true; // } Way w = wayHashMap.get(ref); if (w == null) { System.out.println("Way http://www.openstreetmap.org/?way=" + ref + " was not found but referred as outline in "); System.out.println(" relation http://www.openstreetmap.org/?relation=" + r.id + " I'll ignore this relation"); continue rel; } Outline no = createOutline(w); if (no != null) { a.addOutline(no); if (firstWay == null) { if (w.triangles != null){ System.out.println("strange this outline is already triangulated ! maybe dublicate. I will ignore it"); System.out.println("Way http://www.openstreetmap.org/?way=" + ref); System.out.println("please see http://www.openstreetmap.org/?relation=" + r.id); continue rel; } firstWay = w; } else { removeWays.add(w); } } } for (Long ref : r.getWayIds(Member.ROLE_INNER)) { Way w = wayHashMap.get(ref); if (w == null) { System.out.println("Way http://www.openstreetmap.org/?way=" + ref + " was not found but referred as INNER in "); System.out.println(" relation http://www.openstreetmap.org/?relation=" + r.id + " I'll ignore this relation"); continue rel; } Outline no = createOutline(w); if (no != null) { a.addHole(no); if (w.getType(conf) < 1) { removeWays.add(w); } } } List<Triangle> areaTriangles = a.triangulate(); firstWay.triangles = areaTriangles; firstWay.recreatePath(); r.getTags().remove("type"); if (r.getTags().size() > 0){ firstWay.replaceTags(r); } triangles += areaTriangles.size(); areas += 1; i.remove(); } } for (Way w : removeWays) { parser.removeWay(w); } parser.resize(); }
private void convertAreasToTriangles() { HashMap<Long, Way> wayHashMap = parser.getWayHashMap(); ArrayList<Way> removeWays = new ArrayList<Way>(); Way firstWay = null; Iterator<Relation> i = parser.getRelations().iterator(); rel: while (i.hasNext()) { firstWay = null; Relation r = i.next(); // System.out.println("check relation " + r + "is valid()=" + r.isValid() ); if (r.isValid() && "multipolygon".equals(r.getAttribute("type"))) { if (r.getAttribute("admin_level") != null){ continue; } if (r.getWayIds(Member.ROLE_OUTER).size() == 0){ System.out.println("Relation has no outer member"); System.out.println(" see " + r.toUrl() + " I'll ignore this relation"); continue; } // System.out.println("Triangulate relation " + r.id); Area a = new Area(); // if (r.id == 405925 ){ // a.debug=true; // } for (Long ref : r.getWayIds(Member.ROLE_OUTER)) { // if (ref == 39123631) { // a.debug = true; // } Way w = wayHashMap.get(ref); if (w == null) { System.out.println("Way " + w.toUrl() + " was not found but referred as outline in "); System.out.println(" relation " + r.toUrl() + " I'll ignore this relation"); continue rel; } Outline no = createOutline(w); if (no != null) { a.addOutline(no); if (firstWay == null) { if (w.triangles != null){ System.out.println("strange this outline is already triangulated ! maybe dublicate. I will ignore it"); System.out.println("Way " + w.toUrl()); System.out.println("please see " + r.toUrl()); continue rel; } firstWay = w; } else { removeWays.add(w); } } } for (Long ref : r.getWayIds(Member.ROLE_INNER)) { Way w = wayHashMap.get(ref); if (w == null) { System.out.println("Way " + w.toUrl() + " was not found but referred as INNER in "); System.out.println(" relation "+ r.toUrl() + " I'll ignore this relation"); continue rel; } Outline no = createOutline(w); if (no != null) { a.addHole(no); if (w.getType(conf) < 1) { removeWays.add(w); } } } List<Triangle> areaTriangles = a.triangulate(); firstWay.triangles = areaTriangles; firstWay.recreatePath(); r.getTags().remove("type"); if (r.getTags().size() > 0){ firstWay.replaceTags(r); } triangles += areaTriangles.size(); areas += 1; i.remove(); } } for (Way w : removeWays) { parser.removeWay(w); } parser.resize(); }
diff --git a/src/main/java/me/iffa/bananaspace/config/SpaceConfigUpdater.java b/src/main/java/me/iffa/bananaspace/config/SpaceConfigUpdater.java index ff02551..7cb5681 100644 --- a/src/main/java/me/iffa/bananaspace/config/SpaceConfigUpdater.java +++ b/src/main/java/me/iffa/bananaspace/config/SpaceConfigUpdater.java @@ -1,119 +1,121 @@ // Package Declaration package me.iffa.bananaspace.config; // Java Imports import java.io.IOException; import java.util.logging.Level; // BananaSpace Imports import me.iffa.bananaspace.api.SpaceMessageHandler; import me.iffa.bananaspace.config.SpaceConfig.ConfigFile; // Bukkit Imports import org.bukkit.configuration.file.YamlConfiguration; /** * Converts old pre-v2 worlds into v2 IDs. * * @author iffa */ public class SpaceConfigUpdater { // Variables private static boolean hadToBeUpdated = false; /** * Checks if the configuration files had to be "fixed". * * @return True if had to be updated */ public static boolean wasUpdated() { return hadToBeUpdated; } /** * Checks if a config file needs updating to v2. * * @param configfile ConfigFile to check * * @return True if needs updating */ private static boolean needsUpdate(ConfigFile configfile) { if (SpaceConfig.getConfig(configfile).contains("worlds")) { try { for(String world : SpaceConfig.getConfig(configfile).getConfigurationSection("worlds").getKeys(false)){ if(SpaceConfig.getConfig(configfile).getConfigurationSection("worlds." + world).contains("generation")){ hadToBeUpdated = true; return true; } } } catch (NullPointerException ex) { return false; } } return false; } /** * Updates pre-v2 config files to be compatible with v2. This way the only thing the * user has to do to fix configs for v2 is actually update and run it. */ public static void updateConfigs() { if (!needsUpdate(ConfigFile.CONFIG)) { return; } // Variables SpaceMessageHandler.print(Level.INFO, "Starting to update configs for compatability with v2."); YamlConfiguration configFile = SpaceConfig.getConfig(ConfigFile.CONFIG); YamlConfiguration idsFile = SpaceConfig.getConfig(ConfigFile.IDS); for (String world : configFile.getConfigurationSection("worlds").getKeys(false)) { // Generation values for (String key : configFile.getConfigurationSection("worlds." + world + "." + "generation").getKeys(false)) { Object value = configFile.get("worlds." + world + ".generation." + key); idsFile.set("ids." + world + ".generation." + key, value); SpaceMessageHandler.debugPrint(Level.INFO, "Moved " + key + " of " + world + " to ids.yml with a value of " + value); } // Suit values for (String key : configFile.getConfigurationSection("worlds." + world + "." + "suit").getKeys(false)) { Object value = configFile.get("worlds." + world + ".suit." + key); idsFile.set("ids." + world + ".suit." + key, value); SpaceMessageHandler.debugPrint(Level.INFO, "Moved " + key + " of " + world + " to ids.yml with a value of " + value); } // Helmet values for (String key : configFile.getConfigurationSection("worlds." + world + "." + "helmet").getKeys(false)) { Object value = configFile.get("worlds." + world + ".helmet." + key); idsFile.set("ids." + world + ".helmet." + key, value); SpaceMessageHandler.debugPrint(Level.INFO, "Moved " + key + " of " + world + " to ids.yml with a value of " + value); } // Misc. values for (String key : configFile.getConfigurationSection("worlds." + world).getKeys(false)) { // So we don't make bad things happen. Skrillex (Y) if (key.equalsIgnoreCase("generation") || key.equalsIgnoreCase("suit") || key.equalsIgnoreCase("helmet")) { continue; } Object value = configFile.get("worlds." + world + "." + key); idsFile.set("ids." + world + "." + key, value); SpaceMessageHandler.debugPrint(Level.INFO, "Moved " + key + " of " + world + " to ids.yml with a value of " + value); } + // Removing the world from config.yml. + configFile.set("worlds." + world, null); SpaceMessageHandler.debugPrint(Level.INFO, "Removed " + world + " from config.yml."); } // Saving both files since converting is done. try { configFile.save(SpaceConfig.getConfigFile(ConfigFile.CONFIG)); idsFile.save(SpaceConfig.getConfigFile(ConfigFile.IDS)); SpaceMessageHandler.debugPrint(Level.INFO, "Saved changes to ids and config.yml."); } catch (IOException ex) { // In case of any error. SpaceMessageHandler.print(Level.SEVERE, "There was a problem converting configuration files to v2 format: " + ex.getMessage()); } // It was all done. SpaceMessageHandler.print(Level.INFO, "Your pre-v2 config.yml was succesfully converted to the new v2 format. Your worlds can now be found"); } /** * Constructor of SpaceConfigUpdater. */ private SpaceConfigUpdater() { } }
true
true
public static void updateConfigs() { if (!needsUpdate(ConfigFile.CONFIG)) { return; } // Variables SpaceMessageHandler.print(Level.INFO, "Starting to update configs for compatability with v2."); YamlConfiguration configFile = SpaceConfig.getConfig(ConfigFile.CONFIG); YamlConfiguration idsFile = SpaceConfig.getConfig(ConfigFile.IDS); for (String world : configFile.getConfigurationSection("worlds").getKeys(false)) { // Generation values for (String key : configFile.getConfigurationSection("worlds." + world + "." + "generation").getKeys(false)) { Object value = configFile.get("worlds." + world + ".generation." + key); idsFile.set("ids." + world + ".generation." + key, value); SpaceMessageHandler.debugPrint(Level.INFO, "Moved " + key + " of " + world + " to ids.yml with a value of " + value); } // Suit values for (String key : configFile.getConfigurationSection("worlds." + world + "." + "suit").getKeys(false)) { Object value = configFile.get("worlds." + world + ".suit." + key); idsFile.set("ids." + world + ".suit." + key, value); SpaceMessageHandler.debugPrint(Level.INFO, "Moved " + key + " of " + world + " to ids.yml with a value of " + value); } // Helmet values for (String key : configFile.getConfigurationSection("worlds." + world + "." + "helmet").getKeys(false)) { Object value = configFile.get("worlds." + world + ".helmet." + key); idsFile.set("ids." + world + ".helmet." + key, value); SpaceMessageHandler.debugPrint(Level.INFO, "Moved " + key + " of " + world + " to ids.yml with a value of " + value); } // Misc. values for (String key : configFile.getConfigurationSection("worlds." + world).getKeys(false)) { // So we don't make bad things happen. Skrillex (Y) if (key.equalsIgnoreCase("generation") || key.equalsIgnoreCase("suit") || key.equalsIgnoreCase("helmet")) { continue; } Object value = configFile.get("worlds." + world + "." + key); idsFile.set("ids." + world + "." + key, value); SpaceMessageHandler.debugPrint(Level.INFO, "Moved " + key + " of " + world + " to ids.yml with a value of " + value); } SpaceMessageHandler.debugPrint(Level.INFO, "Removed " + world + " from config.yml."); } // Saving both files since converting is done. try { configFile.save(SpaceConfig.getConfigFile(ConfigFile.CONFIG)); idsFile.save(SpaceConfig.getConfigFile(ConfigFile.IDS)); SpaceMessageHandler.debugPrint(Level.INFO, "Saved changes to ids and config.yml."); } catch (IOException ex) { // In case of any error. SpaceMessageHandler.print(Level.SEVERE, "There was a problem converting configuration files to v2 format: " + ex.getMessage()); } // It was all done. SpaceMessageHandler.print(Level.INFO, "Your pre-v2 config.yml was succesfully converted to the new v2 format. Your worlds can now be found"); }
public static void updateConfigs() { if (!needsUpdate(ConfigFile.CONFIG)) { return; } // Variables SpaceMessageHandler.print(Level.INFO, "Starting to update configs for compatability with v2."); YamlConfiguration configFile = SpaceConfig.getConfig(ConfigFile.CONFIG); YamlConfiguration idsFile = SpaceConfig.getConfig(ConfigFile.IDS); for (String world : configFile.getConfigurationSection("worlds").getKeys(false)) { // Generation values for (String key : configFile.getConfigurationSection("worlds." + world + "." + "generation").getKeys(false)) { Object value = configFile.get("worlds." + world + ".generation." + key); idsFile.set("ids." + world + ".generation." + key, value); SpaceMessageHandler.debugPrint(Level.INFO, "Moved " + key + " of " + world + " to ids.yml with a value of " + value); } // Suit values for (String key : configFile.getConfigurationSection("worlds." + world + "." + "suit").getKeys(false)) { Object value = configFile.get("worlds." + world + ".suit." + key); idsFile.set("ids." + world + ".suit." + key, value); SpaceMessageHandler.debugPrint(Level.INFO, "Moved " + key + " of " + world + " to ids.yml with a value of " + value); } // Helmet values for (String key : configFile.getConfigurationSection("worlds." + world + "." + "helmet").getKeys(false)) { Object value = configFile.get("worlds." + world + ".helmet." + key); idsFile.set("ids." + world + ".helmet." + key, value); SpaceMessageHandler.debugPrint(Level.INFO, "Moved " + key + " of " + world + " to ids.yml with a value of " + value); } // Misc. values for (String key : configFile.getConfigurationSection("worlds." + world).getKeys(false)) { // So we don't make bad things happen. Skrillex (Y) if (key.equalsIgnoreCase("generation") || key.equalsIgnoreCase("suit") || key.equalsIgnoreCase("helmet")) { continue; } Object value = configFile.get("worlds." + world + "." + key); idsFile.set("ids." + world + "." + key, value); SpaceMessageHandler.debugPrint(Level.INFO, "Moved " + key + " of " + world + " to ids.yml with a value of " + value); } // Removing the world from config.yml. configFile.set("worlds." + world, null); SpaceMessageHandler.debugPrint(Level.INFO, "Removed " + world + " from config.yml."); } // Saving both files since converting is done. try { configFile.save(SpaceConfig.getConfigFile(ConfigFile.CONFIG)); idsFile.save(SpaceConfig.getConfigFile(ConfigFile.IDS)); SpaceMessageHandler.debugPrint(Level.INFO, "Saved changes to ids and config.yml."); } catch (IOException ex) { // In case of any error. SpaceMessageHandler.print(Level.SEVERE, "There was a problem converting configuration files to v2 format: " + ex.getMessage()); } // It was all done. SpaceMessageHandler.print(Level.INFO, "Your pre-v2 config.yml was succesfully converted to the new v2 format. Your worlds can now be found"); }
diff --git a/dspace-stats/src/main/java/org/dspace/statistics/util/LocationUtils.java b/dspace-stats/src/main/java/org/dspace/statistics/util/LocationUtils.java index ae29658ae..bf1b18908 100644 --- a/dspace-stats/src/main/java/org/dspace/statistics/util/LocationUtils.java +++ b/dspace-stats/src/main/java/org/dspace/statistics/util/LocationUtils.java @@ -1,168 +1,168 @@ /** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.statistics.util; import java.io.IOException; import java.util.Locale; import java.util.MissingResourceException; import java.util.Properties; import java.util.ResourceBundle; import org.apache.log4j.Logger; import org.dspace.core.I18nUtil; /** * Mapping between Country codes, English Country names, * Continent Codes, and English Continent names * * @author kevinvandevelde at atmire.com * @author ben at atmire.com */ public class LocationUtils { private static final Logger logger = Logger.getLogger(LocationUtils.class); private static final Properties countryToContinent = new Properties(); private static final String CONTINENT_NAMES_BUNDLE = LocationUtils.class.getPackage().getName() + ".continent-names"; /** * Map DSpace continent codes onto ISO country codes. * * @param countryCode ISO 3166-1 alpha-2 country code. * @return DSpace 2-character code for continent containing that country, or * an error message string. */ static public String getContinentCode(String countryCode) { if (null == countryCode) { logger.error("Null country code"); return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-continent"); } if (countryToContinent.isEmpty()) try { countryToContinent.load(LocationUtils.class .getResourceAsStream("country-continent-codes.properties")); } catch (IOException e) { logger.error("Could not load country/continent map file", e); } String continent = countryToContinent.getProperty(countryCode); if (null == continent) { logger.error("Unknown country code " + countryCode); return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-continent"); } else return continent; } /** * Map DSpace continent codes onto default continent names. * * @param continentCode DSpace 2-character code for a continent. * @return Name of the continent in the default locale, or an error message * string. */ @Deprecated static public String getContinentName(String continentCode) { return getContinentName(continentCode, Locale.getDefault()); } /** * Map DSpace continent codes onto localized continent names. * * @param continentCode DSpace 2-character code for a continent. * @param locale The desired localization. * @return Localized name of the continent, or an error message string. */ static public String getContinentName(String continentCode, Locale locale) { ResourceBundle names; if (null == locale) locale = Locale.US; if (null == continentCode) { logger.error("Null continentCode"); return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-continent"); } try { names = ResourceBundle.getBundle(CONTINENT_NAMES_BUNDLE, locale); } catch (MissingResourceException e) { logger.error("Could not load continent code/name resource bundle", e); return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-continent"); } String name; try { name = names.getString(continentCode); } catch (MissingResourceException e) { - logger.error("No continent code " + continentCode + "in bundle " + logger.error("No continent code " + continentCode + " in bundle " + names.getLocale().getDisplayName()); return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-continent"); } return name; } /** * Map ISO country codes onto default country names. * * @param countryCode ISO 3166-1 alpha-2 country code. * @return Name of the country in the default locale, or an error message * string. */ @Deprecated static public String getCountryName(String countryCode) { return getCountryName(countryCode, Locale.getDefault()); } /** * Map ISO country codes onto localized country names. * * @param countryCode ISO 3166-1 alpha-2 country code. * @param locale Desired localization. * @return Localized name of the country, or an error message string. */ static public String getCountryName(String countryCode, Locale locale) { if (null == countryCode) return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-country"); Locale country = new Locale("EN", countryCode); String name = country.getDisplayCountry(locale); if (name.isEmpty()) return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-country"); else return name; } }
true
true
static public String getContinentName(String continentCode, Locale locale) { ResourceBundle names; if (null == locale) locale = Locale.US; if (null == continentCode) { logger.error("Null continentCode"); return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-continent"); } try { names = ResourceBundle.getBundle(CONTINENT_NAMES_BUNDLE, locale); } catch (MissingResourceException e) { logger.error("Could not load continent code/name resource bundle", e); return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-continent"); } String name; try { name = names.getString(continentCode); } catch (MissingResourceException e) { logger.error("No continent code " + continentCode + "in bundle " + names.getLocale().getDisplayName()); return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-continent"); } return name; }
static public String getContinentName(String continentCode, Locale locale) { ResourceBundle names; if (null == locale) locale = Locale.US; if (null == continentCode) { logger.error("Null continentCode"); return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-continent"); } try { names = ResourceBundle.getBundle(CONTINENT_NAMES_BUNDLE, locale); } catch (MissingResourceException e) { logger.error("Could not load continent code/name resource bundle", e); return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-continent"); } String name; try { name = names.getString(continentCode); } catch (MissingResourceException e) { logger.error("No continent code " + continentCode + " in bundle " + names.getLocale().getDisplayName()); return I18nUtil .getMessage("org.dspace.statistics.util.LocationUtils.unknown-continent"); } return name; }
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/viewArtifacts/Navigation.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/viewArtifacts/Navigation.java index fa6ad8073..ff4ba4eb6 100644 --- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/viewArtifacts/Navigation.java +++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/viewArtifacts/Navigation.java @@ -1,150 +1,148 @@ /** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.viewArtifacts; import org.apache.cocoon.caching.CacheableProcessingComponent; import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; import org.apache.cocoon.util.HashUtil; import org.apache.excalibur.source.SourceValidity; import org.apache.excalibur.source.impl.validity.NOPValidity; import org.dspace.app.util.Util; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.HandleUtil; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Options; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.core.ConfigurationManager; import org.xml.sax.SAXException; import java.io.IOException; import java.io.Serializable; import java.sql.SQLException; /** * This transform applies the basic navigational links that should be available * on all pages generated by DSpace. * * @author Scott Phillips * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) * @author Ben Bosman (ben at atmire dot com) */ public class Navigation extends AbstractDSpaceTransformer implements CacheableProcessingComponent { /** * Generate the unique caching key. * This key must be unique inside the space of this component. */ public Serializable getKey() { try { Request request = ObjectModelHelper.getRequest(objectModel); String key = request.getScheme() + request.getServerName() + request.getServerPort() + request.getSitemapURI() + request.getQueryString(); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (dso != null) { key += "-" + dso.getHandle(); } return HashUtil.hash(key); } catch (SQLException sqle) { // Ignore all errors and just return that the component is not cachable. return "0"; } } /** * Generate the cache validity object. * * The cache is always valid. */ public SourceValidity getValidity() { return NOPValidity.SHARED_INSTANCE; } public void addOptions(Options options) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { /* Create skeleton menu structure to ensure consistent order between aspects, * even if they are never used */ options.addList("browse"); options.addList("account"); options.addList("context"); options.addList("administrative"); } /** * Ensure that the context path is added to the page meta. */ public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { // FIXME: I don't think these should be set here, but they're needed and I'm // not sure where else it could go. Perhaps the linkResolver? Request request = ObjectModelHelper.getRequest(objectModel); pageMeta.addMetadata("contextPath").addContent(contextPath); pageMeta.addMetadata("request","queryString").addContent(request.getQueryString()); pageMeta.addMetadata("request","scheme").addContent(request.getScheme()); pageMeta.addMetadata("request","serverPort").addContent(request.getServerPort()); pageMeta.addMetadata("request","serverName").addContent(request.getServerName()); pageMeta.addMetadata("request","URI").addContent(request.getSitemapURI()); String dspaceVersion = Util.getSourceVersion(); if (dspaceVersion != null) { pageMeta.addMetadata("dspace","version").addContent(dspaceVersion); } String analyticsKey = ConfigurationManager.getProperty("xmlui.google.analytics.key"); if (analyticsKey != null && analyticsKey.length() > 0) { analyticsKey = analyticsKey.trim(); pageMeta.addMetadata("google","analytics").addContent(analyticsKey); } // add metadata for OpenSearch auto-discovery links if enabled if (ConfigurationManager.getBooleanProperty("websvc.opensearch.autolink")) { - pageMeta.addMetadata("opensearch", "shortName").addContent( - ConfigurationManager.getProperty("websvc.opensearch.shortname")); - pageMeta.addMetadata("opensearch", "context").addContent( - ConfigurationManager.getProperty("websvc.opensearch.svccontext")); + pageMeta.addMetadata("opensearch", "shortName").addContent( ConfigurationManager.getProperty("websvc.opensearch.shortname") ); + pageMeta.addMetadata("opensearch", "autolink").addContent( "open-search/description.xml" ); } pageMeta.addMetadata("page","contactURL").addContent(contextPath + "/contact"); pageMeta.addMetadata("page","feedbackURL").addContent(contextPath + "/feedback"); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (dso != null) { if (dso instanceof Item) { pageMeta.addMetadata("focus","object").addContent("hdl:"+dso.getHandle()); this.getObjectManager().manageObject(dso); dso = ((Item) dso).getOwningCollection(); } if (dso instanceof Collection || dso instanceof Community) { pageMeta.addMetadata("focus","container").addContent("hdl:"+dso.getHandle()); this.getObjectManager().manageObject(dso); } } } }
true
true
public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { // FIXME: I don't think these should be set here, but they're needed and I'm // not sure where else it could go. Perhaps the linkResolver? Request request = ObjectModelHelper.getRequest(objectModel); pageMeta.addMetadata("contextPath").addContent(contextPath); pageMeta.addMetadata("request","queryString").addContent(request.getQueryString()); pageMeta.addMetadata("request","scheme").addContent(request.getScheme()); pageMeta.addMetadata("request","serverPort").addContent(request.getServerPort()); pageMeta.addMetadata("request","serverName").addContent(request.getServerName()); pageMeta.addMetadata("request","URI").addContent(request.getSitemapURI()); String dspaceVersion = Util.getSourceVersion(); if (dspaceVersion != null) { pageMeta.addMetadata("dspace","version").addContent(dspaceVersion); } String analyticsKey = ConfigurationManager.getProperty("xmlui.google.analytics.key"); if (analyticsKey != null && analyticsKey.length() > 0) { analyticsKey = analyticsKey.trim(); pageMeta.addMetadata("google","analytics").addContent(analyticsKey); } // add metadata for OpenSearch auto-discovery links if enabled if (ConfigurationManager.getBooleanProperty("websvc.opensearch.autolink")) { pageMeta.addMetadata("opensearch", "shortName").addContent( ConfigurationManager.getProperty("websvc.opensearch.shortname")); pageMeta.addMetadata("opensearch", "context").addContent( ConfigurationManager.getProperty("websvc.opensearch.svccontext")); } pageMeta.addMetadata("page","contactURL").addContent(contextPath + "/contact"); pageMeta.addMetadata("page","feedbackURL").addContent(contextPath + "/feedback"); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (dso != null) { if (dso instanceof Item) { pageMeta.addMetadata("focus","object").addContent("hdl:"+dso.getHandle()); this.getObjectManager().manageObject(dso); dso = ((Item) dso).getOwningCollection(); } if (dso instanceof Collection || dso instanceof Community) { pageMeta.addMetadata("focus","container").addContent("hdl:"+dso.getHandle()); this.getObjectManager().manageObject(dso); } } }
public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { // FIXME: I don't think these should be set here, but they're needed and I'm // not sure where else it could go. Perhaps the linkResolver? Request request = ObjectModelHelper.getRequest(objectModel); pageMeta.addMetadata("contextPath").addContent(contextPath); pageMeta.addMetadata("request","queryString").addContent(request.getQueryString()); pageMeta.addMetadata("request","scheme").addContent(request.getScheme()); pageMeta.addMetadata("request","serverPort").addContent(request.getServerPort()); pageMeta.addMetadata("request","serverName").addContent(request.getServerName()); pageMeta.addMetadata("request","URI").addContent(request.getSitemapURI()); String dspaceVersion = Util.getSourceVersion(); if (dspaceVersion != null) { pageMeta.addMetadata("dspace","version").addContent(dspaceVersion); } String analyticsKey = ConfigurationManager.getProperty("xmlui.google.analytics.key"); if (analyticsKey != null && analyticsKey.length() > 0) { analyticsKey = analyticsKey.trim(); pageMeta.addMetadata("google","analytics").addContent(analyticsKey); } // add metadata for OpenSearch auto-discovery links if enabled if (ConfigurationManager.getBooleanProperty("websvc.opensearch.autolink")) { pageMeta.addMetadata("opensearch", "shortName").addContent( ConfigurationManager.getProperty("websvc.opensearch.shortname") ); pageMeta.addMetadata("opensearch", "autolink").addContent( "open-search/description.xml" ); } pageMeta.addMetadata("page","contactURL").addContent(contextPath + "/contact"); pageMeta.addMetadata("page","feedbackURL").addContent(contextPath + "/feedback"); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (dso != null) { if (dso instanceof Item) { pageMeta.addMetadata("focus","object").addContent("hdl:"+dso.getHandle()); this.getObjectManager().manageObject(dso); dso = ((Item) dso).getOwningCollection(); } if (dso instanceof Collection || dso instanceof Community) { pageMeta.addMetadata("focus","container").addContent("hdl:"+dso.getHandle()); this.getObjectManager().manageObject(dso); } } }
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/highlight/HighlighterParseElement.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/highlight/HighlighterParseElement.java index 4725a20b364..9c3f54291ec 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/highlight/HighlighterParseElement.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/highlight/HighlighterParseElement.java @@ -1,183 +1,183 @@ /* * Licensed to Elastic Search and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Elastic Search 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.elasticsearch.search.highlight; import org.elasticsearch.common.collect.Lists; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchParseException; import org.elasticsearch.search.internal.SearchContext; import java.util.List; import static org.elasticsearch.common.collect.Lists.*; /** * <pre> * highlight : { * tags_schema : "styled", * pre_tags : ["tag1", "tag2"], * post_tags : ["tag1", "tag2"], * order : "score", * highlight_filter : true, * fields : { * field1 : { }, * field2 : { fragment_size : 100, number_of_fragments : 2 }, * field3 : { number_of_fragments : 5, order : "simple", tags_schema : "styled" }, * field4 : { number_of_fragments: 0, pre_tags : ["openingTagA", "openingTagB"], post_tags : ["closingTag"] } * } * } * </pre> * * @author kimchy (shay.banon) */ public class HighlighterParseElement implements SearchParseElement { private static final String[] DEFAULT_PRE_TAGS = new String[]{"<em>"}; private static final String[] DEFAULT_POST_TAGS = new String[]{"</em>"}; private static final String[] STYLED_PRE_TAG = { "<em class=\"hlt1\">", "<em class=\"hlt2\">", "<em class=\"hlt3\">", "<em class=\"hlt4\">", "<em class=\"hlt5\">", "<em class=\"hlt6\">", "<em class=\"hlt7\">", "<em class=\"hlt8\">", "<em class=\"hlt9\">", "<em class=\"hlt10\">" }; private static final String[] STYLED_POST_TAGS = {"</em>"}; @Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token; String topLevelFieldName = null; List<SearchContextHighlight.Field> fields = newArrayList(); String[] globalPreTags = DEFAULT_PRE_TAGS; String[] globalPostTags = DEFAULT_POST_TAGS; boolean globalScoreOrdered = false; boolean globalHighlightFilter = true; int globalFragmentSize = 100; int globalNumOfFragments = 5; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { topLevelFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if ("pre_tags".equals(topLevelFieldName) || "preTags".equals(topLevelFieldName)) { List<String> preTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { preTagsList.add(parser.text()); } globalPreTags = preTagsList.toArray(new String[preTagsList.size()]); } else if ("post_tags".equals(topLevelFieldName) || "postTags".equals(topLevelFieldName)) { List<String> postTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { postTagsList.add(parser.text()); } globalPostTags = postTagsList.toArray(new String[postTagsList.size()]); } } else if (token.isValue()) { if ("order".equals(topLevelFieldName)) { globalScoreOrdered = "score".equals(parser.text()); } else if ("tags_schema".equals(topLevelFieldName) || "tagsSchema".equals(topLevelFieldName)) { String schema = parser.text(); if ("styled".equals(schema)) { globalPreTags = STYLED_PRE_TAG; globalPostTags = STYLED_POST_TAGS; } } else if ("highlight_filter".equals(topLevelFieldName) || "highlightFilter".equals(topLevelFieldName)) { globalHighlightFilter = parser.booleanValue(); } else if ("fragment_size".equals(topLevelFieldName) || "fragmentSize".equals(topLevelFieldName)) { globalFragmentSize = parser.intValue(); } else if ("number_of_fragments".equals(topLevelFieldName) || "numberOfFragments".equals(topLevelFieldName)) { globalNumOfFragments = parser.intValue(); } } else if (token == XContentParser.Token.START_OBJECT) { if ("fields".equals(topLevelFieldName)) { String highlightFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { highlightFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { SearchContextHighlight.Field field = new SearchContextHighlight.Field(highlightFieldName); String fieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { fieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if ("pre_tags".equals(fieldName) || "preTags".equals(fieldName)) { List<String> preTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { preTagsList.add(parser.text()); } field.preTags(preTagsList.toArray(new String[preTagsList.size()])); } else if ("post_tags".equals(fieldName) || "postTags".equals(fieldName)) { List<String> postTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { postTagsList.add(parser.text()); } field.postTags(postTagsList.toArray(new String[postTagsList.size()])); } } else if (token.isValue()) { if ("fragment_size".equals(fieldName) || "fragmentSize".equals(fieldName)) { field.fragmentCharSize(parser.intValue()); } else if ("number_of_fragments".equals(fieldName) || "numberOfFragments".equals(fieldName)) { field.numberOfFragments(parser.intValue()); } else if ("fragment_offset".equals(fieldName) || "fragmentOffset".equals(fieldName)) { field.fragmentOffset(parser.intValue()); } else if ("highlight_filter".equals(fieldName) || "highlightFilter".equals(fieldName)) { field.highlightFilter(parser.booleanValue()); - } else if ("score".equals(fieldName)) { + } else if ("order".equals(fieldName)) { field.scoreOrdered("score".equals(parser.text())); } } } fields.add(field); } } } } } if (globalPreTags != null && globalPostTags == null) { throw new SearchParseException(context, "Highlighter global preTags are set, but global postTags are not set"); } // now, go over and fill all fields with default values from the global state for (SearchContextHighlight.Field field : fields) { if (field.preTags() == null) { field.preTags(globalPreTags); } if (field.postTags() == null) { field.postTags(globalPostTags); } if (field.highlightFilter() == null) { field.highlightFilter(globalHighlightFilter); } if (field.scoreOrdered() == null) { field.scoreOrdered(globalScoreOrdered); } if (field.fragmentCharSize() == -1) { field.fragmentCharSize(globalFragmentSize); } if (field.numberOfFragments() == -1) { field.numberOfFragments(globalNumOfFragments); } } context.highlight(new SearchContextHighlight(fields)); } }
true
true
@Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token; String topLevelFieldName = null; List<SearchContextHighlight.Field> fields = newArrayList(); String[] globalPreTags = DEFAULT_PRE_TAGS; String[] globalPostTags = DEFAULT_POST_TAGS; boolean globalScoreOrdered = false; boolean globalHighlightFilter = true; int globalFragmentSize = 100; int globalNumOfFragments = 5; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { topLevelFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if ("pre_tags".equals(topLevelFieldName) || "preTags".equals(topLevelFieldName)) { List<String> preTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { preTagsList.add(parser.text()); } globalPreTags = preTagsList.toArray(new String[preTagsList.size()]); } else if ("post_tags".equals(topLevelFieldName) || "postTags".equals(topLevelFieldName)) { List<String> postTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { postTagsList.add(parser.text()); } globalPostTags = postTagsList.toArray(new String[postTagsList.size()]); } } else if (token.isValue()) { if ("order".equals(topLevelFieldName)) { globalScoreOrdered = "score".equals(parser.text()); } else if ("tags_schema".equals(topLevelFieldName) || "tagsSchema".equals(topLevelFieldName)) { String schema = parser.text(); if ("styled".equals(schema)) { globalPreTags = STYLED_PRE_TAG; globalPostTags = STYLED_POST_TAGS; } } else if ("highlight_filter".equals(topLevelFieldName) || "highlightFilter".equals(topLevelFieldName)) { globalHighlightFilter = parser.booleanValue(); } else if ("fragment_size".equals(topLevelFieldName) || "fragmentSize".equals(topLevelFieldName)) { globalFragmentSize = parser.intValue(); } else if ("number_of_fragments".equals(topLevelFieldName) || "numberOfFragments".equals(topLevelFieldName)) { globalNumOfFragments = parser.intValue(); } } else if (token == XContentParser.Token.START_OBJECT) { if ("fields".equals(topLevelFieldName)) { String highlightFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { highlightFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { SearchContextHighlight.Field field = new SearchContextHighlight.Field(highlightFieldName); String fieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { fieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if ("pre_tags".equals(fieldName) || "preTags".equals(fieldName)) { List<String> preTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { preTagsList.add(parser.text()); } field.preTags(preTagsList.toArray(new String[preTagsList.size()])); } else if ("post_tags".equals(fieldName) || "postTags".equals(fieldName)) { List<String> postTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { postTagsList.add(parser.text()); } field.postTags(postTagsList.toArray(new String[postTagsList.size()])); } } else if (token.isValue()) { if ("fragment_size".equals(fieldName) || "fragmentSize".equals(fieldName)) { field.fragmentCharSize(parser.intValue()); } else if ("number_of_fragments".equals(fieldName) || "numberOfFragments".equals(fieldName)) { field.numberOfFragments(parser.intValue()); } else if ("fragment_offset".equals(fieldName) || "fragmentOffset".equals(fieldName)) { field.fragmentOffset(parser.intValue()); } else if ("highlight_filter".equals(fieldName) || "highlightFilter".equals(fieldName)) { field.highlightFilter(parser.booleanValue()); } else if ("score".equals(fieldName)) { field.scoreOrdered("score".equals(parser.text())); } } } fields.add(field); } } } } } if (globalPreTags != null && globalPostTags == null) { throw new SearchParseException(context, "Highlighter global preTags are set, but global postTags are not set"); } // now, go over and fill all fields with default values from the global state for (SearchContextHighlight.Field field : fields) { if (field.preTags() == null) { field.preTags(globalPreTags); } if (field.postTags() == null) { field.postTags(globalPostTags); } if (field.highlightFilter() == null) { field.highlightFilter(globalHighlightFilter); } if (field.scoreOrdered() == null) { field.scoreOrdered(globalScoreOrdered); } if (field.fragmentCharSize() == -1) { field.fragmentCharSize(globalFragmentSize); } if (field.numberOfFragments() == -1) { field.numberOfFragments(globalNumOfFragments); } } context.highlight(new SearchContextHighlight(fields)); }
@Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token; String topLevelFieldName = null; List<SearchContextHighlight.Field> fields = newArrayList(); String[] globalPreTags = DEFAULT_PRE_TAGS; String[] globalPostTags = DEFAULT_POST_TAGS; boolean globalScoreOrdered = false; boolean globalHighlightFilter = true; int globalFragmentSize = 100; int globalNumOfFragments = 5; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { topLevelFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if ("pre_tags".equals(topLevelFieldName) || "preTags".equals(topLevelFieldName)) { List<String> preTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { preTagsList.add(parser.text()); } globalPreTags = preTagsList.toArray(new String[preTagsList.size()]); } else if ("post_tags".equals(topLevelFieldName) || "postTags".equals(topLevelFieldName)) { List<String> postTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { postTagsList.add(parser.text()); } globalPostTags = postTagsList.toArray(new String[postTagsList.size()]); } } else if (token.isValue()) { if ("order".equals(topLevelFieldName)) { globalScoreOrdered = "score".equals(parser.text()); } else if ("tags_schema".equals(topLevelFieldName) || "tagsSchema".equals(topLevelFieldName)) { String schema = parser.text(); if ("styled".equals(schema)) { globalPreTags = STYLED_PRE_TAG; globalPostTags = STYLED_POST_TAGS; } } else if ("highlight_filter".equals(topLevelFieldName) || "highlightFilter".equals(topLevelFieldName)) { globalHighlightFilter = parser.booleanValue(); } else if ("fragment_size".equals(topLevelFieldName) || "fragmentSize".equals(topLevelFieldName)) { globalFragmentSize = parser.intValue(); } else if ("number_of_fragments".equals(topLevelFieldName) || "numberOfFragments".equals(topLevelFieldName)) { globalNumOfFragments = parser.intValue(); } } else if (token == XContentParser.Token.START_OBJECT) { if ("fields".equals(topLevelFieldName)) { String highlightFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { highlightFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { SearchContextHighlight.Field field = new SearchContextHighlight.Field(highlightFieldName); String fieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { fieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if ("pre_tags".equals(fieldName) || "preTags".equals(fieldName)) { List<String> preTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { preTagsList.add(parser.text()); } field.preTags(preTagsList.toArray(new String[preTagsList.size()])); } else if ("post_tags".equals(fieldName) || "postTags".equals(fieldName)) { List<String> postTagsList = Lists.newArrayList(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { postTagsList.add(parser.text()); } field.postTags(postTagsList.toArray(new String[postTagsList.size()])); } } else if (token.isValue()) { if ("fragment_size".equals(fieldName) || "fragmentSize".equals(fieldName)) { field.fragmentCharSize(parser.intValue()); } else if ("number_of_fragments".equals(fieldName) || "numberOfFragments".equals(fieldName)) { field.numberOfFragments(parser.intValue()); } else if ("fragment_offset".equals(fieldName) || "fragmentOffset".equals(fieldName)) { field.fragmentOffset(parser.intValue()); } else if ("highlight_filter".equals(fieldName) || "highlightFilter".equals(fieldName)) { field.highlightFilter(parser.booleanValue()); } else if ("order".equals(fieldName)) { field.scoreOrdered("score".equals(parser.text())); } } } fields.add(field); } } } } } if (globalPreTags != null && globalPostTags == null) { throw new SearchParseException(context, "Highlighter global preTags are set, but global postTags are not set"); } // now, go over and fill all fields with default values from the global state for (SearchContextHighlight.Field field : fields) { if (field.preTags() == null) { field.preTags(globalPreTags); } if (field.postTags() == null) { field.postTags(globalPostTags); } if (field.highlightFilter() == null) { field.highlightFilter(globalHighlightFilter); } if (field.scoreOrdered() == null) { field.scoreOrdered(globalScoreOrdered); } if (field.fragmentCharSize() == -1) { field.fragmentCharSize(globalFragmentSize); } if (field.numberOfFragments() == -1) { field.numberOfFragments(globalNumOfFragments); } } context.highlight(new SearchContextHighlight(fields)); }
diff --git a/src/main/java/org/jboss/forge/scaffold/spring/metawidget/widgetbuilder/ReadOnlyEntityWidgetBuilder.java b/src/main/java/org/jboss/forge/scaffold/spring/metawidget/widgetbuilder/ReadOnlyEntityWidgetBuilder.java index 47dc966..6ff31de 100644 --- a/src/main/java/org/jboss/forge/scaffold/spring/metawidget/widgetbuilder/ReadOnlyEntityWidgetBuilder.java +++ b/src/main/java/org/jboss/forge/scaffold/spring/metawidget/widgetbuilder/ReadOnlyEntityWidgetBuilder.java @@ -1,49 +1,49 @@ package org.jboss.forge.scaffold.spring.metawidget.widgetbuilder; import static org.metawidget.inspector.InspectionResultConstants.*; import static org.jboss.forge.scaffold.spring.metawidget.inspector.ForgeInspectionResultConstants.*; import java.util.Collection; import java.util.Map; import org.metawidget.statically.StaticXmlMetawidget; import org.metawidget.statically.StaticXmlStub; import org.metawidget.statically.StaticXmlWidget; import org.metawidget.statically.jsp.widgetbuilder.CoreOut; import org.metawidget.statically.jsp.widgetbuilder.ReadOnlyWidgetBuilder; import org.metawidget.util.WidgetBuilderUtils; public class ReadOnlyEntityWidgetBuilder extends ReadOnlyWidgetBuilder { @Override public StaticXmlWidget buildWidget(String elementName, Map<String, String> attributes, StaticXmlMetawidget metawidget) { StaticXmlWidget widget = super.buildWidget(elementName, attributes, metawidget); Class<?> clazz = WidgetBuilderUtils.getActualClassOrType(attributes, null); if (TRUE.equals(attributes.get(N_TO_MANY)) || attributes.containsKey(INVERSE_RELATIONSHIP)) { return new StaticXmlStub(); } if (clazz != null && Collection.class.isAssignableFrom(clazz)) { return null; } - if (widget == null) + if (widget == null && WidgetBuilderUtils.isReadOnly(attributes)) { if (attributes.get(NAME) != null) { return new CoreOut(); } else { return null; } } return widget; } }
true
true
public StaticXmlWidget buildWidget(String elementName, Map<String, String> attributes, StaticXmlMetawidget metawidget) { StaticXmlWidget widget = super.buildWidget(elementName, attributes, metawidget); Class<?> clazz = WidgetBuilderUtils.getActualClassOrType(attributes, null); if (TRUE.equals(attributes.get(N_TO_MANY)) || attributes.containsKey(INVERSE_RELATIONSHIP)) { return new StaticXmlStub(); } if (clazz != null && Collection.class.isAssignableFrom(clazz)) { return null; } if (widget == null) { if (attributes.get(NAME) != null) { return new CoreOut(); } else { return null; } } return widget; }
public StaticXmlWidget buildWidget(String elementName, Map<String, String> attributes, StaticXmlMetawidget metawidget) { StaticXmlWidget widget = super.buildWidget(elementName, attributes, metawidget); Class<?> clazz = WidgetBuilderUtils.getActualClassOrType(attributes, null); if (TRUE.equals(attributes.get(N_TO_MANY)) || attributes.containsKey(INVERSE_RELATIONSHIP)) { return new StaticXmlStub(); } if (clazz != null && Collection.class.isAssignableFrom(clazz)) { return null; } if (widget == null && WidgetBuilderUtils.isReadOnly(attributes)) { if (attributes.get(NAME) != null) { return new CoreOut(); } else { return null; } } return widget; }
diff --git a/bundles/P2P/src/main/java/org/paxle/p2p/services/search/impl/SearchClientImpl.java b/bundles/P2P/src/main/java/org/paxle/p2p/services/search/impl/SearchClientImpl.java index 65217c28..9487e765 100644 --- a/bundles/P2P/src/main/java/org/paxle/p2p/services/search/impl/SearchClientImpl.java +++ b/bundles/P2P/src/main/java/org/paxle/p2p/services/search/impl/SearchClientImpl.java @@ -1,284 +1,284 @@ package org.paxle.p2p.services.search.impl; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import net.jxta.discovery.DiscoveryService; import net.jxta.document.Advertisement; import net.jxta.document.AdvertisementFactory; import net.jxta.endpoint.Message; import net.jxta.endpoint.MessageElement; import net.jxta.endpoint.StringMessageElement; import net.jxta.id.ID; import net.jxta.id.IDFactory; import net.jxta.pipe.OutputPipe; import net.jxta.pipe.PipeID; import net.jxta.pipe.PipeService; import net.jxta.protocol.ModuleSpecAdvertisement; import net.jxta.protocol.PipeAdvertisement; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.paxle.core.doc.IIndexerDocument; import org.paxle.core.doc.IndexerDocument; import org.paxle.p2p.impl.P2PManager; import org.paxle.p2p.services.IService; import org.paxle.p2p.services.impl.AServiceClient; import org.paxle.p2p.services.search.ISearchClient; import org.paxle.se.index.IFieldManager; import org.paxle.se.query.IQueryFactory; import org.paxle.se.query.tokens.AToken; import org.paxle.se.search.ISearchProvider; public class SearchClientImpl extends AServiceClient implements ISearchClient, ISearchProvider { /** * A map to hold the received results */ private final HashMap<Integer, List<Message>> resultMap = new HashMap<Integer, List<Message>>(); private IFieldManager fieldManager = null; private SearchServerImpl searchServiceServer = null; private final SearchQueryTokenFactory queryFactory = new SearchQueryTokenFactory(); public SearchClientImpl(P2PManager p2pManager, IFieldManager fieldManager, SearchServerImpl searchServiceServer) { super(p2pManager); this.fieldManager = fieldManager; this.searchServiceServer = searchServiceServer; } /** * {@inheritDoc} */ @Override protected PipeAdvertisement createPipeAdvertisement() { // create ID for the pipe // TODO: do we need a new ID each time? PipeID pipeID = IDFactory.newPipeID(this.pg.getPeerGroupID()); // create a new pipe advertisement and initialize it PipeAdvertisement pipeAdv = (PipeAdvertisement)AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType()); pipeAdv.setPipeID(pipeID); pipeAdv.setType(PipeService.UnicastType); pipeAdv.setName("Paxle:SearchService:ResponsePipe"); pipeAdv.setDescription("Paxle Search Service - Response queue"); return pipeAdv; } /** * Function to process the response that was received for the service request message * that was sent by {@link #remoteSearch(String)} * * {@inheritDoc} */ @Override protected void processResponse(Message respMsg) { try { // TODO Auto-generated method stub // TODO: extract the result // getting the search query string MessageElement query = respMsg.getMessageElement(SearchServiceConstants.REQ_ID); Integer reqNr = Integer.valueOf(new String(query.getBytes(false),"UTF-8")); System.out.println(String.format("ReqNr: %d",reqNr)); List<Message> resultList = null; synchronized (this.resultMap) { if (!this.resultMap.containsKey(reqNr)) { this.logger.warn("Unknown requestID: " + reqNr); return; } else { resultList = this.resultMap.get(reqNr); } } synchronized (resultList) { resultList.add(respMsg); } // insert it into the result queue } catch (Exception e) { e.printStackTrace(); } } protected Message createRequestMessage(String query, int maxResults, long timeout) { Message reqMessage = super.createRequestMessage(); // append the search parameters reqMessage.addMessageElement(null, new StringMessageElement(SearchServiceConstants.REQ_QUERY, query, null)); reqMessage.addMessageElement(null, new StringMessageElement(SearchServiceConstants.REQ_MAX_RESULTS, Integer.toString(maxResults), null)); reqMessage.addMessageElement(null, new StringMessageElement(SearchServiceConstants.REQ_TIMEOUT, Long.toString(timeout), null)); // add entry into the resultMap synchronized (this.resultMap) { this.resultMap.put(Integer.valueOf(reqMessage.getMessageNumber()), new ArrayList<Message>()); } return reqMessage; } protected void sendRequestMessage(Message reqMessage) throws IOException { PipeAdvertisement otherPeerPipeAdv = null; Enumeration<Advertisement> advs = this.pgDiscoveryService.getLocalAdvertisements(DiscoveryService.ADV, "Name", SearchServiceConstants.SERVICE_MOD_SPEC_NAME); if (advs != null) { while (advs.hasMoreElements()) { Advertisement adv = advs.nextElement(); System.out.println(adv.toString()); if (adv instanceof ModuleSpecAdvertisement) { try { // FIXME: does not work! getting the pipe adv of the other peer otherPeerPipeAdv = ((ModuleSpecAdvertisement)adv).getPipeAdvertisement(); if (this.searchServiceServer != null && this.searchServiceServer.getPipeAdvertisement() != null) { ID otherPeerPipeID = otherPeerPipeAdv.getID(); ID ownPeerPipeID = this.searchServiceServer.getPipeAdvertisement().getPipeID(); if (otherPeerPipeID.equals(ownPeerPipeID)) { this.logger.debug("Found our own peer. Skipping peer ..."); break; } } // create an output pipe to send the request OutputPipe outputPipe = this.pgPipeService.createOutputPipe(otherPeerPipeAdv, 10000); // send the message to the service pipe boolean success = outputPipe.send(reqMessage); if (!success) { // TODO: what to do in this case. Just retry? } this.sentMsgCount++; this.sentBytes += reqMessage.getByteLength(); outputPipe.close(); } catch (IOException ioe) { // unable to connect to the remote peer this.pgDiscoveryService.flushAdvertisement(otherPeerPipeAdv); } } } } } @SuppressWarnings("unchecked") protected void extractResult(Message reqMessage, List<IIndexerDocument> results) { List<Message> messageList = null; synchronized (this.resultMap) { if (!this.resultMap.containsKey(Integer.valueOf(reqMessage.getMessageNumber()))) { this.logger.warn("Unknown requestID: " + reqMessage.getMessageNumber()); - messageList = Collections.EMPTY_LIST; + messageList = Collections.emptyList(); } else { // remove the request from the result-list messageList = this.resultMap.remove(Integer.valueOf(reqMessage.getMessageNumber())); } } for (Message msg : messageList) { try { MessageElement resultListElement = msg.getMessageElement(SearchServiceConstants.RESP_RESULT); SAXReader reader = new SAXReader(); Document xmlDoc = reader.read(resultListElement.getStream()); Element xmlRoot = xmlDoc.getRootElement(); // iterate through child elements of root for (Iterator<Element> i = xmlRoot.elementIterator(SearchServiceConstants.RESULT_ENTRY); i.hasNext(); ) { Element resultElement = i.next(); for (Iterator<Element> j = resultElement.elementIterator(SearchServiceConstants.RESULT_ENTRY_ITEM); j.hasNext(); ) { Element resultItemElement = j.next(); IndexerDocument indexerDoc = new IndexerDocument(); for (Iterator<Element> k = resultItemElement.elementIterator(); k.hasNext(); ) { Element resultItemFieldElement = k.next(); String fieldName = resultItemFieldElement.getName(); String fieldValue = resultItemFieldElement.getText(); final org.paxle.core.doc.Field<?> pfield = this.fieldManager.get(fieldName); if (pfield != null) { indexerDoc.put(pfield, fieldValue); } } results.add(indexerDoc); } } } catch (Exception e) { e.printStackTrace(); } } } /** * @see ISearchClient#remoteSearch(String, int, long) */ public List<IIndexerDocument> remoteSearch(String query, int maxResults, long timeout) throws IOException, InterruptedException { List<IIndexerDocument> results = new ArrayList<IIndexerDocument>(); this.search(query, results, maxResults, timeout); return results; } /** * @see ISearchProvider#search(String, List, int, long) */ public void search(AToken request, List<IIndexerDocument> results, int maxCount, long timeout) throws IOException, InterruptedException { search(IQueryFactory.transformToken(request, queryFactory), results, maxCount, timeout); } public void search(String query, List<IIndexerDocument> results, int maxResults, long timeout) throws IOException, InterruptedException { try { /* ================================================================ * SEND REQUEST * ================================================================ */ /* ---------------------------------------------------------------- * Discover Service * ---------------------------------------------------------------- */ this.pgDiscoveryService.getRemoteAdvertisements(null, DiscoveryService.ADV, "Name", SearchServiceConstants.SERVICE_MOD_SPEC_NAME ,10); /* ---------------------------------------------------------------- * build the request message * ---------------------------------------------------------------- */ Message reqMessage = this.createRequestMessage(query, maxResults, timeout); // wait a few seconds // TODO: change this Thread.sleep(3000); /* ---------------------------------------------------------------- * Connect to other peers * ---------------------------------------------------------------- */ long reqStart = System.currentTimeMillis(); this.sendRequestMessage(reqMessage); /* ================================================================ * WAIT FOR RESPONSE * ================================================================ */ long timeToWait = Math.max(timeout - (System.currentTimeMillis() - reqStart),1); System.out.println("Waiting " + timeToWait + " ms for the result."); Thread.sleep(timeToWait); // Access result this.extractResult(reqMessage, results); } catch (Exception e) { e.printStackTrace(); } } /** * @see IService#getServiceIdentifier() */ public String getServiceIdentifier() { return SearchServiceConstants.SERVICE_MOD_SPEC_NAME; } }
true
true
protected void extractResult(Message reqMessage, List<IIndexerDocument> results) { List<Message> messageList = null; synchronized (this.resultMap) { if (!this.resultMap.containsKey(Integer.valueOf(reqMessage.getMessageNumber()))) { this.logger.warn("Unknown requestID: " + reqMessage.getMessageNumber()); messageList = Collections.EMPTY_LIST; } else { // remove the request from the result-list messageList = this.resultMap.remove(Integer.valueOf(reqMessage.getMessageNumber())); } } for (Message msg : messageList) { try { MessageElement resultListElement = msg.getMessageElement(SearchServiceConstants.RESP_RESULT); SAXReader reader = new SAXReader(); Document xmlDoc = reader.read(resultListElement.getStream()); Element xmlRoot = xmlDoc.getRootElement(); // iterate through child elements of root for (Iterator<Element> i = xmlRoot.elementIterator(SearchServiceConstants.RESULT_ENTRY); i.hasNext(); ) { Element resultElement = i.next(); for (Iterator<Element> j = resultElement.elementIterator(SearchServiceConstants.RESULT_ENTRY_ITEM); j.hasNext(); ) { Element resultItemElement = j.next(); IndexerDocument indexerDoc = new IndexerDocument(); for (Iterator<Element> k = resultItemElement.elementIterator(); k.hasNext(); ) { Element resultItemFieldElement = k.next(); String fieldName = resultItemFieldElement.getName(); String fieldValue = resultItemFieldElement.getText(); final org.paxle.core.doc.Field<?> pfield = this.fieldManager.get(fieldName); if (pfield != null) { indexerDoc.put(pfield, fieldValue); } } results.add(indexerDoc); } } } catch (Exception e) { e.printStackTrace(); } } }
protected void extractResult(Message reqMessage, List<IIndexerDocument> results) { List<Message> messageList = null; synchronized (this.resultMap) { if (!this.resultMap.containsKey(Integer.valueOf(reqMessage.getMessageNumber()))) { this.logger.warn("Unknown requestID: " + reqMessage.getMessageNumber()); messageList = Collections.emptyList(); } else { // remove the request from the result-list messageList = this.resultMap.remove(Integer.valueOf(reqMessage.getMessageNumber())); } } for (Message msg : messageList) { try { MessageElement resultListElement = msg.getMessageElement(SearchServiceConstants.RESP_RESULT); SAXReader reader = new SAXReader(); Document xmlDoc = reader.read(resultListElement.getStream()); Element xmlRoot = xmlDoc.getRootElement(); // iterate through child elements of root for (Iterator<Element> i = xmlRoot.elementIterator(SearchServiceConstants.RESULT_ENTRY); i.hasNext(); ) { Element resultElement = i.next(); for (Iterator<Element> j = resultElement.elementIterator(SearchServiceConstants.RESULT_ENTRY_ITEM); j.hasNext(); ) { Element resultItemElement = j.next(); IndexerDocument indexerDoc = new IndexerDocument(); for (Iterator<Element> k = resultItemElement.elementIterator(); k.hasNext(); ) { Element resultItemFieldElement = k.next(); String fieldName = resultItemFieldElement.getName(); String fieldValue = resultItemFieldElement.getText(); final org.paxle.core.doc.Field<?> pfield = this.fieldManager.get(fieldName); if (pfield != null) { indexerDoc.put(pfield, fieldValue); } } results.add(indexerDoc); } } } catch (Exception e) { e.printStackTrace(); } } }
diff --git a/src/java/org/apache/cassandra/transport/DataType.java b/src/java/org/apache/cassandra/transport/DataType.java index 0cb9d2d75..80528e759 100644 --- a/src/java/org/apache/cassandra/transport/DataType.java +++ b/src/java/org/apache/cassandra/transport/DataType.java @@ -1,197 +1,197 @@ /* * 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.cassandra.transport; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.List; import com.google.common.base.Charsets; import org.jboss.netty.buffer.ChannelBuffer; import org.apache.cassandra.exceptions.RequestValidationException; import org.apache.cassandra.db.marshal.*; import org.apache.cassandra.utils.Pair; public enum DataType implements OptionCodec.Codecable<DataType> { CUSTOM (0, null), ASCII (1, AsciiType.instance), BIGINT (2, LongType.instance), BLOB (3, BytesType.instance), BOOLEAN (4, BooleanType.instance), COUNTER (5, CounterColumnType.instance), DECIMAL (6, DecimalType.instance), DOUBLE (7, DoubleType.instance), FLOAT (8, FloatType.instance), INT (9, Int32Type.instance), TEXT (10, UTF8Type.instance), TIMESTAMP(11, DateType.instance), UUID (12, UUIDType.instance), VARCHAR (13, UTF8Type.instance), VARINT (14, IntegerType.instance), TIMEUUID (15, TimeUUIDType.instance), INET (16, InetAddressType.instance), LIST (32, null), MAP (33, null), SET (34, null); public static final OptionCodec<DataType> codec = new OptionCodec<DataType>(DataType.class); private final int id; private final AbstractType type; private static final Map<AbstractType, DataType> dataTypeMap = new HashMap<AbstractType, DataType>(); static { for (DataType type : DataType.values()) { if (type.type != null) dataTypeMap.put(type.type, type); } } private DataType(int id, AbstractType type) { this.id = id; this.type = type; } public int getId() { return id; } public Object readValue(ChannelBuffer cb) { switch (this) { case CUSTOM: return CBUtil.readString(cb); case LIST: return DataType.toType(codec.decodeOne(cb)); case SET: return DataType.toType(codec.decodeOne(cb)); case MAP: List<AbstractType> l = new ArrayList<AbstractType>(2); l.add(DataType.toType(codec.decodeOne(cb))); l.add(DataType.toType(codec.decodeOne(cb))); return l; default: return null; } } public void writeValue(Object value, ChannelBuffer cb) { switch (this) { case CUSTOM: assert value instanceof String; cb.writeBytes(CBUtil.stringToCB((String)value)); break; case LIST: cb.writeBytes(codec.encodeOne(DataType.fromType((AbstractType)value))); break; case SET: cb.writeBytes(codec.encodeOne(DataType.fromType((AbstractType)value))); break; case MAP: List<AbstractType> l = (List<AbstractType>)value; cb.writeBytes(codec.encodeOne(DataType.fromType(l.get(0)))); cb.writeBytes(codec.encodeOne(DataType.fromType(l.get(1)))); break; } } public int serializedValueSize(Object value) { switch (this) { case CUSTOM: return 2 + ((String)value).getBytes(Charsets.UTF_8).length; case LIST: case SET: return codec.oneSerializedSize(DataType.fromType((AbstractType)value)); case MAP: List<AbstractType> l = (List<AbstractType>)value; int s = 0; s += codec.oneSerializedSize(DataType.fromType(l.get(0))); s += codec.oneSerializedSize(DataType.fromType(l.get(1))); return s; default: return 0; } } public static Pair<DataType, Object> fromType(AbstractType type) { DataType dt = dataTypeMap.get(type); if (dt == null) { if (type.isCollection()) { if (type instanceof ListType) { return Pair.<DataType, Object>create(LIST, ((ListType)type).elements); } else if (type instanceof MapType) { MapType mt = (MapType)type; return Pair.<DataType, Object>create(MAP, Arrays.asList(mt.keys, mt.values)); } else { assert type instanceof SetType; - return Pair.<DataType, Object>create(LIST, ((SetType)type).elements); + return Pair.<DataType, Object>create(SET, ((SetType)type).elements); } } return Pair.<DataType, Object>create(CUSTOM, type.toString()); } else { return Pair.create(dt, null); } } public static AbstractType toType(Pair<DataType, Object> entry) { try { switch (entry.left) { case CUSTOM: return TypeParser.parse((String)entry.right); case LIST: return ListType.getInstance((AbstractType)entry.right); case SET: return SetType.getInstance((AbstractType)entry.right); case MAP: List<AbstractType> l = (List<AbstractType>)entry.right; return MapType.getInstance(l.get(0), l.get(1)); default: return entry.left.type; } } catch (RequestValidationException e) { throw new ProtocolException(e.getMessage()); } } }
true
true
public static Pair<DataType, Object> fromType(AbstractType type) { DataType dt = dataTypeMap.get(type); if (dt == null) { if (type.isCollection()) { if (type instanceof ListType) { return Pair.<DataType, Object>create(LIST, ((ListType)type).elements); } else if (type instanceof MapType) { MapType mt = (MapType)type; return Pair.<DataType, Object>create(MAP, Arrays.asList(mt.keys, mt.values)); } else { assert type instanceof SetType; return Pair.<DataType, Object>create(LIST, ((SetType)type).elements); } } return Pair.<DataType, Object>create(CUSTOM, type.toString()); } else { return Pair.create(dt, null); } }
public static Pair<DataType, Object> fromType(AbstractType type) { DataType dt = dataTypeMap.get(type); if (dt == null) { if (type.isCollection()) { if (type instanceof ListType) { return Pair.<DataType, Object>create(LIST, ((ListType)type).elements); } else if (type instanceof MapType) { MapType mt = (MapType)type; return Pair.<DataType, Object>create(MAP, Arrays.asList(mt.keys, mt.values)); } else { assert type instanceof SetType; return Pair.<DataType, Object>create(SET, ((SetType)type).elements); } } return Pair.<DataType, Object>create(CUSTOM, type.toString()); } else { return Pair.create(dt, null); } }
diff --git a/src/net/sourcewalker/smugview/gui/AlbumListActivity.java b/src/net/sourcewalker/smugview/gui/AlbumListActivity.java index 068ba4c..88ee3a9 100644 --- a/src/net/sourcewalker/smugview/gui/AlbumListActivity.java +++ b/src/net/sourcewalker/smugview/gui/AlbumListActivity.java @@ -1,212 +1,212 @@ package net.sourcewalker.smugview.gui; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import net.sourcewalker.smugview.ApiConstants; import net.sourcewalker.smugview.R; import net.sourcewalker.smugview.data.Cache; import net.sourcewalker.smugview.parcel.AlbumInfo; import net.sourcewalker.smugview.parcel.Extras; import net.sourcewalker.smugview.parcel.ImageInfo; import net.sourcewalker.smugview.parcel.LoginResult; import android.app.ListActivity; import android.content.Intent; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import com.kallasoft.smugmug.api.json.entity.Album; import com.kallasoft.smugmug.api.json.v1_2_0.APIVersionConstants; import com.kallasoft.smugmug.api.json.v1_2_0.albums.Get; import com.kallasoft.smugmug.api.json.v1_2_0.albums.Get.GetResponse; public class AlbumListActivity extends ListActivity { private AlbumListAdapter listAdapter; private LoginResult login; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.albumlist); login = (LoginResult) getIntent().getExtras().get(Extras.EXTRA_LOGIN); listAdapter = new AlbumListAdapter(); setListAdapter(listAdapter); startGetAlbums(); } private void startGetAlbums() { new GetAlbumsTask().execute(login); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { AlbumInfo album = (AlbumInfo) listAdapter.getItem(position); Intent intent = new Intent(this, AlbumActivity.class); intent.putExtra(Extras.EXTRA_LOGIN, login); intent.putExtra(Extras.EXTRA_ALBUM, album); startActivity(intent); } private class GetAlbumsTask extends AsyncTask<LoginResult, Void, List<AlbumInfo>> { @Override protected void onPreExecute() { setProgressBarIndeterminateVisibility(true); } @Override protected List<AlbumInfo> doInBackground(LoginResult... params) { LoginResult login = params[0]; List<AlbumInfo> result = new ArrayList<AlbumInfo>(); GetResponse response = new Get().execute( APIVersionConstants.SECURE_SERVER_URL, ApiConstants.APIKEY, login.getSession(), false); if (!response.isError()) { for (Album a : response.getAlbumList()) { result.add(new AlbumInfo(a)); } } return result; } @Override protected void onPostExecute(List<AlbumInfo> result) { setProgressBarIndeterminateVisibility(false); listAdapter.clear(); listAdapter.addAll(result); } } private class AlbumListAdapter implements ListAdapter { private List<AlbumInfo> albums = new ArrayList<AlbumInfo>(); private List<DataSetObserver> observers = new ArrayList<DataSetObserver>(); private Random rnd = new Random(); public void addAll(Collection<? extends AlbumInfo> items) { albums.addAll(items); notifyObservers(); } public void clear() { albums.clear(); notifyObservers(); } private void notifyObservers() { for (DataSetObserver observer : observers) { observer.onChanged(); } } @Override public boolean areAllItemsEnabled() { return true; } @Override public boolean isEnabled(int position) { return true; } @Override public int getCount() { return albums.size(); } @Override public Object getItem(int position) { return albums.get(position); } @Override public long getItemId(int position) { return albums.get(position).getId(); } @Override public int getItemViewType(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { AlbumListHolder holder; if (convertView == null) { convertView = View.inflate(AlbumListActivity.this, R.layout.albumlist_row, null); holder = new AlbumListHolder(); holder.title = (TextView) convertView .findViewById(R.id.albumrow_title); holder.desc = (TextView) convertView .findViewById(R.id.albumrow_desc); holder.example = (ImageView) convertView .findViewById(R.id.albumrow_image); convertView.setTag(holder); } else { holder = (AlbumListHolder) convertView.getTag(); } AlbumInfo item = albums.get(position); holder.title.setText(item.getTitle()); holder.desc.setText(item.getDescription()); Drawable thumbnail = null; List<ImageInfo> cache = Cache.getAlbumImages(item); - if (cache != null) { + if (cache != null && cache.size() > 0) { ImageInfo random = cache.get(rnd.nextInt(cache.size())); thumbnail = random.getThumbnail(); } holder.example.setImageDrawable(thumbnail); return convertView; } @Override public int getViewTypeCount() { return 1; } @Override public boolean hasStableIds() { return true; } @Override public boolean isEmpty() { return albums.size() == 0; } @Override public void registerDataSetObserver(DataSetObserver observer) { observers.add(observer); } @Override public void unregisterDataSetObserver(DataSetObserver observer) { observers.remove(observer); } } private class AlbumListHolder { public TextView title; public TextView desc; public ImageView example; } }
true
true
public View getView(int position, View convertView, ViewGroup parent) { AlbumListHolder holder; if (convertView == null) { convertView = View.inflate(AlbumListActivity.this, R.layout.albumlist_row, null); holder = new AlbumListHolder(); holder.title = (TextView) convertView .findViewById(R.id.albumrow_title); holder.desc = (TextView) convertView .findViewById(R.id.albumrow_desc); holder.example = (ImageView) convertView .findViewById(R.id.albumrow_image); convertView.setTag(holder); } else { holder = (AlbumListHolder) convertView.getTag(); } AlbumInfo item = albums.get(position); holder.title.setText(item.getTitle()); holder.desc.setText(item.getDescription()); Drawable thumbnail = null; List<ImageInfo> cache = Cache.getAlbumImages(item); if (cache != null) { ImageInfo random = cache.get(rnd.nextInt(cache.size())); thumbnail = random.getThumbnail(); } holder.example.setImageDrawable(thumbnail); return convertView; }
public View getView(int position, View convertView, ViewGroup parent) { AlbumListHolder holder; if (convertView == null) { convertView = View.inflate(AlbumListActivity.this, R.layout.albumlist_row, null); holder = new AlbumListHolder(); holder.title = (TextView) convertView .findViewById(R.id.albumrow_title); holder.desc = (TextView) convertView .findViewById(R.id.albumrow_desc); holder.example = (ImageView) convertView .findViewById(R.id.albumrow_image); convertView.setTag(holder); } else { holder = (AlbumListHolder) convertView.getTag(); } AlbumInfo item = albums.get(position); holder.title.setText(item.getTitle()); holder.desc.setText(item.getDescription()); Drawable thumbnail = null; List<ImageInfo> cache = Cache.getAlbumImages(item); if (cache != null && cache.size() > 0) { ImageInfo random = cache.get(rnd.nextInt(cache.size())); thumbnail = random.getThumbnail(); } holder.example.setImageDrawable(thumbnail); return convertView; }
diff --git a/autocompleteServer/src/main/java/de/metalcon/autocompleteServer/Search.java b/autocompleteServer/src/main/java/de/metalcon/autocompleteServer/Search.java index 0961799..465ecf5 100644 --- a/autocompleteServer/src/main/java/de/metalcon/autocompleteServer/Search.java +++ b/autocompleteServer/src/main/java/de/metalcon/autocompleteServer/Search.java @@ -1,51 +1,52 @@ package de.metalcon.autocompleteServer; import java.io.*; import de.metalcon.autocompleteServer.SuggestTree; import de.metalcon.autocompleteServer.SuggestTree.*; public class Search { public static SuggestTree suggestTree = null; public static String treeSearch(String input) { if (suggestTree == null) { + suggestTree = new SuggestTree(7); int priority = 100000; String filename = "/var/lib/datasets/metalcon/Band.csv"; // there must be a way to use relative paths! try { BufferedReader in = new BufferedReader(new FileReader(filename)); String zeile = null; String newZeile = null; String newZeileMyspace = null; // String Bandname = null; while ((zeile = in.readLine()) != null) { String[] parts = zeile.split(";"); if ((parts.length == 3) && !(parts[1].equals("NULL")) && !(parts[2].equals("NULL")) && !(parts[0].equals(""))) { parts[0] = parts[0].replaceAll("[\"]", ""); newZeile = "<a href=" + parts[1] + ">" + parts[0] + "</a>" + "<br>"; newZeileMyspace = "<a href=" + parts[2] + ">" + parts[0] + "</a>" + "<br>"; suggestTree.put(parts[0], priority); --priority; } } } catch (IOException e) { e.printStackTrace(); return null; } } // TODO: find a working way to return multiple results Node result = suggestTree.getBestSuggestions(input); StringBuffer resultList = new StringBuffer(""); for (int i = 0; i < result.listLength(); ++i) { resultList = resultList.append(result.getSuggestion(i) + ","); } // return resultList.toString(); return resultList.toString(); } }
true
true
public static String treeSearch(String input) { if (suggestTree == null) { int priority = 100000; String filename = "/var/lib/datasets/metalcon/Band.csv"; // there must be a way to use relative paths! try { BufferedReader in = new BufferedReader(new FileReader(filename)); String zeile = null; String newZeile = null; String newZeileMyspace = null; // String Bandname = null; while ((zeile = in.readLine()) != null) { String[] parts = zeile.split(";"); if ((parts.length == 3) && !(parts[1].equals("NULL")) && !(parts[2].equals("NULL")) && !(parts[0].equals(""))) { parts[0] = parts[0].replaceAll("[\"]", ""); newZeile = "<a href=" + parts[1] + ">" + parts[0] + "</a>" + "<br>"; newZeileMyspace = "<a href=" + parts[2] + ">" + parts[0] + "</a>" + "<br>"; suggestTree.put(parts[0], priority); --priority; } } } catch (IOException e) { e.printStackTrace(); return null; } } // TODO: find a working way to return multiple results Node result = suggestTree.getBestSuggestions(input); StringBuffer resultList = new StringBuffer(""); for (int i = 0; i < result.listLength(); ++i) { resultList = resultList.append(result.getSuggestion(i) + ","); } // return resultList.toString(); return resultList.toString(); }
public static String treeSearch(String input) { if (suggestTree == null) { suggestTree = new SuggestTree(7); int priority = 100000; String filename = "/var/lib/datasets/metalcon/Band.csv"; // there must be a way to use relative paths! try { BufferedReader in = new BufferedReader(new FileReader(filename)); String zeile = null; String newZeile = null; String newZeileMyspace = null; // String Bandname = null; while ((zeile = in.readLine()) != null) { String[] parts = zeile.split(";"); if ((parts.length == 3) && !(parts[1].equals("NULL")) && !(parts[2].equals("NULL")) && !(parts[0].equals(""))) { parts[0] = parts[0].replaceAll("[\"]", ""); newZeile = "<a href=" + parts[1] + ">" + parts[0] + "</a>" + "<br>"; newZeileMyspace = "<a href=" + parts[2] + ">" + parts[0] + "</a>" + "<br>"; suggestTree.put(parts[0], priority); --priority; } } } catch (IOException e) { e.printStackTrace(); return null; } } // TODO: find a working way to return multiple results Node result = suggestTree.getBestSuggestions(input); StringBuffer resultList = new StringBuffer(""); for (int i = 0; i < result.listLength(); ++i) { resultList = resultList.append(result.getSuggestion(i) + ","); } // return resultList.toString(); return resultList.toString(); }
diff --git a/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java b/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java index 1a539406..f83a7fbf 100644 --- a/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java +++ b/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java @@ -1,195 +1,195 @@ package com.redhat.qe.jon.sahi.base.inventory; import com.redhat.qe.jon.sahi.base.editor.*; import com.redhat.qe.jon.sahi.tasks.*; import net.sf.sahi.client.*; import org.testng.*; import java.util.*; import java.util.logging.*; /** * represents <b>Operations</b> Tab of given resource. * Creating instance of this class will navigate to resource and select <b>Operations</b> Tab * * @author lzoubek */ public class Operations extends ResourceTab { public Operations(SahiTasks tasks, Resource resource) { super(tasks, resource); } @Override protected void navigate() { navigateUnderResource("Operations/Schedules"); raiseErrorIfCellDoesNotExist("Operations"); } public void history() { navigateUnderResource("Operations/History"); raiseErrorIfCellDoesNotExist("Operations"); } /** * Creates new Operation of given name, also selects it in <b>Operation:</b> combo * * @param name of new Operation * @return new operation */ public Operation newOperation(String name) { tasks.cell("New").click(); tasks.reloadPage(); return new Operation(tasks, name); } /** * asserts operation result, waits until operation is either success or failure. * * @param op operation * @param success if true, success is expected, otherwise failure is expected * @return result map returned by this operation if operation succeeded, otherwise null. * In this map, keys are result properties and values are result values */ public Map<String, String> assertOperationResult(Operation op, boolean success) { String opName = op.name; String resultImage = "Operation_failed_16.png"; String succ = "Failed"; if (success) { resultImage = "Operation_ok_16.png"; succ = "Success"; } log.fine("Asserting operation [" + opName + "] result, expecting " + succ); getResource().operations().history(); int allOperationStartedTimeout = Timing.TIME_30S; while (tasks.cell("not yet started").in(tasks.div(opName).parentNode("tr")).isVisible() && allOperationStartedTimeout > 0) { allOperationStartedTimeout -= Timing.WAIT_TIME; tasks.waitFor(Timing.WAIT_TIME); - tasks.cell("Reload").click(); + tasks.cell("Refresh").click(); } // sort by Date Submitted tasks.cell("Date Submitted").doubleClick(); tasks.waitFor(Timing.WAIT_TIME); tasks.cell("Date Submitted").doubleClick(); tasks.waitFor(Timing.WAIT_TIME); int timeout = 20 * Timing.TIME_1M; int time = 0; while (time < timeout && tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) { time += Timing.TIME_10S; log.fine("Operation [" + opName + "] in progress, waiting " + Timing.toString(Timing.TIME_10S)); tasks.waitFor(Timing.TIME_10S); tasks.cell("Refresh").click(); // getResource().operations().history(); // it would have to be sorted again } if (tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) { log.info("Operation [" + opName + "] did NOT finish after " + Timing.toString(time) + "!!!"); Assert.assertEquals(!success, success, "Operation [" + opName + "] result: " + succ); } else { log.info("Operation [" + opName + "] finished after " + Timing.toString(time)); } boolean existsImage = tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).exists(); // when operation failed and success was expected, let's get operation error message if (!existsImage && success) { log.info("Retrieving the error message as it was expected that operation ends successfully but it didn't"); String message = null; tasks.xy(tasks.image("Operation_failed_16.png").in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).click(); if (tasks.preformatted("").exists()) { message = tasks.preformatted("").getText(); } tasks.waitFor(Timing.WAIT_TIME); int buttons = tasks.image("close.png").countSimilar(); tasks.xy(tasks.image("close.png[" + (buttons - 1) + "]"), 3, 3).click(); if (message != null) { Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ + " errorMessage:\n" + message); return null; } } Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ); log.fine("Getting operation result"); ElementStub linkToOperationResults = tasks.link(0).near(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr"))); linkToOperationResults.click(); if (!tasks.cell("Execution ID :").isVisible()) { log.fine("Operation results not opened correctly"); tasks.xy(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).doubleClick(); } tasks.reloadPage(); log.finest("The property element: " + tasks.cell("Property").fetch()); List<ElementStub> headerCells = tasks.cell("Property").collectSimilar(); for (ElementStub el : headerCells) { log.finest("Header cell: " + el.fetch()); } if (headerCells.size() > 0) { Map<String, String> result = new HashMap<String, String>(); ElementStub table = headerCells.get(headerCells.size() - 1).parentNode("table"); log.finer("Table element is " + table.toString()); List<ElementStub> rows = tasks.row("").in(table).collectSimilar(); // starting with 3rd row, because 1st some shit and 2nd is table header // we also ignore last because sahi was failing log.fine("Have " + (rows.size() - 2) + " result rows"); log.finest("The rows are: " + rows.toString()); log.finest("The last row first column: " + tasks.cell(0).in(rows.get(rows.size()-1)).getText()); for (int i = 2; i < rows.size(); i++) { ElementStub row = rows.get(i); ElementStub key = tasks.cell(0).in(row); ElementStub value = tasks.cell(2).in(row); if (key.exists() && value.exists()) { log.fine("Found result property [" + key.getText() + "]"); result.put(key.getText(), value.getText()); } else { log.warning("Missing key or value column in the results table - probably caused by nonstandard result output"); } } return result; } log.fine("Result table not found"); return null; } public static class Operation { private final SahiTasks tasks; private final String name; private final Editor editor; private final Logger log = Logger.getLogger(this.getClass().getName()); public Operation(SahiTasks tasks, String name) { this.tasks = tasks; this.name = name; this.editor = new Editor(tasks); tasks.waitFor(Timing.WAIT_TIME); selectOperation(this.name); } public void selectOperation(String op) { getEditor().selectCombo(op); } /** * asserts all required input fields have been filled */ public void assertRequiredInputs() { getEditor().assertRequiredInputs(); } public Editor getEditor() { return editor; } /** * clicks <b>Schedule</b> button to start operation */ public void schedule() { tasks.cell("Schedule").click(); Assert.assertTrue(tasks.waitForElementVisible(tasks, tasks.cell("/Operation Schedule created.*/"), "Successful message",Timing.WAIT_TIME) ,"Operation was scheduled"); } } }
true
true
public Map<String, String> assertOperationResult(Operation op, boolean success) { String opName = op.name; String resultImage = "Operation_failed_16.png"; String succ = "Failed"; if (success) { resultImage = "Operation_ok_16.png"; succ = "Success"; } log.fine("Asserting operation [" + opName + "] result, expecting " + succ); getResource().operations().history(); int allOperationStartedTimeout = Timing.TIME_30S; while (tasks.cell("not yet started").in(tasks.div(opName).parentNode("tr")).isVisible() && allOperationStartedTimeout > 0) { allOperationStartedTimeout -= Timing.WAIT_TIME; tasks.waitFor(Timing.WAIT_TIME); tasks.cell("Reload").click(); } // sort by Date Submitted tasks.cell("Date Submitted").doubleClick(); tasks.waitFor(Timing.WAIT_TIME); tasks.cell("Date Submitted").doubleClick(); tasks.waitFor(Timing.WAIT_TIME); int timeout = 20 * Timing.TIME_1M; int time = 0; while (time < timeout && tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) { time += Timing.TIME_10S; log.fine("Operation [" + opName + "] in progress, waiting " + Timing.toString(Timing.TIME_10S)); tasks.waitFor(Timing.TIME_10S); tasks.cell("Refresh").click(); // getResource().operations().history(); // it would have to be sorted again } if (tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) { log.info("Operation [" + opName + "] did NOT finish after " + Timing.toString(time) + "!!!"); Assert.assertEquals(!success, success, "Operation [" + opName + "] result: " + succ); } else { log.info("Operation [" + opName + "] finished after " + Timing.toString(time)); } boolean existsImage = tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).exists(); // when operation failed and success was expected, let's get operation error message if (!existsImage && success) { log.info("Retrieving the error message as it was expected that operation ends successfully but it didn't"); String message = null; tasks.xy(tasks.image("Operation_failed_16.png").in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).click(); if (tasks.preformatted("").exists()) { message = tasks.preformatted("").getText(); } tasks.waitFor(Timing.WAIT_TIME); int buttons = tasks.image("close.png").countSimilar(); tasks.xy(tasks.image("close.png[" + (buttons - 1) + "]"), 3, 3).click(); if (message != null) { Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ + " errorMessage:\n" + message); return null; } } Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ); log.fine("Getting operation result"); ElementStub linkToOperationResults = tasks.link(0).near(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr"))); linkToOperationResults.click(); if (!tasks.cell("Execution ID :").isVisible()) { log.fine("Operation results not opened correctly"); tasks.xy(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).doubleClick(); } tasks.reloadPage(); log.finest("The property element: " + tasks.cell("Property").fetch()); List<ElementStub> headerCells = tasks.cell("Property").collectSimilar(); for (ElementStub el : headerCells) { log.finest("Header cell: " + el.fetch()); } if (headerCells.size() > 0) { Map<String, String> result = new HashMap<String, String>(); ElementStub table = headerCells.get(headerCells.size() - 1).parentNode("table"); log.finer("Table element is " + table.toString()); List<ElementStub> rows = tasks.row("").in(table).collectSimilar(); // starting with 3rd row, because 1st some shit and 2nd is table header // we also ignore last because sahi was failing log.fine("Have " + (rows.size() - 2) + " result rows"); log.finest("The rows are: " + rows.toString()); log.finest("The last row first column: " + tasks.cell(0).in(rows.get(rows.size()-1)).getText()); for (int i = 2; i < rows.size(); i++) { ElementStub row = rows.get(i); ElementStub key = tasks.cell(0).in(row); ElementStub value = tasks.cell(2).in(row); if (key.exists() && value.exists()) { log.fine("Found result property [" + key.getText() + "]"); result.put(key.getText(), value.getText()); } else { log.warning("Missing key or value column in the results table - probably caused by nonstandard result output"); } } return result; } log.fine("Result table not found"); return null; }
public Map<String, String> assertOperationResult(Operation op, boolean success) { String opName = op.name; String resultImage = "Operation_failed_16.png"; String succ = "Failed"; if (success) { resultImage = "Operation_ok_16.png"; succ = "Success"; } log.fine("Asserting operation [" + opName + "] result, expecting " + succ); getResource().operations().history(); int allOperationStartedTimeout = Timing.TIME_30S; while (tasks.cell("not yet started").in(tasks.div(opName).parentNode("tr")).isVisible() && allOperationStartedTimeout > 0) { allOperationStartedTimeout -= Timing.WAIT_TIME; tasks.waitFor(Timing.WAIT_TIME); tasks.cell("Refresh").click(); } // sort by Date Submitted tasks.cell("Date Submitted").doubleClick(); tasks.waitFor(Timing.WAIT_TIME); tasks.cell("Date Submitted").doubleClick(); tasks.waitFor(Timing.WAIT_TIME); int timeout = 20 * Timing.TIME_1M; int time = 0; while (time < timeout && tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) { time += Timing.TIME_10S; log.fine("Operation [" + opName + "] in progress, waiting " + Timing.toString(Timing.TIME_10S)); tasks.waitFor(Timing.TIME_10S); tasks.cell("Refresh").click(); // getResource().operations().history(); // it would have to be sorted again } if (tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) { log.info("Operation [" + opName + "] did NOT finish after " + Timing.toString(time) + "!!!"); Assert.assertEquals(!success, success, "Operation [" + opName + "] result: " + succ); } else { log.info("Operation [" + opName + "] finished after " + Timing.toString(time)); } boolean existsImage = tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).exists(); // when operation failed and success was expected, let's get operation error message if (!existsImage && success) { log.info("Retrieving the error message as it was expected that operation ends successfully but it didn't"); String message = null; tasks.xy(tasks.image("Operation_failed_16.png").in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).click(); if (tasks.preformatted("").exists()) { message = tasks.preformatted("").getText(); } tasks.waitFor(Timing.WAIT_TIME); int buttons = tasks.image("close.png").countSimilar(); tasks.xy(tasks.image("close.png[" + (buttons - 1) + "]"), 3, 3).click(); if (message != null) { Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ + " errorMessage:\n" + message); return null; } } Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ); log.fine("Getting operation result"); ElementStub linkToOperationResults = tasks.link(0).near(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr"))); linkToOperationResults.click(); if (!tasks.cell("Execution ID :").isVisible()) { log.fine("Operation results not opened correctly"); tasks.xy(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).doubleClick(); } tasks.reloadPage(); log.finest("The property element: " + tasks.cell("Property").fetch()); List<ElementStub> headerCells = tasks.cell("Property").collectSimilar(); for (ElementStub el : headerCells) { log.finest("Header cell: " + el.fetch()); } if (headerCells.size() > 0) { Map<String, String> result = new HashMap<String, String>(); ElementStub table = headerCells.get(headerCells.size() - 1).parentNode("table"); log.finer("Table element is " + table.toString()); List<ElementStub> rows = tasks.row("").in(table).collectSimilar(); // starting with 3rd row, because 1st some shit and 2nd is table header // we also ignore last because sahi was failing log.fine("Have " + (rows.size() - 2) + " result rows"); log.finest("The rows are: " + rows.toString()); log.finest("The last row first column: " + tasks.cell(0).in(rows.get(rows.size()-1)).getText()); for (int i = 2; i < rows.size(); i++) { ElementStub row = rows.get(i); ElementStub key = tasks.cell(0).in(row); ElementStub value = tasks.cell(2).in(row); if (key.exists() && value.exists()) { log.fine("Found result property [" + key.getText() + "]"); result.put(key.getText(), value.getText()); } else { log.warning("Missing key or value column in the results table - probably caused by nonstandard result output"); } } return result; } log.fine("Result table not found"); return null; }
diff --git a/hale/eu.esdihumboldt.hale/src/eu/esdihumboldt/hale/rcp/wizards/io/InstanceDataImportWizardMainPage.java b/hale/eu.esdihumboldt.hale/src/eu/esdihumboldt/hale/rcp/wizards/io/InstanceDataImportWizardMainPage.java index 19a68a9a5..3e92edab8 100644 --- a/hale/eu.esdihumboldt.hale/src/eu/esdihumboldt/hale/rcp/wizards/io/InstanceDataImportWizardMainPage.java +++ b/hale/eu.esdihumboldt.hale/src/eu/esdihumboldt/hale/rcp/wizards/io/InstanceDataImportWizardMainPage.java @@ -1,240 +1,240 @@ /* * HUMBOLDT: A Framework for Data Harmonisation and Service Integration. * EU Integrated Project #030962 01.10.2006 - 30.09.2010 * * For more information on the project, please refer to the this web site: * http://www.esdi-humboldt.eu * * LICENSE: For information on the license under which this program is * available, please refer to http:/www.esdi-humboldt.eu/license.html#core * (c) the HUMBOLDT Consortium, 2007 to 2010. */ package eu.esdihumboldt.hale.rcp.wizards.io; import java.net.URI; import java.net.URL; import org.apache.log4j.Logger; import org.eclipse.jface.preference.FileFieldEditor; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; /** * This is the first page of the {@link InstanceDataImportWizard}. It allows to * select the principal source of the geodata to be used in HALE. * * @author Thorsten Reitz * @version $Id$ */ public class InstanceDataImportWizardMainPage extends WizardPage { private static Logger _log = Logger.getLogger(InstanceDataImportWizardMainPage.class); private boolean useFile = true; private String result; private FileFieldEditor fileFieldEditor; private UrlFieldEditor wfsFieldEditor; // constructors ............................................................ protected InstanceDataImportWizardMainPage(String pageName, String pageTitle) { super(pageName, pageTitle, (ImageDescriptor) null); // FIXME ImageDescriptor super.setTitle(pageName); //NON-NLS-1 super.setDescription(Messages.InstanceDataImportWizardMainPage_LoadGeoDescription1 + Messages.InstanceDataImportWizardMainPage_LoadGeoDescription2); } // methods ................................................................. /** * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { super.initializeDialogUnits(parent); Composite composite = new Composite(parent, SWT.NULL); composite.setLayout(new GridLayout()); composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL)); composite.setSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); composite.setFont(parent.getFont()); this.createSourceGroup(composite); super.setPageComplete(false); super.setErrorMessage(null); super.setControl(composite); } /** * Creates the UI controls for the selection of the source of the schema * to be imported. * * @param parent the parent {@link Composite} */ private void createSourceGroup(Composite parent) { // define source group composite Group selectionArea = new Group(parent, SWT.NONE); selectionArea.setText(Messages.InstanceDataImportWizardMainPage_ReadGeodata); selectionArea.setLayout(new GridLayout()); GridData selectionAreaGD = new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL); selectionAreaGD.grabExcessHorizontalSpace = true; selectionArea.setLayoutData(selectionAreaGD); selectionArea.setSize(selectionArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); selectionArea.setFont(parent.getFont()); // read from file (XSD, GML, XML) final Composite fileSelectionArea = new Composite(selectionArea, SWT.NONE); GridData fileSelectionData = new GridData( GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL); fileSelectionData.grabExcessHorizontalSpace = true; fileSelectionArea.setLayoutData(fileSelectionData); GridLayout fileSelectionLayout = new GridLayout(); fileSelectionLayout.numColumns = 2; fileSelectionLayout.makeColumnsEqualWidth = false; fileSelectionLayout.marginWidth = 0; fileSelectionLayout.marginHeight = 0; fileSelectionArea.setLayout(fileSelectionLayout); Button useFileRadio = new Button(fileSelectionArea, SWT.RADIO); useFileRadio.setSelection(true); final Composite ffe_container = new Composite(fileSelectionArea, SWT.NULL); ffe_container.setLayoutData( new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); this.fileFieldEditor = new FileFieldEditor("fileSelect", //$NON-NLS-1$ Messages.InstanceDataImportWizardMainPage_File, ffe_container); //NON-NLS-1 //NON-NLS-2 this.fileFieldEditor.getTextControl(ffe_container).addModifyListener(new ModifyListener(){ public void modifyText(ModifyEvent e) { getWizard().getContainer().updateButtons(); } }); String[] extensions = new String[] { "*.gml", "*.xml" }; //NON-NLS-1 //$NON-NLS-1$ //$NON-NLS-2$ this.fileFieldEditor.setFileExtensions(extensions); // read from WFS (GetFeature) Button useWfsRadio = new Button(fileSelectionArea, SWT.RADIO); - useWfsRadio.setEnabled(false); + useWfsRadio.setEnabled(true); final Composite ufe_container = new Composite(fileSelectionArea, SWT.NULL); ufe_container.setLayoutData( new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); this.wfsFieldEditor = new UrlFieldEditor("urlSelect","... WFS GetFeature:", ufe_container,true); //$NON-NLS-1$ //$NON-NLS-2$ this.wfsFieldEditor.setEnabled(false, ufe_container); this.wfsFieldEditor.getTextControl(ufe_container).addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { getWizard().getContainer().updateButtons(); } }); // add listeners to radio buttons useFileRadio.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { useFile = ((Button)e.widget).getSelection(); if (((Button)e.widget).getSelection()) { fileFieldEditor.setEnabled(true, ffe_container); wfsFieldEditor.setEnabled(false, ufe_container); } else { fileFieldEditor.setEnabled(false, ffe_container); wfsFieldEditor.setEnabled(true, ufe_container); } } }); useWfsRadio.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - useFile = ((Button)e.widget).getSelection(); + useFile = !((Button)e.widget).getSelection(); if (((Button)e.widget).getSelection()) { fileFieldEditor.setEnabled(false, ffe_container); wfsFieldEditor.setEnabled(true, ufe_container); } else { fileFieldEditor.setEnabled(true, ffe_container); wfsFieldEditor.setEnabled(false, ufe_container); } } }); // finish some stuff. fileSelectionArea.moveAbove(null); } /** * @see org.eclipse.jface.wizard.WizardPage#isPageComplete() */ @Override public boolean isPageComplete() { if (this.fileFieldEditor != null && this.wfsFieldEditor != null) { try { if (!this.useFile) { // test whether content of the WFS Field Editor validates to URL. String test = this.wfsFieldEditor.getStringValue(); if (test != null && !test.equals("")) { //$NON-NLS-1$ new URL(test); _log.debug("wfsFieldEditor URL was OK."); //$NON-NLS-1$ this.result = test; } else { return false; } } else { // test whether content of the File Field Editor validates to URI. String test = this.fileFieldEditor.getStringValue(); if (test != null && !test.equals("")) { //$NON-NLS-1$ test = test.replace(" ", "%20"); //$NON-NLS-1$ //$NON-NLS-2$ new URI(test.replaceAll("\\\\", "/")); //$NON-NLS-1$ //$NON-NLS-2$ _log.debug("fileFieldEditor URI was OK."); //$NON-NLS-1$ this.result = test; } else { return false; } } } catch (Exception ex) { ex.printStackTrace(); return false; } _log.debug("Page is complete."); //$NON-NLS-1$ return true; } else { return false; } } /** * @return a String representing the URL or URI to load the schema from. */ public String getResult() { return this.result; } public InstanceInterfaceType getInterfaceType() { if (this.useFile) { return InstanceInterfaceType.FILE; } else { return InstanceInterfaceType.WFS; } } }
false
true
private void createSourceGroup(Composite parent) { // define source group composite Group selectionArea = new Group(parent, SWT.NONE); selectionArea.setText(Messages.InstanceDataImportWizardMainPage_ReadGeodata); selectionArea.setLayout(new GridLayout()); GridData selectionAreaGD = new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL); selectionAreaGD.grabExcessHorizontalSpace = true; selectionArea.setLayoutData(selectionAreaGD); selectionArea.setSize(selectionArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); selectionArea.setFont(parent.getFont()); // read from file (XSD, GML, XML) final Composite fileSelectionArea = new Composite(selectionArea, SWT.NONE); GridData fileSelectionData = new GridData( GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL); fileSelectionData.grabExcessHorizontalSpace = true; fileSelectionArea.setLayoutData(fileSelectionData); GridLayout fileSelectionLayout = new GridLayout(); fileSelectionLayout.numColumns = 2; fileSelectionLayout.makeColumnsEqualWidth = false; fileSelectionLayout.marginWidth = 0; fileSelectionLayout.marginHeight = 0; fileSelectionArea.setLayout(fileSelectionLayout); Button useFileRadio = new Button(fileSelectionArea, SWT.RADIO); useFileRadio.setSelection(true); final Composite ffe_container = new Composite(fileSelectionArea, SWT.NULL); ffe_container.setLayoutData( new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); this.fileFieldEditor = new FileFieldEditor("fileSelect", //$NON-NLS-1$ Messages.InstanceDataImportWizardMainPage_File, ffe_container); //NON-NLS-1 //NON-NLS-2 this.fileFieldEditor.getTextControl(ffe_container).addModifyListener(new ModifyListener(){ public void modifyText(ModifyEvent e) { getWizard().getContainer().updateButtons(); } }); String[] extensions = new String[] { "*.gml", "*.xml" }; //NON-NLS-1 //$NON-NLS-1$ //$NON-NLS-2$ this.fileFieldEditor.setFileExtensions(extensions); // read from WFS (GetFeature) Button useWfsRadio = new Button(fileSelectionArea, SWT.RADIO); useWfsRadio.setEnabled(false); final Composite ufe_container = new Composite(fileSelectionArea, SWT.NULL); ufe_container.setLayoutData( new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); this.wfsFieldEditor = new UrlFieldEditor("urlSelect","... WFS GetFeature:", ufe_container,true); //$NON-NLS-1$ //$NON-NLS-2$ this.wfsFieldEditor.setEnabled(false, ufe_container); this.wfsFieldEditor.getTextControl(ufe_container).addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { getWizard().getContainer().updateButtons(); } }); // add listeners to radio buttons useFileRadio.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { useFile = ((Button)e.widget).getSelection(); if (((Button)e.widget).getSelection()) { fileFieldEditor.setEnabled(true, ffe_container); wfsFieldEditor.setEnabled(false, ufe_container); } else { fileFieldEditor.setEnabled(false, ffe_container); wfsFieldEditor.setEnabled(true, ufe_container); } } }); useWfsRadio.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { useFile = ((Button)e.widget).getSelection(); if (((Button)e.widget).getSelection()) { fileFieldEditor.setEnabled(false, ffe_container); wfsFieldEditor.setEnabled(true, ufe_container); } else { fileFieldEditor.setEnabled(true, ffe_container); wfsFieldEditor.setEnabled(false, ufe_container); } } }); // finish some stuff. fileSelectionArea.moveAbove(null); }
private void createSourceGroup(Composite parent) { // define source group composite Group selectionArea = new Group(parent, SWT.NONE); selectionArea.setText(Messages.InstanceDataImportWizardMainPage_ReadGeodata); selectionArea.setLayout(new GridLayout()); GridData selectionAreaGD = new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL); selectionAreaGD.grabExcessHorizontalSpace = true; selectionArea.setLayoutData(selectionAreaGD); selectionArea.setSize(selectionArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); selectionArea.setFont(parent.getFont()); // read from file (XSD, GML, XML) final Composite fileSelectionArea = new Composite(selectionArea, SWT.NONE); GridData fileSelectionData = new GridData( GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL); fileSelectionData.grabExcessHorizontalSpace = true; fileSelectionArea.setLayoutData(fileSelectionData); GridLayout fileSelectionLayout = new GridLayout(); fileSelectionLayout.numColumns = 2; fileSelectionLayout.makeColumnsEqualWidth = false; fileSelectionLayout.marginWidth = 0; fileSelectionLayout.marginHeight = 0; fileSelectionArea.setLayout(fileSelectionLayout); Button useFileRadio = new Button(fileSelectionArea, SWT.RADIO); useFileRadio.setSelection(true); final Composite ffe_container = new Composite(fileSelectionArea, SWT.NULL); ffe_container.setLayoutData( new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); this.fileFieldEditor = new FileFieldEditor("fileSelect", //$NON-NLS-1$ Messages.InstanceDataImportWizardMainPage_File, ffe_container); //NON-NLS-1 //NON-NLS-2 this.fileFieldEditor.getTextControl(ffe_container).addModifyListener(new ModifyListener(){ public void modifyText(ModifyEvent e) { getWizard().getContainer().updateButtons(); } }); String[] extensions = new String[] { "*.gml", "*.xml" }; //NON-NLS-1 //$NON-NLS-1$ //$NON-NLS-2$ this.fileFieldEditor.setFileExtensions(extensions); // read from WFS (GetFeature) Button useWfsRadio = new Button(fileSelectionArea, SWT.RADIO); useWfsRadio.setEnabled(true); final Composite ufe_container = new Composite(fileSelectionArea, SWT.NULL); ufe_container.setLayoutData( new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); this.wfsFieldEditor = new UrlFieldEditor("urlSelect","... WFS GetFeature:", ufe_container,true); //$NON-NLS-1$ //$NON-NLS-2$ this.wfsFieldEditor.setEnabled(false, ufe_container); this.wfsFieldEditor.getTextControl(ufe_container).addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { getWizard().getContainer().updateButtons(); } }); // add listeners to radio buttons useFileRadio.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { useFile = ((Button)e.widget).getSelection(); if (((Button)e.widget).getSelection()) { fileFieldEditor.setEnabled(true, ffe_container); wfsFieldEditor.setEnabled(false, ufe_container); } else { fileFieldEditor.setEnabled(false, ffe_container); wfsFieldEditor.setEnabled(true, ufe_container); } } }); useWfsRadio.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { useFile = !((Button)e.widget).getSelection(); if (((Button)e.widget).getSelection()) { fileFieldEditor.setEnabled(false, ffe_container); wfsFieldEditor.setEnabled(true, ufe_container); } else { fileFieldEditor.setEnabled(true, ffe_container); wfsFieldEditor.setEnabled(false, ufe_container); } } }); // finish some stuff. fileSelectionArea.moveAbove(null); }
diff --git a/DesktopDataLaboratory/src/org/gephi/desktop/datalab/persistence/DataLaboratoryPersistenceProvider.java b/DesktopDataLaboratory/src/org/gephi/desktop/datalab/persistence/DataLaboratoryPersistenceProvider.java index 49fac158d..76ea2221e 100644 --- a/DesktopDataLaboratory/src/org/gephi/desktop/datalab/persistence/DataLaboratoryPersistenceProvider.java +++ b/DesktopDataLaboratory/src/org/gephi/desktop/datalab/persistence/DataLaboratoryPersistenceProvider.java @@ -1,128 +1,128 @@ /* Copyright 2008-2010 Gephi Authors : Eduardo Ramos <[email protected]> Website : http://www.gephi.org This file is part of Gephi. Gephi is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gephi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Gephi. If not, see <http://www.gnu.org/licenses/>. */ package org.gephi.desktop.datalab.persistence; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.events.XMLEvent; import org.gephi.data.attributes.api.AttributeColumn; import org.gephi.data.attributes.api.AttributeModel; import org.gephi.data.attributes.api.AttributeTable; import org.gephi.desktop.datalab.AvailableColumnsModel; import org.gephi.desktop.datalab.DataTablesModel; import org.gephi.project.api.Workspace; import org.gephi.project.spi.WorkspacePersistenceProvider; import org.openide.util.lookup.ServiceProvider; /** * * @author Eduardo */ @ServiceProvider(service = WorkspacePersistenceProvider.class, position = 16000) public class DataLaboratoryPersistenceProvider implements WorkspacePersistenceProvider { private static final String AVAILABLE_COLUMNS = "availablecolumns"; private static final String NODE_COLUMN = "nodecolumn"; private static final String EDGE_COLUMN = "edgecolumn"; public void writeXML(XMLStreamWriter writer, Workspace workspace) { AttributeModel attributeModel = workspace.getLookup().lookup(AttributeModel.class); DataTablesModel dataTablesModel = workspace.getLookup().lookup(DataTablesModel.class); if (dataTablesModel == null) { workspace.add(dataTablesModel = new DataTablesModel(attributeModel.getNodeTable(), attributeModel.getEdgeTable())); } try { writeDataTablesModel(writer, dataTablesModel); } catch (XMLStreamException ex) { throw new RuntimeException(ex); } } public void readXML(XMLStreamReader reader, Workspace workspace) { try { readDataTablesModel(reader, workspace); } catch (XMLStreamException ex) { throw new RuntimeException(ex); } } public String getIdentifier() { return AVAILABLE_COLUMNS; } private void writeDataTablesModel(XMLStreamWriter writer, DataTablesModel dataTablesModel) throws XMLStreamException { writer.writeStartElement(AVAILABLE_COLUMNS); for (AttributeColumn column : dataTablesModel.getNodeAvailableColumnsModel().getAvailableColumns()) { writer.writeStartElement(NODE_COLUMN); writer.writeAttribute("id", String.valueOf(column.getIndex())); writer.writeEndElement(); } for (AttributeColumn column : dataTablesModel.getEdgeAvailableColumnsModel().getAvailableColumns()) { writer.writeStartElement(EDGE_COLUMN); writer.writeAttribute("id", String.valueOf(column.getIndex())); writer.writeEndElement(); } writer.writeEndElement(); } private void readDataTablesModel(XMLStreamReader reader, Workspace workspace) throws XMLStreamException { AttributeModel attributeModel = workspace.getLookup().lookup(AttributeModel.class); AttributeTable nodesTable = attributeModel.getNodeTable(); AttributeTable edgesTable = attributeModel.getEdgeTable(); DataTablesModel dataTablesModel = workspace.getLookup().lookup(DataTablesModel.class); if (dataTablesModel == null) { workspace.add(dataTablesModel = new DataTablesModel()); } AvailableColumnsModel nodeColumns = dataTablesModel.getNodeAvailableColumnsModel(); nodeColumns.removeAllColumns(); AvailableColumnsModel edgeColumns = dataTablesModel.getEdgeAvailableColumnsModel(); edgeColumns.removeAllColumns(); boolean end = false; while (reader.hasNext() && !end) { Integer eventType = reader.next(); if (eventType.equals(XMLEvent.START_ELEMENT)) { String name = reader.getLocalName(); if (NODE_COLUMN.equalsIgnoreCase(name)) { - String id = reader.getAttributeValue(null, "id"); + Integer id = Integer.parseInt(reader.getAttributeValue(null, "id")); AttributeColumn column = nodesTable.getColumn(id); if (column != null) { nodeColumns.addAvailableColumn(column); } } else if (EDGE_COLUMN.equalsIgnoreCase(name)) { String id = reader.getAttributeValue(null, "id"); AttributeColumn column = edgesTable.getColumn(id); if (column != null) { edgeColumns.addAvailableColumn(column); } } } else if (eventType.equals(XMLStreamReader.END_ELEMENT)) { if (AVAILABLE_COLUMNS.equalsIgnoreCase(reader.getLocalName())) { end = true; } } } } }
true
true
private void readDataTablesModel(XMLStreamReader reader, Workspace workspace) throws XMLStreamException { AttributeModel attributeModel = workspace.getLookup().lookup(AttributeModel.class); AttributeTable nodesTable = attributeModel.getNodeTable(); AttributeTable edgesTable = attributeModel.getEdgeTable(); DataTablesModel dataTablesModel = workspace.getLookup().lookup(DataTablesModel.class); if (dataTablesModel == null) { workspace.add(dataTablesModel = new DataTablesModel()); } AvailableColumnsModel nodeColumns = dataTablesModel.getNodeAvailableColumnsModel(); nodeColumns.removeAllColumns(); AvailableColumnsModel edgeColumns = dataTablesModel.getEdgeAvailableColumnsModel(); edgeColumns.removeAllColumns(); boolean end = false; while (reader.hasNext() && !end) { Integer eventType = reader.next(); if (eventType.equals(XMLEvent.START_ELEMENT)) { String name = reader.getLocalName(); if (NODE_COLUMN.equalsIgnoreCase(name)) { String id = reader.getAttributeValue(null, "id"); AttributeColumn column = nodesTable.getColumn(id); if (column != null) { nodeColumns.addAvailableColumn(column); } } else if (EDGE_COLUMN.equalsIgnoreCase(name)) { String id = reader.getAttributeValue(null, "id"); AttributeColumn column = edgesTable.getColumn(id); if (column != null) { edgeColumns.addAvailableColumn(column); } } } else if (eventType.equals(XMLStreamReader.END_ELEMENT)) { if (AVAILABLE_COLUMNS.equalsIgnoreCase(reader.getLocalName())) { end = true; } } } }
private void readDataTablesModel(XMLStreamReader reader, Workspace workspace) throws XMLStreamException { AttributeModel attributeModel = workspace.getLookup().lookup(AttributeModel.class); AttributeTable nodesTable = attributeModel.getNodeTable(); AttributeTable edgesTable = attributeModel.getEdgeTable(); DataTablesModel dataTablesModel = workspace.getLookup().lookup(DataTablesModel.class); if (dataTablesModel == null) { workspace.add(dataTablesModel = new DataTablesModel()); } AvailableColumnsModel nodeColumns = dataTablesModel.getNodeAvailableColumnsModel(); nodeColumns.removeAllColumns(); AvailableColumnsModel edgeColumns = dataTablesModel.getEdgeAvailableColumnsModel(); edgeColumns.removeAllColumns(); boolean end = false; while (reader.hasNext() && !end) { Integer eventType = reader.next(); if (eventType.equals(XMLEvent.START_ELEMENT)) { String name = reader.getLocalName(); if (NODE_COLUMN.equalsIgnoreCase(name)) { Integer id = Integer.parseInt(reader.getAttributeValue(null, "id")); AttributeColumn column = nodesTable.getColumn(id); if (column != null) { nodeColumns.addAvailableColumn(column); } } else if (EDGE_COLUMN.equalsIgnoreCase(name)) { String id = reader.getAttributeValue(null, "id"); AttributeColumn column = edgesTable.getColumn(id); if (column != null) { edgeColumns.addAvailableColumn(column); } } } else if (eventType.equals(XMLStreamReader.END_ELEMENT)) { if (AVAILABLE_COLUMNS.equalsIgnoreCase(reader.getLocalName())) { end = true; } } } }
diff --git a/api/src/main/java/org/jboss/marshalling/reflect/SerializableClass.java b/api/src/main/java/org/jboss/marshalling/reflect/SerializableClass.java index b3f350b..8f9ac3e 100644 --- a/api/src/main/java/org/jboss/marshalling/reflect/SerializableClass.java +++ b/api/src/main/java/org/jboss/marshalling/reflect/SerializableClass.java @@ -1,512 +1,516 @@ /* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.reflect; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.lang.reflect.Field; import java.lang.ref.WeakReference; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.io.ObjectStreamException; import java.io.ObjectStreamField; import java.io.ObjectStreamClass; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; import java.security.AccessController; import java.security.PrivilegedAction; /** * Reflection information about a serializable class. Intended for use by implementations of the Marshalling API. */ public final class SerializableClass { private final WeakReference<Class<?>> subjectRef; private final LazyWeakMethodRef writeObject; private final LazyWeakMethodRef writeReplace; private final LazyWeakMethodRef readObject; private final LazyWeakMethodRef readObjectNoData; private final LazyWeakMethodRef readResolve; private final SerializableField[] fields; private final long effectiveSerialVersionUID; private static final Comparator<? super SerializableField> NAME_COMPARATOR = new Comparator<SerializableField>() { public int compare(final SerializableField o1, final SerializableField o2) { return o1.getName().compareTo(o2.getName()); } }; public static final SerializableField[] NOFIELDS = new SerializableField[0]; SerializableClass(Class<?> subject) { final WeakReference<Class<?>> subjectRef = new WeakReference<Class<?>>(subject); this.subjectRef = subjectRef; writeObject = LazyWeakMethodRef.getInstance(new MethodFinder() { public Method get(Class<?> clazz) { return lookupPrivateMethod(clazz, "writeObject", ObjectOutputStream.class); } }, subjectRef); readObject = LazyWeakMethodRef.getInstance(new MethodFinder() { public Method get(final Class<?> clazz) { return lookupPrivateMethod(clazz, "readObject", ObjectInputStream.class); } }, subjectRef); readObjectNoData = LazyWeakMethodRef.getInstance(new MethodFinder() { public Method get(final Class<?> clazz) { return lookupPrivateMethod(clazz, "readObjectNoData"); } }, subjectRef); writeReplace = LazyWeakMethodRef.getInstance(new MethodFinder() { public Method get(final Class<?> clazz) { return lookupInheritableMethod(clazz, "writeReplace"); } }, subjectRef); readResolve = LazyWeakMethodRef.getInstance(new MethodFinder() { public Method get(final Class<?> clazz) { return lookupInheritableMethod(clazz, "readResolve"); } }, subjectRef); final ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(subject); effectiveSerialVersionUID = objectStreamClass == null ? 0L : objectStreamClass.getSerialVersionUID(); // todo find a better solution fields = getSerializableFields(subject); } private static SerializableField[] getSerializableFields(Class<?> clazz) { final ObjectStreamField[] objectStreamFields = getDeclaredSerialPersistentFields(clazz); if (objectStreamFields != null) { SerializableField[] fields = new SerializableField[objectStreamFields.length]; for (int i = 0; i < objectStreamFields.length; i++) { ObjectStreamField field = objectStreamFields[i]; fields[i] = new SerializableField(clazz, field.getType(), field.getName(), field.isUnshared()); } Arrays.sort(fields, NAME_COMPARATOR); return fields; } // not declared; we'll have to dig through the class's fields final Field[] declaredFields = clazz.getDeclaredFields(); final ArrayList<SerializableField> fields = new ArrayList<SerializableField>(declaredFields.length); for (Field field : declaredFields) { if ((field.getModifiers() & (Modifier.TRANSIENT | Modifier.STATIC)) == 0) { fields.add(new SerializableField(clazz, field.getType(), field.getName(), false)); } } Collections.sort(fields, NAME_COMPARATOR); return fields.toArray(new SerializableField[fields.size()]); } private static ObjectStreamField[] getDeclaredSerialPersistentFields(Class<?> clazz) { final Field field; try { field = clazz.getDeclaredField("serialPersistentFields"); } catch (NoSuchFieldException e) { return null; } if (field == null) { return null; } final int requiredModifiers = Modifier.STATIC | Modifier.PRIVATE | Modifier.FINAL; if ((field.getModifiers() & requiredModifiers) != requiredModifiers) { return null; } field.setAccessible(true); try { return (ObjectStreamField[]) field.get(null); } catch (IllegalAccessException e) { return null; } catch (ClassCastException e) { return null; } } /** * Get the serializable fields of this class. The returned array is a direct reference, so care should be taken * not to modify it. * * @return the fields */ public SerializableField[] getFields() { return fields; } /** * Create a synthetic field for this object class. * * @param name the name of the field * @param fieldType the field type * @param unshared {@code true} if the field should be unshared * @return the field * @throws ClassNotFoundException if a class was not found while looking up the subject class */ public SerializableField getSerializableField(String name, Class<?> fieldType, boolean unshared) throws ClassNotFoundException { return new SerializableField(getSubjectClass(), fieldType, name, unshared); } /** * Determine whether this class has a {@code writeObject()} method. * * @return {@code true} if there is a {@code writeObject()} method */ public boolean hasWriteObject() { return writeObject != null; } /** * Invoke the {@code writeObject()} method for an object. * * @param object the object to invoke on * @param outputStream the object output stream to pass in * @throws IOException if an I/O error occurs */ public void callWriteObject(Object object, ObjectOutputStream outputStream) throws IOException { try { writeObject.getMethod().invoke(object, outputStream); } catch (InvocationTargetException e) { final Throwable te = e.getTargetException(); if (te instanceof IOException) { throw (IOException)te; } else if (te instanceof RuntimeException) { throw (RuntimeException)te; } else if (te instanceof Error) { throw (Error)te; } else { throw new IllegalStateException("Unexpected exception", te); } } catch (ClassNotFoundException e) { throw new IllegalStateException("Class is unexpectedly missing or changed"); } catch (IllegalAccessException e) { throw new IllegalStateException("Method is unexpectedly inaccessible"); } } /** * Determine whether this class has a {@code readObject()} method. * * @return {@code true} if there is a {@code readObject()} method */ public boolean hasReadObject() { return readObject != null; } /** * Invoke the {@code readObject()} method for an object. * * @param object the object to invoke on * @param inputStream the object input stream to pass in * @throws IOException if an I/O error occurs * @throws ClassNotFoundException if a class was not able to be loaded */ public void callReadObject(Object object, ObjectInputStream inputStream) throws IOException, ClassNotFoundException { try { readObject.getMethod().invoke(object, inputStream); } catch (InvocationTargetException e) { final Throwable te = e.getTargetException(); if (te instanceof IOException) { throw (IOException)te; } else if (te instanceof ClassNotFoundException) { throw (ClassNotFoundException)te; } else if (te instanceof RuntimeException) { throw (RuntimeException)te; } else if (te instanceof Error) { throw (Error)te; } else { throw new IllegalStateException("Unexpected exception", te); } } catch (ClassNotFoundException e) { throw new IllegalStateException("Class is unexpectedly missing or changed"); } catch (IllegalAccessException e) { throw new IllegalStateException("Method is unexpectedly inaccessible"); } } /** * Determine whether this class has a {@code readObjectNoData()} method. * * @return {@code true} if there is a {@code readObjectNoData()} method */ public boolean hasReadObjectNoData() { return readObjectNoData != null; } /** * Invoke the {@code readObjectNoData()} method for an object. * * @param object the object to invoke on * @throws ObjectStreamException if an I/O error occurs */ public void callReadObjectNoData(Object object) throws ObjectStreamException { try { readObjectNoData.getMethod().invoke(object); } catch (InvocationTargetException e) { final Throwable te = e.getTargetException(); if (te instanceof ObjectStreamException) { throw (ObjectStreamException)te; } else if (te instanceof RuntimeException) { throw (RuntimeException)te; } else if (te instanceof Error) { throw (Error)te; } else { throw new IllegalStateException("Unexpected exception", te); } } catch (ClassNotFoundException e) { throw new IllegalStateException("Class is unexpectedly missing or changed"); } catch (IllegalAccessException e) { throw new IllegalStateException("Method is unexpectedly inaccessible"); } } /** * Determine whether this class has a {@code writeReplace()} method. * * @return {@code true} if there is a {@code writeReplace()} method */ public boolean hasWriteReplace() { return writeReplace != null; } /** * Invoke the {@code writeReplace()} method for an object. * * @param object the object to invoke on * @return the nominated replacement object * @throws ObjectStreamException if an I/O error occurs */ public Object callWriteReplace(Object object) throws ObjectStreamException { try { return writeReplace.getMethod().invoke(object); } catch (InvocationTargetException e) { final Throwable te = e.getTargetException(); if (te instanceof ObjectStreamException) { throw (ObjectStreamException)te; } else if (te instanceof RuntimeException) { throw (RuntimeException)te; } else if (te instanceof Error) { throw (Error)te; } else { throw new IllegalStateException("Unexpected exception", te); } } catch (ClassNotFoundException e) { throw new IllegalStateException("Class is unexpectedly missing or changed"); } catch (IllegalAccessException e) { throw new IllegalStateException("Method is unexpectedly inaccessible"); } } /** * Determine whether this class has a {@code readResolve()} method. * * @return {@code true} if there is a {@code readResolve()} method */ public boolean hasReadResolve() { return readResolve != null; } /** * Invoke the {@code readResolve()} method for an object. * * @param object the object to invoke on * @return the original object * @throws ObjectStreamException if an I/O error occurs */ public Object callReadResolve(Object object) throws ObjectStreamException { try { return readResolve.getMethod().invoke(object); } catch (InvocationTargetException e) { final Throwable te = e.getTargetException(); if (te instanceof ObjectStreamException) { throw (ObjectStreamException)te; } else if (te instanceof RuntimeException) { throw (RuntimeException)te; } else if (te instanceof Error) { throw (Error)te; } else { throw new IllegalStateException("Unexpected exception", te); } } catch (ClassNotFoundException e) { throw new IllegalStateException("Class is unexpectedly missing or changed"); } catch (IllegalAccessException e) { throw new IllegalStateException("Method is unexpectedly inaccessible"); } } /** * Get the effective serial version UID of this class. * * @return the serial version UID */ public long getEffectiveSerialVersionUID() { return effectiveSerialVersionUID; } /** * Get the {@code Class} of this class. * * @return the subject class * @throws ClassNotFoundException if the class was unloaded */ public Class<?> getSubjectClass() throws ClassNotFoundException { return dereference(subjectRef); } private static Method lookupPrivateMethod(final Class<?> subject, final String name, final Class<?>... params) { return AccessController.doPrivileged(new PrivilegedAction<Method>() { public Method run() { try { final Method method = subject.getDeclaredMethod(name, params); final int modifiers = method.getModifiers(); if ((modifiers & Modifier.PRIVATE) == 0) { // must be private... return null; } else if ((modifiers & Modifier.STATIC) != 0) { // must NOT be static... return null; } else { method.setAccessible(true); return method; } } catch (NoSuchMethodException e) { return null; } } }); } private static Method lookupInheritableMethod(final Class<?> subject, final String name) { return AccessController.doPrivileged(new PrivilegedAction<Method>() { public Method run() { - Class<?> foundClass; + Class<?> foundClass = subject; Method method = null; - for (foundClass = subject; method == null; foundClass = foundClass.getSuperclass()) { + while (method == null) { try { if (foundClass == null) { return null; } method = foundClass.getDeclaredMethod(name); + if (method == null) { + foundClass = foundClass.getSuperclass(); + } } catch (NoSuchMethodException e) { + foundClass = foundClass.getSuperclass(); continue; } } final int modifiers = method.getModifiers(); if ((modifiers & Modifier.STATIC) != 0) { // must NOT be static.. return null; } else if ((modifiers & Modifier.ABSTRACT) != 0) { // must NOT be abstract... return null; } else if ((modifiers & Modifier.PRIVATE) != 0 && foundClass != subject) { // not visible to the actual class return null; } else if ((modifiers & (Modifier.PROTECTED | Modifier.PUBLIC)) != 0 || isSamePackage(foundClass, subject)) { // visible! method.setAccessible(true); return method; } else { // package private, but not the same package return null; } } }); } // the package is the same if the name and classloader are both the same private static boolean isSamePackage(Class<?> a, Class<?> b) { return a.getClassLoader() == b.getClassLoader() && getPackageName(a).equals(getPackageName(b)); } private static String getPackageName(Class<?> c) { String name = c.getName(); // skip array part int idx = name.lastIndexOf('['); if (idx > -1) { // [[[[Lfoo.bar.baz.Blah; // skip [ and also the L name = name.substring(idx + 2); } idx = name.lastIndexOf('.'); if (idx > -1) { // foo.bar.baz.Blah; name = name.substring(0, idx); return name; } else { // no package return ""; } } private interface MethodFinder { Method get(Class<?> clazz); } static Class<?> dereference(final WeakReference<Class<?>> classRef) throws ClassNotFoundException { final Class<?> clazz = classRef.get(); if (clazz == null) { throw new ClassNotFoundException("Class was unloaded"); } return clazz; } private static class LazyWeakMethodRef { private final AtomicReference<WeakReference<Method>> ref; private final MethodFinder finder; private final WeakReference<Class<?>> classRef; private LazyWeakMethodRef(final MethodFinder finder, final Method initial, final WeakReference<Class<?>> classRef) { this.finder = finder; this.classRef = classRef; ref = new AtomicReference<WeakReference<Method>>(new WeakReference<Method>(initial)); } private static LazyWeakMethodRef getInstance(MethodFinder finder, WeakReference<Class<?>> classRef) { final Class<?> clazz = classRef.get(); if (clazz == null) { throw new NullPointerException("clazz is null (no strong reference held to class when serialization info was acquired"); } final Method method = finder.get(clazz); if (method == null) { return null; } return new LazyWeakMethodRef(finder, method, classRef); } private Method getMethod() throws ClassNotFoundException { final WeakReference<Method> weakReference = ref.get(); if (weakReference != null) { final Method method = weakReference.get(); if (method != null) { return method; } } final Class<?> clazz = dereference(classRef); final Method method = finder.get(clazz); if (method == null) { throw new NullPointerException("method is null (was non-null on last check)"); } final WeakReference<Method> newVal = new WeakReference<Method>(method); ref.compareAndSet(weakReference, newVal); return method; } } }
false
true
private static Method lookupInheritableMethod(final Class<?> subject, final String name) { return AccessController.doPrivileged(new PrivilegedAction<Method>() { public Method run() { Class<?> foundClass; Method method = null; for (foundClass = subject; method == null; foundClass = foundClass.getSuperclass()) { try { if (foundClass == null) { return null; } method = foundClass.getDeclaredMethod(name); } catch (NoSuchMethodException e) { continue; } } final int modifiers = method.getModifiers(); if ((modifiers & Modifier.STATIC) != 0) { // must NOT be static.. return null; } else if ((modifiers & Modifier.ABSTRACT) != 0) { // must NOT be abstract... return null; } else if ((modifiers & Modifier.PRIVATE) != 0 && foundClass != subject) { // not visible to the actual class return null; } else if ((modifiers & (Modifier.PROTECTED | Modifier.PUBLIC)) != 0 || isSamePackage(foundClass, subject)) { // visible! method.setAccessible(true); return method; } else { // package private, but not the same package return null; } } }); }
private static Method lookupInheritableMethod(final Class<?> subject, final String name) { return AccessController.doPrivileged(new PrivilegedAction<Method>() { public Method run() { Class<?> foundClass = subject; Method method = null; while (method == null) { try { if (foundClass == null) { return null; } method = foundClass.getDeclaredMethod(name); if (method == null) { foundClass = foundClass.getSuperclass(); } } catch (NoSuchMethodException e) { foundClass = foundClass.getSuperclass(); continue; } } final int modifiers = method.getModifiers(); if ((modifiers & Modifier.STATIC) != 0) { // must NOT be static.. return null; } else if ((modifiers & Modifier.ABSTRACT) != 0) { // must NOT be abstract... return null; } else if ((modifiers & Modifier.PRIVATE) != 0 && foundClass != subject) { // not visible to the actual class return null; } else if ((modifiers & (Modifier.PROTECTED | Modifier.PUBLIC)) != 0 || isSamePackage(foundClass, subject)) { // visible! method.setAccessible(true); return method; } else { // package private, but not the same package return null; } } }); }
diff --git a/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/management/TeachingHoursCDRManagement.java b/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/management/TeachingHoursCDRManagement.java index d4472074..ec85514c 100644 --- a/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/management/TeachingHoursCDRManagement.java +++ b/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/management/TeachingHoursCDRManagement.java @@ -1,332 +1,334 @@ package gr.sch.ira.minoas.seam.components.management; import gr.sch.ira.minoas.model.core.SchoolYear; import gr.sch.ira.minoas.model.core.Unit; import gr.sch.ira.minoas.model.employee.Employee; import gr.sch.ira.minoas.model.employement.Disposal; import gr.sch.ira.minoas.model.employement.Employment; import gr.sch.ira.minoas.model.employement.EmploymentType; import gr.sch.ira.minoas.model.employement.Leave; import gr.sch.ira.minoas.model.employement.Secondment; import gr.sch.ira.minoas.model.employement.ServiceAllocation; import gr.sch.ira.minoas.model.employement.TeachingHourCDR; import gr.sch.ira.minoas.model.employement.TeachingHourCDRType; import gr.sch.ira.minoas.seam.components.BaseDatabaseAwareSeamComponent; import gr.sch.ira.minoas.seam.components.CoreSearching; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collection; import javax.persistence.EntityManager; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.Transactional; @Name(value = "teachingHoursCDRManagement") @Scope(ScopeType.CONVERSATION) public class TeachingHoursCDRManagement extends BaseDatabaseAwareSeamComponent { /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 1L; @In(required = true, create = true) private CoreSearching coreSearching; @Transactional public void doCalculateCurrentCDRs() { long started = System.currentTimeMillis(); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); EntityManager em = getEntityManager(); SchoolYear currentSchoolYear = coreSearching.getActiveSchoolYear(em); info("generating teaching hours CDR for current school year #0", currentSchoolYear); int totalCDRsCreated = 0; /* first fetch all current CDRs and remove them */ Collection<TeachingHourCDR> oldCRDs = coreSearching.getTeachingHoursCDRs(em, currentSchoolYear); int cdrsDeleted = 0; for (TeachingHourCDR cdr : oldCRDs) { entityManager.remove(cdr); cdrsDeleted++; } info("successfully deleted totally #0 old CRD(s).", cdrsDeleted); /* fetch all regular employments */ Collection<Employment> regularEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.REGULAR, currentSchoolYear); for (Employment employment : regularEmployments) { TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT); StringBuffer sb = new StringBuffer(); sb.append("Οργανική θέση στην μονάδα απο τις "); sb.append(df.format(employment.getEstablished())); sb.append(" με υποχρεωτικό ωράριο "); sb.append(employment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(employment.getEmployee()); cdr.setEmployment(employment); cdr.setHours(employment.getFinalWorkingHours()); cdr.setUnit(employment.getSchool()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* fetch all deputy employments */ Collection<Employment> deputyEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.DEPUTY, currentSchoolYear); for (Employment employment : deputyEmployments) { TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT); StringBuffer sb = new StringBuffer(); sb.append("Τοποθέτηση αναπληρωτή στην μονάδα απο τις "); sb.append(df.format(employment.getEstablished())); sb.append(" για "); sb.append(employment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(employment.getEmployee()); cdr.setEmployment(employment); cdr.setHours(employment.getFinalWorkingHours()); cdr.setUnit(employment.getSchool()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* fetch all hourly employments */ Collection<Employment> hourlyEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.HOURLYBASED, currentSchoolYear); for (Employment employment : hourlyEmployments) { TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT); StringBuffer sb = new StringBuffer(); sb.append("Τοποθέτηση ωρομίσθιου στην μονάδα απο τις "); sb.append(df.format(employment.getEstablished())); sb.append(" για "); sb.append(employment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(employment.getEmployee()); cdr.setEmployment(employment); cdr.setHours(employment.getFinalWorkingHours()); cdr.setUnit(employment.getSchool()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* handle secodnments */ Collection<Secondment> secondments = coreSearching.getActiveSecondments(em, currentSchoolYear); for (Secondment secondment : secondments) { /* hack for secondments */ if (secondment.getFinalWorkingHours() != null && secondment.getMandatoryWorkingHours() != null && secondment.getFinalWorkingHours().intValue() == secondment.getMandatoryWorkingHours().intValue()) { /* if final working hour is equal to mandatory working hours then it means * that the valus were copied from the employment */ Integer workingHours = secondment.getFinalWorkingHours(); Employment employment = secondment.getAffectedEmployment(); if (employment != null) { if (employment.getMandatoryWorkingHours().intValue() != workingHours.intValue()) { secondment.setFinalWorkingHours(employment.getMandatoryWorkingHours()); secondment.setMandatoryWorkingHours(employment.getMandatoryWorkingHours()); } } } TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.SECONDMENT); StringBuffer sb = new StringBuffer(); sb.append("Αποσπασμένος απο την μονάδα "); sb.append(secondment.getSourceUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(secondment.getEstablished())); sb.append(" για "); sb.append(secondment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(secondment.getEmployee()); cdr.setSecondment(secondment); cdr.setHours(secondment.getFinalWorkingHours()); cdr.setUnit(secondment.getTargetUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; /* apply on source unit */ cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.SECONDMENT); sb = new StringBuffer(); sb.append("Αποσπασμένος στην μονάδα "); sb.append(secondment.getTargetUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(secondment.getEstablished())); sb.append(" για "); sb.append(secondment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(secondment.getEmployee()); cdr.setSecondment(secondment); cdr.setHours((-1) * secondment.getFinalWorkingHours()); cdr.setUnit(secondment.getSourceUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* handle disposal */ Collection<Disposal> disposals = coreSearching.getActiveDisposal(em, currentSchoolYear); for (Disposal disposal : disposals) { Unit sourceUnit = null; try { sourceUnit = disposal.getAffectedEmployment() != null ? disposal.getAffectedEmployment().getSchool() : disposal.getAffectedSecondment().getTargetUnit(); } catch (Exception ex) { error("unhandled exception with disposal #0. Exception #1", disposal, ex); continue; } TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.DISPOSAL); StringBuffer sb = new StringBuffer(); sb.append("Διάθεση απο την μονάδα "); sb.append(sourceUnit.getTitle()); sb.append(" απο τις "); sb.append(df.format(disposal.getEstablished())); sb.append(" για "); sb.append(disposal.getHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(disposal.getEmployee()); cdr.setDisposal(disposal); cdr.setHours(disposal.getHours()); cdr.setUnit(disposal.getDisposalUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; /* apply on source unit */ cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.DISPOSAL); sb = new StringBuffer(); sb.append("Διάθεση στην μονάδα "); sb.append(disposal.getDisposalUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(disposal.getEstablished())); sb.append(" για "); sb.append(disposal.getHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(disposal.getEmployee()); cdr.setDisposal(disposal); cdr.setHours((-1) * disposal.getHours()); cdr.setUnit(sourceUnit); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* handle service allocation */ Collection<ServiceAllocation> serviceAllocations = coreSearching.getActiveServiceAllocations(em); info("found #0 totally active service allocations.", serviceAllocations.size()); for(ServiceAllocation serviceAllocation : serviceAllocations) { if(serviceAllocation.getSourceUnit()==null) { /* this should never happen */ warn("service allocation #0 has no source unit !!!!!!", serviceAllocation); break; } TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.SERVICE_ALLOCATION); StringBuffer sb = new StringBuffer(); sb.append("Θητεία απο την μονάδα "); sb.append(serviceAllocation.getSourceUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(serviceAllocation.getEstablished())); sb.append(" για "); sb.append(serviceAllocation.getWorkingHoursOnServicingPosition()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(serviceAllocation.getEmployee()); cdr.setServiceAllocation(serviceAllocation); cdr.setHours(serviceAllocation.getWorkingHoursOnServicingPosition()); cdr.setUnit(serviceAllocation.getServiceUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; /* apply on source unit */ cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.SERVICE_ALLOCATION); sb = new StringBuffer(); sb.append("Θητεία στην μονάδα "); sb.append(serviceAllocation.getServiceUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(serviceAllocation.getEstablished())); sb.append(" για "); sb.append(serviceAllocation.getWorkingHoursOnServicingPosition()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(serviceAllocation.getEmployee()); cdr.setServiceAllocation(serviceAllocation); cdr.setHours((-1) * serviceAllocation.getWorkingHoursOnServicingPosition()); cdr.setUnit(serviceAllocation.getSourceUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* WE NEED TO ADD LEAVES */ Collection<Leave> activeLeaves = coreSearching.getActiveLeaves(em); info("found #0 totally active leaves.", activeLeaves.size()); for(Leave activeLeave : activeLeaves) { Employee employeeWithLeave = activeLeave.getEmployee(); /* fix the common leave message */ StringBuffer sb = new StringBuffer(); sb.append("Άδεια τύπου "); sb.append(activeLeave.getLeaveType()); sb.append(" απο τις "); sb.append(df.format(activeLeave.getEstablished())); sb.append(" μέχρι και "); sb.append(df.format(activeLeave.getDueTo())); Collection<TeachingHourCDR> employeeCDRs = coreSearching.getEmployeeTeachingHoursCDRs(em, currentSchoolYear, employeeWithLeave); for(TeachingHourCDR employeeCDR : employeeCDRs) { TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.LEAVE); cdr.setComment(sb.toString()); cdr.setEmployee(employeeWithLeave); cdr.setHours(0); cdr.setSchoolYear(currentSchoolYear); cdr.setUnit(employeeCDR.getUnit()); cdr.setLeave(activeLeave); + entityManager.persist(cdr); + totalCDRsCreated++; } } em.flush(); long finished = System.currentTimeMillis(); info("generated total CDRs #0 after #1 [ms]", totalCDRsCreated, (finished - started)); } }
true
true
public void doCalculateCurrentCDRs() { long started = System.currentTimeMillis(); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); EntityManager em = getEntityManager(); SchoolYear currentSchoolYear = coreSearching.getActiveSchoolYear(em); info("generating teaching hours CDR for current school year #0", currentSchoolYear); int totalCDRsCreated = 0; /* first fetch all current CDRs and remove them */ Collection<TeachingHourCDR> oldCRDs = coreSearching.getTeachingHoursCDRs(em, currentSchoolYear); int cdrsDeleted = 0; for (TeachingHourCDR cdr : oldCRDs) { entityManager.remove(cdr); cdrsDeleted++; } info("successfully deleted totally #0 old CRD(s).", cdrsDeleted); /* fetch all regular employments */ Collection<Employment> regularEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.REGULAR, currentSchoolYear); for (Employment employment : regularEmployments) { TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT); StringBuffer sb = new StringBuffer(); sb.append("Οργανική θέση στην μονάδα απο τις "); sb.append(df.format(employment.getEstablished())); sb.append(" με υποχρεωτικό ωράριο "); sb.append(employment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(employment.getEmployee()); cdr.setEmployment(employment); cdr.setHours(employment.getFinalWorkingHours()); cdr.setUnit(employment.getSchool()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* fetch all deputy employments */ Collection<Employment> deputyEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.DEPUTY, currentSchoolYear); for (Employment employment : deputyEmployments) { TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT); StringBuffer sb = new StringBuffer(); sb.append("Τοποθέτηση αναπληρωτή στην μονάδα απο τις "); sb.append(df.format(employment.getEstablished())); sb.append(" για "); sb.append(employment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(employment.getEmployee()); cdr.setEmployment(employment); cdr.setHours(employment.getFinalWorkingHours()); cdr.setUnit(employment.getSchool()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* fetch all hourly employments */ Collection<Employment> hourlyEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.HOURLYBASED, currentSchoolYear); for (Employment employment : hourlyEmployments) { TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT); StringBuffer sb = new StringBuffer(); sb.append("Τοποθέτηση ωρομίσθιου στην μονάδα απο τις "); sb.append(df.format(employment.getEstablished())); sb.append(" για "); sb.append(employment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(employment.getEmployee()); cdr.setEmployment(employment); cdr.setHours(employment.getFinalWorkingHours()); cdr.setUnit(employment.getSchool()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* handle secodnments */ Collection<Secondment> secondments = coreSearching.getActiveSecondments(em, currentSchoolYear); for (Secondment secondment : secondments) { /* hack for secondments */ if (secondment.getFinalWorkingHours() != null && secondment.getMandatoryWorkingHours() != null && secondment.getFinalWorkingHours().intValue() == secondment.getMandatoryWorkingHours().intValue()) { /* if final working hour is equal to mandatory working hours then it means * that the valus were copied from the employment */ Integer workingHours = secondment.getFinalWorkingHours(); Employment employment = secondment.getAffectedEmployment(); if (employment != null) { if (employment.getMandatoryWorkingHours().intValue() != workingHours.intValue()) { secondment.setFinalWorkingHours(employment.getMandatoryWorkingHours()); secondment.setMandatoryWorkingHours(employment.getMandatoryWorkingHours()); } } } TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.SECONDMENT); StringBuffer sb = new StringBuffer(); sb.append("Αποσπασμένος απο την μονάδα "); sb.append(secondment.getSourceUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(secondment.getEstablished())); sb.append(" για "); sb.append(secondment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(secondment.getEmployee()); cdr.setSecondment(secondment); cdr.setHours(secondment.getFinalWorkingHours()); cdr.setUnit(secondment.getTargetUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; /* apply on source unit */ cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.SECONDMENT); sb = new StringBuffer(); sb.append("Αποσπασμένος στην μονάδα "); sb.append(secondment.getTargetUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(secondment.getEstablished())); sb.append(" για "); sb.append(secondment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(secondment.getEmployee()); cdr.setSecondment(secondment); cdr.setHours((-1) * secondment.getFinalWorkingHours()); cdr.setUnit(secondment.getSourceUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* handle disposal */ Collection<Disposal> disposals = coreSearching.getActiveDisposal(em, currentSchoolYear); for (Disposal disposal : disposals) { Unit sourceUnit = null; try { sourceUnit = disposal.getAffectedEmployment() != null ? disposal.getAffectedEmployment().getSchool() : disposal.getAffectedSecondment().getTargetUnit(); } catch (Exception ex) { error("unhandled exception with disposal #0. Exception #1", disposal, ex); continue; } TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.DISPOSAL); StringBuffer sb = new StringBuffer(); sb.append("Διάθεση απο την μονάδα "); sb.append(sourceUnit.getTitle()); sb.append(" απο τις "); sb.append(df.format(disposal.getEstablished())); sb.append(" για "); sb.append(disposal.getHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(disposal.getEmployee()); cdr.setDisposal(disposal); cdr.setHours(disposal.getHours()); cdr.setUnit(disposal.getDisposalUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; /* apply on source unit */ cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.DISPOSAL); sb = new StringBuffer(); sb.append("Διάθεση στην μονάδα "); sb.append(disposal.getDisposalUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(disposal.getEstablished())); sb.append(" για "); sb.append(disposal.getHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(disposal.getEmployee()); cdr.setDisposal(disposal); cdr.setHours((-1) * disposal.getHours()); cdr.setUnit(sourceUnit); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* handle service allocation */ Collection<ServiceAllocation> serviceAllocations = coreSearching.getActiveServiceAllocations(em); info("found #0 totally active service allocations.", serviceAllocations.size()); for(ServiceAllocation serviceAllocation : serviceAllocations) { if(serviceAllocation.getSourceUnit()==null) { /* this should never happen */ warn("service allocation #0 has no source unit !!!!!!", serviceAllocation); break; } TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.SERVICE_ALLOCATION); StringBuffer sb = new StringBuffer(); sb.append("Θητεία απο την μονάδα "); sb.append(serviceAllocation.getSourceUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(serviceAllocation.getEstablished())); sb.append(" για "); sb.append(serviceAllocation.getWorkingHoursOnServicingPosition()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(serviceAllocation.getEmployee()); cdr.setServiceAllocation(serviceAllocation); cdr.setHours(serviceAllocation.getWorkingHoursOnServicingPosition()); cdr.setUnit(serviceAllocation.getServiceUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; /* apply on source unit */ cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.SERVICE_ALLOCATION); sb = new StringBuffer(); sb.append("Θητεία στην μονάδα "); sb.append(serviceAllocation.getServiceUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(serviceAllocation.getEstablished())); sb.append(" για "); sb.append(serviceAllocation.getWorkingHoursOnServicingPosition()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(serviceAllocation.getEmployee()); cdr.setServiceAllocation(serviceAllocation); cdr.setHours((-1) * serviceAllocation.getWorkingHoursOnServicingPosition()); cdr.setUnit(serviceAllocation.getSourceUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* WE NEED TO ADD LEAVES */ Collection<Leave> activeLeaves = coreSearching.getActiveLeaves(em); info("found #0 totally active leaves.", activeLeaves.size()); for(Leave activeLeave : activeLeaves) { Employee employeeWithLeave = activeLeave.getEmployee(); /* fix the common leave message */ StringBuffer sb = new StringBuffer(); sb.append("Άδεια τύπου "); sb.append(activeLeave.getLeaveType()); sb.append(" απο τις "); sb.append(df.format(activeLeave.getEstablished())); sb.append(" μέχρι και "); sb.append(df.format(activeLeave.getDueTo())); Collection<TeachingHourCDR> employeeCDRs = coreSearching.getEmployeeTeachingHoursCDRs(em, currentSchoolYear, employeeWithLeave); for(TeachingHourCDR employeeCDR : employeeCDRs) { TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.LEAVE); cdr.setComment(sb.toString()); cdr.setEmployee(employeeWithLeave); cdr.setHours(0); cdr.setSchoolYear(currentSchoolYear); cdr.setUnit(employeeCDR.getUnit()); cdr.setLeave(activeLeave); } } em.flush(); long finished = System.currentTimeMillis(); info("generated total CDRs #0 after #1 [ms]", totalCDRsCreated, (finished - started)); }
public void doCalculateCurrentCDRs() { long started = System.currentTimeMillis(); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); EntityManager em = getEntityManager(); SchoolYear currentSchoolYear = coreSearching.getActiveSchoolYear(em); info("generating teaching hours CDR for current school year #0", currentSchoolYear); int totalCDRsCreated = 0; /* first fetch all current CDRs and remove them */ Collection<TeachingHourCDR> oldCRDs = coreSearching.getTeachingHoursCDRs(em, currentSchoolYear); int cdrsDeleted = 0; for (TeachingHourCDR cdr : oldCRDs) { entityManager.remove(cdr); cdrsDeleted++; } info("successfully deleted totally #0 old CRD(s).", cdrsDeleted); /* fetch all regular employments */ Collection<Employment> regularEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.REGULAR, currentSchoolYear); for (Employment employment : regularEmployments) { TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT); StringBuffer sb = new StringBuffer(); sb.append("Οργανική θέση στην μονάδα απο τις "); sb.append(df.format(employment.getEstablished())); sb.append(" με υποχρεωτικό ωράριο "); sb.append(employment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(employment.getEmployee()); cdr.setEmployment(employment); cdr.setHours(employment.getFinalWorkingHours()); cdr.setUnit(employment.getSchool()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* fetch all deputy employments */ Collection<Employment> deputyEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.DEPUTY, currentSchoolYear); for (Employment employment : deputyEmployments) { TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT); StringBuffer sb = new StringBuffer(); sb.append("Τοποθέτηση αναπληρωτή στην μονάδα απο τις "); sb.append(df.format(employment.getEstablished())); sb.append(" για "); sb.append(employment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(employment.getEmployee()); cdr.setEmployment(employment); cdr.setHours(employment.getFinalWorkingHours()); cdr.setUnit(employment.getSchool()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* fetch all hourly employments */ Collection<Employment> hourlyEmployments = coreSearching.getEmploymentsOfType(em, EmploymentType.HOURLYBASED, currentSchoolYear); for (Employment employment : hourlyEmployments) { TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.EMPLOYMENT); StringBuffer sb = new StringBuffer(); sb.append("Τοποθέτηση ωρομίσθιου στην μονάδα απο τις "); sb.append(df.format(employment.getEstablished())); sb.append(" για "); sb.append(employment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(employment.getEmployee()); cdr.setEmployment(employment); cdr.setHours(employment.getFinalWorkingHours()); cdr.setUnit(employment.getSchool()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* handle secodnments */ Collection<Secondment> secondments = coreSearching.getActiveSecondments(em, currentSchoolYear); for (Secondment secondment : secondments) { /* hack for secondments */ if (secondment.getFinalWorkingHours() != null && secondment.getMandatoryWorkingHours() != null && secondment.getFinalWorkingHours().intValue() == secondment.getMandatoryWorkingHours().intValue()) { /* if final working hour is equal to mandatory working hours then it means * that the valus were copied from the employment */ Integer workingHours = secondment.getFinalWorkingHours(); Employment employment = secondment.getAffectedEmployment(); if (employment != null) { if (employment.getMandatoryWorkingHours().intValue() != workingHours.intValue()) { secondment.setFinalWorkingHours(employment.getMandatoryWorkingHours()); secondment.setMandatoryWorkingHours(employment.getMandatoryWorkingHours()); } } } TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.SECONDMENT); StringBuffer sb = new StringBuffer(); sb.append("Αποσπασμένος απο την μονάδα "); sb.append(secondment.getSourceUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(secondment.getEstablished())); sb.append(" για "); sb.append(secondment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(secondment.getEmployee()); cdr.setSecondment(secondment); cdr.setHours(secondment.getFinalWorkingHours()); cdr.setUnit(secondment.getTargetUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; /* apply on source unit */ cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.SECONDMENT); sb = new StringBuffer(); sb.append("Αποσπασμένος στην μονάδα "); sb.append(secondment.getTargetUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(secondment.getEstablished())); sb.append(" για "); sb.append(secondment.getFinalWorkingHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(secondment.getEmployee()); cdr.setSecondment(secondment); cdr.setHours((-1) * secondment.getFinalWorkingHours()); cdr.setUnit(secondment.getSourceUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* handle disposal */ Collection<Disposal> disposals = coreSearching.getActiveDisposal(em, currentSchoolYear); for (Disposal disposal : disposals) { Unit sourceUnit = null; try { sourceUnit = disposal.getAffectedEmployment() != null ? disposal.getAffectedEmployment().getSchool() : disposal.getAffectedSecondment().getTargetUnit(); } catch (Exception ex) { error("unhandled exception with disposal #0. Exception #1", disposal, ex); continue; } TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.DISPOSAL); StringBuffer sb = new StringBuffer(); sb.append("Διάθεση απο την μονάδα "); sb.append(sourceUnit.getTitle()); sb.append(" απο τις "); sb.append(df.format(disposal.getEstablished())); sb.append(" για "); sb.append(disposal.getHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(disposal.getEmployee()); cdr.setDisposal(disposal); cdr.setHours(disposal.getHours()); cdr.setUnit(disposal.getDisposalUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; /* apply on source unit */ cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.DISPOSAL); sb = new StringBuffer(); sb.append("Διάθεση στην μονάδα "); sb.append(disposal.getDisposalUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(disposal.getEstablished())); sb.append(" για "); sb.append(disposal.getHours()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(disposal.getEmployee()); cdr.setDisposal(disposal); cdr.setHours((-1) * disposal.getHours()); cdr.setUnit(sourceUnit); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* handle service allocation */ Collection<ServiceAllocation> serviceAllocations = coreSearching.getActiveServiceAllocations(em); info("found #0 totally active service allocations.", serviceAllocations.size()); for(ServiceAllocation serviceAllocation : serviceAllocations) { if(serviceAllocation.getSourceUnit()==null) { /* this should never happen */ warn("service allocation #0 has no source unit !!!!!!", serviceAllocation); break; } TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.SERVICE_ALLOCATION); StringBuffer sb = new StringBuffer(); sb.append("Θητεία απο την μονάδα "); sb.append(serviceAllocation.getSourceUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(serviceAllocation.getEstablished())); sb.append(" για "); sb.append(serviceAllocation.getWorkingHoursOnServicingPosition()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(serviceAllocation.getEmployee()); cdr.setServiceAllocation(serviceAllocation); cdr.setHours(serviceAllocation.getWorkingHoursOnServicingPosition()); cdr.setUnit(serviceAllocation.getServiceUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; /* apply on source unit */ cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.SERVICE_ALLOCATION); sb = new StringBuffer(); sb.append("Θητεία στην μονάδα "); sb.append(serviceAllocation.getServiceUnit().getTitle()); sb.append(" απο τις "); sb.append(df.format(serviceAllocation.getEstablished())); sb.append(" για "); sb.append(serviceAllocation.getWorkingHoursOnServicingPosition()); sb.append(" ώρες."); cdr.setComment(sb.toString()); cdr.setEmployee(serviceAllocation.getEmployee()); cdr.setServiceAllocation(serviceAllocation); cdr.setHours((-1) * serviceAllocation.getWorkingHoursOnServicingPosition()); cdr.setUnit(serviceAllocation.getSourceUnit()); cdr.setSchoolYear(currentSchoolYear); entityManager.persist(cdr); totalCDRsCreated++; } /* WE NEED TO ADD LEAVES */ Collection<Leave> activeLeaves = coreSearching.getActiveLeaves(em); info("found #0 totally active leaves.", activeLeaves.size()); for(Leave activeLeave : activeLeaves) { Employee employeeWithLeave = activeLeave.getEmployee(); /* fix the common leave message */ StringBuffer sb = new StringBuffer(); sb.append("Άδεια τύπου "); sb.append(activeLeave.getLeaveType()); sb.append(" απο τις "); sb.append(df.format(activeLeave.getEstablished())); sb.append(" μέχρι και "); sb.append(df.format(activeLeave.getDueTo())); Collection<TeachingHourCDR> employeeCDRs = coreSearching.getEmployeeTeachingHoursCDRs(em, currentSchoolYear, employeeWithLeave); for(TeachingHourCDR employeeCDR : employeeCDRs) { TeachingHourCDR cdr = new TeachingHourCDR(); cdr.setCdrType(TeachingHourCDRType.LEAVE); cdr.setComment(sb.toString()); cdr.setEmployee(employeeWithLeave); cdr.setHours(0); cdr.setSchoolYear(currentSchoolYear); cdr.setUnit(employeeCDR.getUnit()); cdr.setLeave(activeLeave); entityManager.persist(cdr); totalCDRsCreated++; } } em.flush(); long finished = System.currentTimeMillis(); info("generated total CDRs #0 after #1 [ms]", totalCDRsCreated, (finished - started)); }
diff --git a/sbia/ch05/src/test/java/com/manning/sbia/ch05/CommandLineJobRunnerTest.java b/sbia/ch05/src/test/java/com/manning/sbia/ch05/CommandLineJobRunnerTest.java index 8ff666e..3a7c31b 100755 --- a/sbia/ch05/src/test/java/com/manning/sbia/ch05/CommandLineJobRunnerTest.java +++ b/sbia/ch05/src/test/java/com/manning/sbia/ch05/CommandLineJobRunnerTest.java @@ -1,69 +1,69 @@ /** * */ package com.manning.sbia.ch05; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import org.junit.Assert; import org.junit.Test; import org.springframework.batch.core.launch.support.CommandLineJobRunner; import org.springframework.batch.core.launch.support.SystemExiter; /** * @author acogoluegnes * */ public class CommandLineJobRunnerTest { - @Test public void run() { + @Test public void run() throws Exception { final Queue<Integer> exitCode = new ArrayBlockingQueue<Integer>(1); CommandLineJobRunner.presetSystemExiter(new SystemExiter() { @Override public void exit(int status) { exitCode.add(status); } }); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob" } ); Assert.assertEquals(0,exitCode.poll().intValue()); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob", "exit.status=COMPLETED" } ); Assert.assertEquals(0,exitCode.poll().intValue()); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob", "exit.status=FAILED" } ); Assert.assertEquals(1,exitCode.poll().intValue()); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob", "exit.status=COMPLETED WITH SKIPS" } ); Assert.assertEquals(3,exitCode.poll().intValue()); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob", "exit.status=ANYTHING" } ); Assert.assertEquals(2,exitCode.poll().intValue()); } }
true
true
@Test public void run() { final Queue<Integer> exitCode = new ArrayBlockingQueue<Integer>(1); CommandLineJobRunner.presetSystemExiter(new SystemExiter() { @Override public void exit(int status) { exitCode.add(status); } }); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob" } ); Assert.assertEquals(0,exitCode.poll().intValue()); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob", "exit.status=COMPLETED" } ); Assert.assertEquals(0,exitCode.poll().intValue()); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob", "exit.status=FAILED" } ); Assert.assertEquals(1,exitCode.poll().intValue()); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob", "exit.status=COMPLETED WITH SKIPS" } ); Assert.assertEquals(3,exitCode.poll().intValue()); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob", "exit.status=ANYTHING" } ); Assert.assertEquals(2,exitCode.poll().intValue()); }
@Test public void run() throws Exception { final Queue<Integer> exitCode = new ArrayBlockingQueue<Integer>(1); CommandLineJobRunner.presetSystemExiter(new SystemExiter() { @Override public void exit(int status) { exitCode.add(status); } }); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob" } ); Assert.assertEquals(0,exitCode.poll().intValue()); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob", "exit.status=COMPLETED" } ); Assert.assertEquals(0,exitCode.poll().intValue()); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob", "exit.status=FAILED" } ); Assert.assertEquals(1,exitCode.poll().intValue()); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob", "exit.status=COMPLETED WITH SKIPS" } ); Assert.assertEquals(3,exitCode.poll().intValue()); CommandLineJobRunner.main(new String[] { "/com/manning/sbia/ch05/import-products-job-exit-code.xml", "importProductsJob", "exit.status=ANYTHING" } ); Assert.assertEquals(2,exitCode.poll().intValue()); }
diff --git a/src/modules/Todo.java b/src/modules/Todo.java index a70d92c..5e73d47 100644 --- a/src/modules/Todo.java +++ b/src/modules/Todo.java @@ -1,243 +1,243 @@ /* Copyright (c) Kenneth Prugh 2012 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 modules; import database.Postgres; import irc.Message; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Todo { private final static Connection db = Postgres.getInstance().getConnection(); private static String selectStatement; private static PreparedStatement prepStmt; private static ResultSet rs; public String parseTodo(final Message m) { // !todo [for target] <msg> String todoString = m.msg.substring(5).trim(); if (todoString.length() == 0) { return getTodo(m); } String target = m.user; if (todoString.startsWith("for ")) { try { target = todoString.split(" ", 3)[1].trim(); String todo = todoString.split(" ", 3)[2]; return newTodo(todo, target); } catch (ArrayIndexOutOfBoundsException e) { return "Invalid input"; } } return newTodo(todoString, target); } private String getTodo(final Message m) { int userid = -1; userid = getUserID(m.user); StringBuilder todo = new StringBuilder(); String selectStatement = "SELECT todo_id,todo FROM todos WHERE user_id = ? "; try { prepStmt = db.prepareStatement(selectStatement); prepStmt.setInt(1, userid); rs = prepStmt.executeQuery(); int todoid = -1; int c = 0; while (rs.next()) { if (c > 0) { todo.append(" | "); } ++c; todoid = rs.getInt(1); todo.append("#"); todo.append(todoid); todo.append(" "); todo.append(rs.getString(2)); } } catch (SQLException e) { e.printStackTrace(); } finally { if (prepStmt != null) { try { prepStmt.close(); } catch (SQLException e) {} } if (rs != null) { try { rs.close(); } catch (SQLException e) {} } } if (todo.length() == 0) { return "You have no todos"; } return todo.toString(); } private String newTodo(String todo, String target) { int userid = getUserID(target); selectStatement = "INSERT INTO todos (todo, user_id) VALUES(?, ?)"; try { prepStmt = db.prepareStatement(selectStatement); prepStmt.setString(1, todo); prepStmt.setInt(2, userid); prepStmt.execute(); } catch (SQLException e) { e.printStackTrace(); return "Error adding todo"; } finally { if (prepStmt != null) { try { prepStmt.close(); } catch (SQLException e) {} } } return "todo added successfully"; } public String deleteTodo(final Message m) { String todoString = m.msg.substring(5).trim(); if (todoString.length() == 0) { return "No todo id specified"; } int userid = getUserID(m.user); int todoid = -1; try { - todoid = Integer.parseInt(todoString.split(" ")[1].trim()); + todoid = Integer.parseInt(todoString.trim()); } catch (ArrayIndexOutOfBoundsException e) { return "Invalid input"; } int todo_user_id = -1; selectStatement = "SELECT user_id FROM todos where todo_id = ?"; try { prepStmt = db.prepareStatement(selectStatement); prepStmt.setInt(1, todoid); rs = prepStmt.executeQuery(); if (rs.next()) { todo_user_id = rs.getInt(1); } } catch (SQLException e) { todo_user_id = -1; } finally { if (prepStmt != null) { try { prepStmt.close(); } catch (SQLException e) {} } } if (userid != todo_user_id) { return "You do not own todo #" + todoid; } selectStatement = "DELETE FROM todos WHERE todo_id = ?"; try { prepStmt = db.prepareStatement(selectStatement); prepStmt.setInt(1, todoid); prepStmt.execute(); } catch (SQLException e) { e.printStackTrace(); return "Error deleting todo"; } finally { if (prepStmt != null) { try { prepStmt.close(); } catch (SQLException e) {} } } return "todo #" + todoid + " deleted"; } private static int getUserID(String user) { int id = -1; selectStatement = "SELECT user_id FROM susers where suser = ?"; try { prepStmt = db.prepareStatement(selectStatement); prepStmt.setString(1, user); rs = prepStmt.executeQuery(); if (rs.next()) { id = rs.getInt(1); } } catch (SQLException e) { id = -1; } finally { if (prepStmt != null) { try { prepStmt.close(); } catch (SQLException e) {} } } if (id == -1) { insertUser(user); return getUserID(user); } return id; } private static void insertUser(String user) { selectStatement = "INSERT INTO susers (suser) VALUES(?)"; try { prepStmt = db.prepareStatement(selectStatement); prepStmt.setString(1, user); prepStmt.execute(); } catch (SQLException e) { } finally { if (prepStmt != null) { try { prepStmt.close(); } catch (SQLException e) {} } } } }
true
true
public String deleteTodo(final Message m) { String todoString = m.msg.substring(5).trim(); if (todoString.length() == 0) { return "No todo id specified"; } int userid = getUserID(m.user); int todoid = -1; try { todoid = Integer.parseInt(todoString.split(" ")[1].trim()); } catch (ArrayIndexOutOfBoundsException e) { return "Invalid input"; } int todo_user_id = -1; selectStatement = "SELECT user_id FROM todos where todo_id = ?"; try { prepStmt = db.prepareStatement(selectStatement); prepStmt.setInt(1, todoid); rs = prepStmt.executeQuery(); if (rs.next()) { todo_user_id = rs.getInt(1); } } catch (SQLException e) { todo_user_id = -1; } finally { if (prepStmt != null) { try { prepStmt.close(); } catch (SQLException e) {} } } if (userid != todo_user_id) { return "You do not own todo #" + todoid; } selectStatement = "DELETE FROM todos WHERE todo_id = ?"; try { prepStmt = db.prepareStatement(selectStatement); prepStmt.setInt(1, todoid); prepStmt.execute(); } catch (SQLException e) { e.printStackTrace(); return "Error deleting todo"; } finally { if (prepStmt != null) { try { prepStmt.close(); } catch (SQLException e) {} } } return "todo #" + todoid + " deleted"; }
public String deleteTodo(final Message m) { String todoString = m.msg.substring(5).trim(); if (todoString.length() == 0) { return "No todo id specified"; } int userid = getUserID(m.user); int todoid = -1; try { todoid = Integer.parseInt(todoString.trim()); } catch (ArrayIndexOutOfBoundsException e) { return "Invalid input"; } int todo_user_id = -1; selectStatement = "SELECT user_id FROM todos where todo_id = ?"; try { prepStmt = db.prepareStatement(selectStatement); prepStmt.setInt(1, todoid); rs = prepStmt.executeQuery(); if (rs.next()) { todo_user_id = rs.getInt(1); } } catch (SQLException e) { todo_user_id = -1; } finally { if (prepStmt != null) { try { prepStmt.close(); } catch (SQLException e) {} } } if (userid != todo_user_id) { return "You do not own todo #" + todoid; } selectStatement = "DELETE FROM todos WHERE todo_id = ?"; try { prepStmt = db.prepareStatement(selectStatement); prepStmt.setInt(1, todoid); prepStmt.execute(); } catch (SQLException e) { e.printStackTrace(); return "Error deleting todo"; } finally { if (prepStmt != null) { try { prepStmt.close(); } catch (SQLException e) {} } } return "todo #" + todoid + " deleted"; }
diff --git a/core/java/android/preference/PreferenceScreen.java b/core/java/android/preference/PreferenceScreen.java index 6ea2528b..95e54324 100644 --- a/core/java/android/preference/PreferenceScreen.java +++ b/core/java/android/preference/PreferenceScreen.java @@ -1,260 +1,260 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.preference; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; /** * Represents a top-level {@link Preference} that * is the root of a Preference hierarchy. A {@link PreferenceActivity} * points to an instance of this class to show the preferences. To instantiate * this class, use {@link PreferenceManager#createPreferenceScreen(Context)}. * <ul> * This class can appear in two places: * <li> When a {@link PreferenceActivity} points to this, it is used as the root * and is not shown (only the contained preferences are shown). * <li> When it appears inside another preference hierarchy, it is shown and * serves as the gateway to another screen of preferences (either by showing * another screen of preferences as a {@link Dialog} or via a * {@link Context#startActivity(android.content.Intent)} from the * {@link Preference#getIntent()}). The children of this {@link PreferenceScreen} * are NOT shown in the screen that this {@link PreferenceScreen} is shown in. * Instead, a separate screen will be shown when this preference is clicked. * </ul> * <p>Here's an example XML layout of a PreferenceScreen:</p> * <pre> &lt;PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:key="first_preferencescreen"&gt; &lt;CheckBoxPreference android:key="wifi enabled" android:title="WiFi" /&gt; &lt;PreferenceScreen android:key="second_preferencescreen" android:title="WiFi settings"&gt; &lt;CheckBoxPreference android:key="prefer wifi" android:title="Prefer WiFi" /&gt; ... other preferences here ... &lt;/PreferenceScreen&gt; &lt;/PreferenceScreen&gt; </pre> * <p> * In this example, the "first_preferencescreen" will be used as the root of the * hierarchy and given to a {@link PreferenceActivity}. The first screen will * show preferences "WiFi" (which can be used to quickly enable/disable WiFi) * and "WiFi settings". The "WiFi settings" is the "second_preferencescreen" and when * clicked will show another screen of preferences such as "Prefer WiFi" (and * the other preferences that are children of the "second_preferencescreen" tag). * * @see PreferenceCategory */ public final class PreferenceScreen extends PreferenceGroup implements AdapterView.OnItemClickListener, DialogInterface.OnDismissListener { private ListAdapter mRootAdapter; private Dialog mDialog; /** * Do NOT use this constructor, use {@link PreferenceManager#createPreferenceScreen(Context)}. * @hide- */ public PreferenceScreen(Context context, AttributeSet attrs) { super(context, attrs, com.android.internal.R.attr.preferenceScreenStyle); } /** * Returns an adapter that can be attached to a {@link PreferenceActivity} * to show the preferences contained in this {@link PreferenceScreen}. * <p> * This {@link PreferenceScreen} will NOT appear in the returned adapter, instead * it appears in the hierarchy above this {@link PreferenceScreen}. * <p> * This adapter's {@link Adapter#getItem(int)} should always return a * subclass of {@link Preference}. * * @return An adapter that provides the {@link Preference} contained in this * {@link PreferenceScreen}. */ public ListAdapter getRootAdapter() { if (mRootAdapter == null) { mRootAdapter = onCreateRootAdapter(); } return mRootAdapter; } /** * Creates the root adapter. * * @return An adapter that contains the preferences contained in this {@link PreferenceScreen}. * @see #getRootAdapter() */ protected ListAdapter onCreateRootAdapter() { return new PreferenceGroupAdapter(this); } /** * Binds a {@link ListView} to the preferences contained in this {@link PreferenceScreen} via * {@link #getRootAdapter()}. It also handles passing list item clicks to the corresponding * {@link Preference} contained by this {@link PreferenceScreen}. * * @param listView The list view to attach to. */ public void bind(ListView listView) { listView.setOnItemClickListener(this); listView.setAdapter(getRootAdapter()); onAttachedToActivity(); } @Override protected void onClick() { if (getIntent() != null || getPreferenceCount() == 0) { return; } showDialog(null); } private void showDialog(Bundle state) { Context context = getContext(); ListView listView = new ListView(context); bind(listView); // Set the title bar if title is available, else no title bar final CharSequence title = getTitle(); - Dialog dialog = mDialog = new Dialog(context, !TextUtils.isEmpty(title) + Dialog dialog = mDialog = new Dialog(context, TextUtils.isEmpty(title) ? com.android.internal.R.style.Theme_NoTitleBar : com.android.internal.R.style.Theme); dialog.setContentView(listView); if (!TextUtils.isEmpty(title)) { dialog.setTitle(title); } dialog.setOnDismissListener(this); if (state != null) { dialog.onRestoreInstanceState(state); } // Add the screen to the list of preferences screens opened as dialogs getPreferenceManager().addPreferencesScreen(dialog); dialog.show(); } public void onDismiss(DialogInterface dialog) { mDialog = null; getPreferenceManager().removePreferencesScreen(dialog); } /** * Used to get a handle to the dialog. * This is useful for cases where we want to manipulate the dialog * as we would with any other activity or view. */ public Dialog getDialog() { return mDialog; } public void onItemClick(AdapterView parent, View view, int position, long id) { Object item = getRootAdapter().getItem(position); if (!(item instanceof Preference)) return; final Preference preference = (Preference) item; preference.performClick(this); } @Override protected boolean isOnSameScreenAsChildren() { return false; } @Override protected Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); final Dialog dialog = mDialog; if (dialog == null || !dialog.isShowing()) { return superState; } final SavedState myState = new SavedState(superState); myState.isDialogShowing = true; myState.dialogBundle = dialog.onSaveInstanceState(); return myState; } @Override protected void onRestoreInstanceState(Parcelable state) { if (state == null || !state.getClass().equals(SavedState.class)) { // Didn't save state for us in onSaveInstanceState super.onRestoreInstanceState(state); return; } SavedState myState = (SavedState) state; super.onRestoreInstanceState(myState.getSuperState()); if (myState.isDialogShowing) { showDialog(myState.dialogBundle); } } private static class SavedState extends BaseSavedState { boolean isDialogShowing; Bundle dialogBundle; public SavedState(Parcel source) { super(source); isDialogShowing = source.readInt() == 1; dialogBundle = source.readBundle(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(isDialogShowing ? 1 : 0); dest.writeBundle(dialogBundle); } public SavedState(Parcelable superState) { super(superState); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
true
true
private void showDialog(Bundle state) { Context context = getContext(); ListView listView = new ListView(context); bind(listView); // Set the title bar if title is available, else no title bar final CharSequence title = getTitle(); Dialog dialog = mDialog = new Dialog(context, !TextUtils.isEmpty(title) ? com.android.internal.R.style.Theme_NoTitleBar : com.android.internal.R.style.Theme); dialog.setContentView(listView); if (!TextUtils.isEmpty(title)) { dialog.setTitle(title); } dialog.setOnDismissListener(this); if (state != null) { dialog.onRestoreInstanceState(state); } // Add the screen to the list of preferences screens opened as dialogs getPreferenceManager().addPreferencesScreen(dialog); dialog.show(); }
private void showDialog(Bundle state) { Context context = getContext(); ListView listView = new ListView(context); bind(listView); // Set the title bar if title is available, else no title bar final CharSequence title = getTitle(); Dialog dialog = mDialog = new Dialog(context, TextUtils.isEmpty(title) ? com.android.internal.R.style.Theme_NoTitleBar : com.android.internal.R.style.Theme); dialog.setContentView(listView); if (!TextUtils.isEmpty(title)) { dialog.setTitle(title); } dialog.setOnDismissListener(this); if (state != null) { dialog.onRestoreInstanceState(state); } // Add the screen to the list of preferences screens opened as dialogs getPreferenceManager().addPreferencesScreen(dialog); dialog.show(); }
diff --git a/parser/org/eclipse/cdt/internal/core/parser/scanner2/ExpressionEvaluator.java b/parser/org/eclipse/cdt/internal/core/parser/scanner2/ExpressionEvaluator.java index 0dd640883..705574c3c 100644 --- a/parser/org/eclipse/cdt/internal/core/parser/scanner2/ExpressionEvaluator.java +++ b/parser/org/eclipse/cdt/internal/core/parser/scanner2/ExpressionEvaluator.java @@ -1,1078 +1,1084 @@ /******************************************************************************* * Copyright (c) 2004, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial implementation * Markus Schorn (Wind River Systems) * Bryan Wilkinson (QNX) - https://bugs.eclipse.org/bugs/show_bug.cgi?id=151207 * Anton Leherbauer (Wind River Systems) *******************************************************************************/ package org.eclipse.cdt.internal.core.parser.scanner2; import org.eclipse.cdt.core.parser.IProblem; import org.eclipse.cdt.core.parser.util.CharArrayObjectMap; import org.eclipse.cdt.core.parser.util.CharArrayUtils; import org.eclipse.cdt.internal.core.parser.scanner2.BaseScanner.MacroData; public class ExpressionEvaluator { private static char[] emptyCharArray = new char[0]; // The context stack private static final int initSize = 8; private int bufferStackPos = -1; private char[][] bufferStack = new char[initSize][]; private Object[] bufferData = new Object[initSize]; private int[] bufferPos = new int[initSize]; private int[] bufferLimit = new int[initSize]; private ScannerCallbackManager callbackManager = null; private ScannerProblemFactory problemFactory = null; private int lineNumber = 1; private char[] fileName = null; private int pos = 0; // The macros CharArrayObjectMap definitions; public ExpressionEvaluator() { super(); } public ExpressionEvaluator(ScannerCallbackManager manager, ScannerProblemFactory spf) { this.callbackManager = manager; this.problemFactory = spf; } public long evaluate(char[] buffer, int p, int length, CharArrayObjectMap defs) { return evaluate(buffer, p, length, defs, 0, "".toCharArray()); //$NON-NLS-1$ } public long evaluate(char[] buffer, int p, int length, CharArrayObjectMap defs, int ln, char[] fn) { this.lineNumber = ln; this.fileName = fn; bufferStack[++bufferStackPos] = buffer; bufferPos[bufferStackPos] = p - 1; bufferLimit[bufferStackPos] = p + length; this.definitions = defs; tokenType = 0; long r = 0; try { r = expression(); } catch (ExpressionEvaluator.EvalException e) { } while (bufferStackPos >= 0) popContext(); return r; } private static class EvalException extends Exception { private static final long serialVersionUID = 0; public EvalException(String msg) { super(msg); } } private long expression() throws EvalException { return conditionalExpression(); } private long conditionalExpression() throws EvalException { long r1 = logicalOrExpression(); if (LA() == tQUESTION) { consume(); long r2 = expression(); if (LA() == tCOLON) consume(); else { handleProblem(IProblem.SCANNER_BAD_CONDITIONAL_EXPRESSION, pos); throw new EvalException("bad conditional expression"); //$NON-NLS-1$ } long r3 = conditionalExpression(); return r1 != 0 ? r2 : r3; } return r1; } private long logicalOrExpression() throws EvalException { long r1 = logicalAndExpression(); while (LA() == tOR) { consume(); long r2 = logicalAndExpression(); r1 = ((r1 != 0) || (r2 != 0)) ? 1 : 0; } return r1; } private long logicalAndExpression() throws EvalException { long r1 = inclusiveOrExpression(); while (LA() == tAND) { consume(); long r2 = inclusiveOrExpression(); r1 = ((r1 != 0) && (r2 != 0)) ? 1 : 0; } return r1; } private long inclusiveOrExpression() throws EvalException { long r1 = exclusiveOrExpression(); while (LA() == tBITOR) { consume(); long r2 = exclusiveOrExpression(); r1 = r1 | r2; } return r1; } private long exclusiveOrExpression() throws EvalException { long r1 = andExpression(); while (LA() == tBITXOR) { consume(); long r2 = andExpression(); r1 = r1 ^ r2; } return r1; } private long andExpression() throws EvalException { long r1 = equalityExpression(); while (LA() == tBITAND) { consume(); long r2 = equalityExpression(); r1 = r1 & r2; } return r1; } private long equalityExpression() throws EvalException { long r1 = relationalExpression(); for (int t = LA(); t == tEQUAL || t == tNOTEQUAL; t = LA()) { consume(); long r2 = relationalExpression(); if (t == tEQUAL) r1 = (r1 == r2) ? 1 : 0; else // t == tNOTEQUAL r1 = (r1 != r2) ? 1 : 0; } return r1; } private long relationalExpression() throws EvalException { long r1 = shiftExpression(); for (int t = LA(); t == tLT || t == tLTEQUAL || t == tGT || t == tGTEQUAL; t = LA()) { consume(); long r2 = shiftExpression(); switch (t) { case tLT: r1 = (r1 < r2) ? 1 : 0; break; case tLTEQUAL: r1 = (r1 <= r2) ? 1 : 0; break; case tGT: r1 = (r1 > r2) ? 1 : 0; break; case tGTEQUAL: r1 = (r1 >= r2) ? 1 : 0; break; } } return r1; } private long shiftExpression() throws EvalException { long r1 = additiveExpression(); for (int t = LA(); t == tSHIFTL || t == tSHIFTR; t = LA()) { consume(); long r2 = additiveExpression(); if (t == tSHIFTL) r1 = r1 << r2; else // t == tSHIFTR r1 = r1 >> r2; } return r1; } private long additiveExpression() throws EvalException { long r1 = multiplicativeExpression(); for (int t = LA(); t == tPLUS || t == tMINUS; t = LA()) { consume(); long r2 = multiplicativeExpression(); if (t == tPLUS) r1 = r1 + r2; else // t == tMINUS r1 = r1 - r2; } return r1; } private long multiplicativeExpression() throws EvalException { long r1 = unaryExpression(); for (int t = LA(); t == tMULT || t == tDIV || t == tMOD; t = LA()) { int position = pos; // for IProblem /0 below, need position // before // consume() consume(); long r2 = unaryExpression(); if (t == tMULT) r1 = r1 * r2; else if (r2 != 0) { if (t == tDIV) r1 = r1 / r2; else r1 = r1 % r2; //tMOD } else { handleProblem(IProblem.SCANNER_DIVIDE_BY_ZERO, position); throw new EvalException("Divide by 0 encountered"); //$NON-NLS-1$ } } return r1; } private long unaryExpression() throws EvalException { switch (LA()) { case tPLUS: consume(); return unaryExpression(); case tMINUS: consume(); return -unaryExpression(); case tNOT: consume(); return unaryExpression() == 0 ? 1 : 0; case tCOMPL: consume(); return ~unaryExpression(); case tNUMBER: return consume(); case t_defined: return handleDefined(); case tLPAREN: consume(); long r1 = expression(); if (LA() == tRPAREN) { consume(); return r1; } handleProblem(IProblem.SCANNER_MISSING_R_PAREN, pos); throw new EvalException("missing )"); //$NON-NLS-1$ case tCHAR: return getChar(); default: handleProblem(IProblem.SCANNER_EXPRESSION_SYNTAX_ERROR, pos); throw new EvalException("expression syntax error"); //$NON-NLS-1$ } } private long handleDefined() throws EvalException { // We need to do some special handline to get the identifier without // it // being // expanded by macro expansion skipWhiteSpace(); char[] buffer = bufferStack[bufferStackPos]; int limit = bufferLimit[bufferStackPos]; if (++bufferPos[bufferStackPos] >= limit) return 0; // check first character char c = buffer[bufferPos[bufferStackPos]]; boolean inParens = false; if (c == '(') { inParens = true; skipWhiteSpace(); if (++bufferPos[bufferStackPos] >= limit) return 0; c = buffer[bufferPos[bufferStackPos]]; } if (!((c >= 'A' && c <= 'Z') || c == '_' || (c >= 'a' && c <= 'z'))) { handleProblem(IProblem.SCANNER_ILLEGAL_IDENTIFIER, pos); throw new EvalException("illegal identifier in defined()"); //$NON-NLS-1$ } // consume rest of identifier int idstart = bufferPos[bufferStackPos]; int idlen = 1; while (++bufferPos[bufferStackPos] < limit) { c = buffer[bufferPos[bufferStackPos]]; if ((c >= 'A' && c <= 'Z') || c == '_' || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) { ++idlen; continue; } break; } --bufferPos[bufferStackPos]; // consume to the closing paren; if (inParens) { skipWhiteSpace(); if (++bufferPos[bufferStackPos] <= limit && buffer[bufferPos[bufferStackPos]] != ')') { handleProblem(IProblem.SCANNER_MISSING_R_PAREN, pos); throw new EvalException("missing ) on defined"); //$NON-NLS-1$ } } // Set up the lookahead to whatever comes next nextToken(); return definitions.get(buffer, idstart, idlen) != null ? 1 : 0; } // Scanner part int tokenType = tNULL; long tokenValue; private int LA() throws EvalException { if (tokenType == tNULL) nextToken(); return tokenType; } private long consume() throws EvalException { long value = tokenValue; if (tokenType != tEOF) nextToken(); return value; } private long getChar() throws EvalException { long value = 0; // if getting a character then make sure it's in '' otherwise leave // it // as 0 if (bufferPos[bufferStackPos] - 1 >= 0 && bufferPos[bufferStackPos] + 1 < bufferStack[bufferStackPos].length && bufferStack[bufferStackPos][bufferPos[bufferStackPos] - 1] == '\'' && bufferStack[bufferStackPos][bufferPos[bufferStackPos] + 1] == '\'') value = bufferStack[bufferStackPos][bufferPos[bufferStackPos]]; if (tokenType != tEOF) nextToken(); return value; } private static char[] _defined = "defined".toCharArray(); //$NON-NLS-1$ private void nextToken() throws EvalException { boolean isHex = false; boolean isOctal = false; boolean isDecimal = false; contextLoop: while (bufferStackPos >= 0) { // Find the first thing we would care about skipWhiteSpace(); while (++bufferPos[bufferStackPos] >= bufferLimit[bufferStackPos]) { // We're at the end of a context, pop it off and try again popContext(); continue contextLoop; } // Tokens don't span buffers, stick to our current one char[] buffer = bufferStack[bufferStackPos]; int limit = bufferLimit[bufferStackPos]; pos = bufferPos[bufferStackPos]; if (buffer[pos] >= '1' && buffer[pos] <= '9') isDecimal = true; else if (buffer[pos] == '0' && pos + 1 < limit) if (buffer[pos + 1] == 'x' || buffer[pos + 1] == 'X') { isHex = true; ++bufferPos[bufferStackPos]; if (pos + 2 < limit) if ((buffer[pos + 2] < '0' || buffer[pos + 2] > '9') && (buffer[pos + 2] < 'a' || buffer[pos + 2] > 'f') && (buffer[pos + 2] < 'A' || buffer[pos + 2] > 'F')) handleProblem(IProblem.SCANNER_BAD_HEX_FORMAT, pos); } else isOctal = true; switch (buffer[pos]) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': int start = bufferPos[bufferStackPos]; int len = 1; while (++bufferPos[bufferStackPos] < limit) { char c = buffer[bufferPos[bufferStackPos]]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) { ++len; continue; } break; } --bufferPos[bufferStackPos]; // Check for defined( pos = bufferPos[bufferStackPos]; if (CharArrayUtils.equals(buffer, start, len, _defined)) { tokenType = t_defined; return; } // Check for macro expansion Object expObject = null; if (bufferData[bufferStackPos] instanceof FunctionStyleMacro.Expansion) { // first check if name is a macro arg expObject = ((FunctionStyleMacro.Expansion) bufferData[bufferStackPos]).definitions .get(buffer, start, len); } if (expObject == null) // now check regular macros expObject = definitions.get(buffer, start, len); if (expObject != null) { if (expObject instanceof FunctionStyleMacro) { handleFunctionStyleMacro((FunctionStyleMacro) expObject); } else if (expObject instanceof ObjectStyleMacro) { ObjectStyleMacro expMacro = (ObjectStyleMacro) expObject; char[] expText = expMacro.getExpansion(); if (expText.length > 0 ) { if (BaseScanner.shouldExpandMacro(expMacro, bufferStackPos, bufferData, -1, bufferPos, bufferStack )) pushContext(expText, new MacroData(start, start + len, expMacro)); else { if (len == 1) { // is a character tokenType = tCHAR; return; } // undefined macro, assume 0 tokenValue = 0; tokenType = tNUMBER; return; } } } else if (expObject instanceof char[]) { char[] expText = (char[]) expObject; if (expText.length > 0) pushContext(expText, null); } continue; } if (len == 1) { // is a character tokenType = tCHAR; return; } // undefined macro, assume 0 tokenValue = 0; tokenType = tNUMBER; return; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': tokenValue = buffer[pos] - '0'; tokenType = tNUMBER; while (++bufferPos[bufferStackPos] < limit) { char c = buffer[bufferPos[bufferStackPos]]; if (isHex) { if (c >= '0' && c <= '9') { tokenValue *= 16; tokenValue += c - '0'; continue; } else if (c >= 'a' && c <= 'f') { tokenValue = (tokenValue == 0 ? 10 : (tokenValue * 16) + 10); tokenValue += c - 'a'; continue; } else if (c >= 'A' && c <= 'F') { tokenValue = (tokenValue == 0 ? 10 : (tokenValue * 16) + 10); tokenValue += c - 'A'; continue; } else { if (bufferPos[bufferStackPos] + 1 < limit) if (!isValidTokenSeparator( c, buffer[bufferPos[bufferStackPos] + 1])) handleProblem( IProblem.SCANNER_BAD_HEX_FORMAT, pos); } } else if (isOctal) { if (c >= '0' && c <= '7') { tokenValue *= 8; tokenValue += c - '0'; continue; } if (bufferPos[bufferStackPos] + 1 < limit) if (!isValidTokenSeparator(c, buffer[bufferPos[bufferStackPos] + 1])) handleProblem( IProblem.SCANNER_BAD_OCTAL_FORMAT, pos); } else if (isDecimal) { if (c >= '0' && c <= '9') { tokenValue *= 10; tokenValue += c - '0'; continue; } if (bufferPos[bufferStackPos] + 1 < limit && !(c == 'L' || c == 'l' || c == 'U' || c == 'u')) if (!isValidTokenSeparator(c, buffer[bufferPos[bufferStackPos] + 1])) handleProblem( IProblem.SCANNER_BAD_DECIMAL_FORMAT, pos); } // end of number if (c == 'L' || c == 'l' || c == 'U' || c == 'u') { // eat the long/unsigned - ++bufferPos[bufferStackPos]; + int pos= ++bufferPos[bufferStackPos]; + if (pos < limit) { + c= buffer[pos]; + if (c == 'L' || c == 'l' || c == 'U' || c == 'u') { + ++bufferPos[bufferStackPos]; + } + } } // done break; } --bufferPos[bufferStackPos]; return; case '(': tokenType = tLPAREN; return; case ')': tokenType = tRPAREN; return; case ':': tokenType = tCOLON; return; case '?': tokenType = tQUESTION; return; case '+': tokenType = tPLUS; return; case '-': tokenType = tMINUS; return; case '*': tokenType = tMULT; return; case '/': tokenType = tDIV; return; case '%': tokenType = tMOD; return; case '^': tokenType = tBITXOR; return; case '&': if (pos + 1 < limit && buffer[pos + 1] == '&') { ++bufferPos[bufferStackPos]; tokenType = tAND; return; } tokenType = tBITAND; return; case '|': if (pos + 1 < limit && buffer[pos + 1] == '|') { ++bufferPos[bufferStackPos]; tokenType = tOR; return; } tokenType = tBITOR; return; case '~': tokenType = tCOMPL; return; case '!': if (pos + 1 < limit && buffer[pos + 1] == '=') { ++bufferPos[bufferStackPos]; tokenType = tNOTEQUAL; return; } tokenType = tNOT; return; case '=': if (pos + 1 < limit && buffer[pos + 1] == '=') { ++bufferPos[bufferStackPos]; tokenType = tEQUAL; return; } handleProblem(IProblem.SCANNER_ASSIGNMENT_NOT_ALLOWED, pos); throw new EvalException("assignment not allowed"); //$NON-NLS-1$ case '<': if (pos + 1 < limit) { if (buffer[pos + 1] == '=') { ++bufferPos[bufferStackPos]; tokenType = tLTEQUAL; return; } else if (buffer[pos + 1] == '<') { ++bufferPos[bufferStackPos]; tokenType = tSHIFTL; return; } } tokenType = tLT; return; case '>': if (pos + 1 < limit) { if (buffer[pos + 1] == '=') { ++bufferPos[bufferStackPos]; tokenType = tGTEQUAL; return; } else if (buffer[pos + 1] == '>') { ++bufferPos[bufferStackPos]; tokenType = tSHIFTR; return; } } tokenType = tGT; return; default: // skip over anything we don't handle } } // We've run out of contexts, our work is done here tokenType = tEOF; return; } private void handleFunctionStyleMacro(FunctionStyleMacro macro) { char[] buffer = bufferStack[bufferStackPos]; int limit = bufferLimit[bufferStackPos]; skipWhiteSpace(); if (++bufferPos[bufferStackPos] >= limit || buffer[bufferPos[bufferStackPos]] != '(') return; FunctionStyleMacro.Expansion exp = macro.new Expansion(); char[][] arglist = macro.arglist; int currarg = -1; int parens = 0; while (bufferPos[bufferStackPos] < limit) { if (++currarg >= arglist.length || arglist[currarg] == null) // too many args break; skipWhiteSpace(); int p = ++bufferPos[bufferStackPos]; char c = buffer[p]; if (c == ')') { if (parens == 0) // end of macro break; --parens; continue; } else if (c == ',') { // empty arg exp.definitions.put(arglist[currarg], emptyCharArray); continue; } else if (c == '(') { ++parens; continue; } // peel off the arg int argstart = p; int argend = argstart - 1; // Loop looking for end of argument while (bufferPos[bufferStackPos] < limit) { skipOverMacroArg(); argend = bufferPos[bufferStackPos]; skipWhiteSpace(); if (++bufferPos[bufferStackPos] >= limit) break; c = buffer[bufferPos[bufferStackPos]]; if (c == ',' || c == ')') break; } char[] arg = emptyCharArray; int arglen = argend - argstart + 1; if (arglen > 0) { arg = new char[arglen]; System.arraycopy(buffer, argstart, arg, 0, arglen); } exp.definitions.put(arglist[currarg], arg); if (c == ')') break; } char[] expText = macro.getExpansion(); if (expText.length > 0) pushContext(expText, exp); } private void skipOverMacroArg() { char[] buffer = bufferStack[bufferStackPos]; int limit = bufferLimit[bufferStackPos]; while (++bufferPos[bufferStackPos] < limit) { switch (buffer[bufferPos[bufferStackPos]]) { case ' ': case '\t': case '\r': case ',': case ')': --bufferPos[bufferStackPos]; return; case '\n': lineNumber++; --bufferPos[bufferStackPos]; return; case '\\': int p = bufferPos[bufferStackPos]; if (p + 1 < limit && buffer[p + 1] == '\n') { // \n is whitespace lineNumber++; --bufferPos[bufferStackPos]; return; } break; case '"': boolean escaped = false; loop: while (++bufferPos[bufferStackPos] < bufferLimit[bufferStackPos]) { switch (buffer[bufferPos[bufferStackPos]]) { case '\\': escaped = !escaped; continue; case '"': if (escaped) { escaped = false; continue; } break loop; default: escaped = false; } } break; } } --bufferPos[bufferStackPos]; } private void skipWhiteSpace() { char[] buffer = bufferStack[bufferStackPos]; int limit = bufferLimit[bufferStackPos]; while (++bufferPos[bufferStackPos] < limit) { int p = bufferPos[bufferStackPos]; switch (buffer[p]) { case ' ': case '\t': case '\r': continue; case '/': if (p + 1 < limit) { if (buffer[p + 1] == '/') { // C++ comment, skip rest of line for (bufferPos[bufferStackPos] += 2; bufferPos[bufferStackPos] < limit; ++bufferPos[bufferStackPos]) { p = bufferPos[bufferStackPos]; if (buffer[p] == '\\' && p + 1 < limit && buffer[p + 1] == '\n') { bufferPos[bufferStackPos] += 2; continue; } if (buffer[p] == '\\' && p + 1 < limit && buffer[p + 1] == '\r' && p + 2 < limit && buffer[p + 2] == '\n') { bufferPos[bufferStackPos] += 3; continue; } if (buffer[p] == '\n') break; // break when find non-escaped // newline } continue; } else if (buffer[p + 1] == '*') { // C comment, find // closing */ for (bufferPos[bufferStackPos] += 2; bufferPos[bufferStackPos] < limit; ++bufferPos[bufferStackPos]) { p = bufferPos[bufferStackPos]; if (buffer[p] == '*' && p + 1 < limit && buffer[p + 1] == '/') { ++bufferPos[bufferStackPos]; break; } } continue; } } break; case '\\': if (p + 1 < limit && buffer[p + 1] == '\n') { // \n is a whitespace lineNumber++; ++bufferPos[bufferStackPos]; continue; } } // fell out of switch without continuing, we're done --bufferPos[bufferStackPos]; return; } // fell out of while without continuing, we're done --bufferPos[bufferStackPos]; return; } private static final int tNULL = 0; private static final int tEOF = 1; private static final int tNUMBER = 2; private static final int tLPAREN = 3; private static final int tRPAREN = 4; private static final int tNOT = 5; private static final int tCOMPL = 6; private static final int tMULT = 7; private static final int tDIV = 8; private static final int tMOD = 9; private static final int tPLUS = 10; private static final int tMINUS = 11; private static final int tSHIFTL = 12; private static final int tSHIFTR = 13; private static final int tLT = 14; private static final int tGT = 15; private static final int tLTEQUAL = 16; private static final int tGTEQUAL = 17; private static final int tEQUAL = 18; private static final int tNOTEQUAL = 19; private static final int tBITAND = 20; private static final int tBITXOR = 21; private static final int tBITOR = 22; private static final int tAND = 23; private static final int tOR = 24; private static final int tQUESTION = 25; private static final int tCOLON = 26; private static final int t_defined = 27; private static final int tCHAR = 28; private void pushContext(char[] buffer, Object data) { if (++bufferStackPos == bufferStack.length) { int size = bufferStack.length * 2; char[][] oldBufferStack = bufferStack; bufferStack = new char[size][]; System.arraycopy(oldBufferStack, 0, bufferStack, 0, oldBufferStack.length); Object[] oldBufferData = bufferData; bufferData = new Object[size]; System.arraycopy(oldBufferData, 0, bufferData, 0, oldBufferData.length); int[] oldBufferPos = bufferPos; bufferPos = new int[size]; System.arraycopy(oldBufferPos, 0, bufferPos, 0, oldBufferPos.length); int[] oldBufferLimit = bufferLimit; bufferLimit = new int[size]; System.arraycopy(oldBufferLimit, 0, bufferLimit, 0, oldBufferLimit.length); } bufferStack[bufferStackPos] = buffer; bufferPos[bufferStackPos] = -1; bufferLimit[bufferStackPos] = buffer.length; bufferData[bufferStackPos] = data; } private void popContext() { bufferStack[bufferStackPos] = null; bufferData[bufferStackPos] = null; --bufferStackPos; } private void handleProblem(int id, int startOffset) { if (callbackManager != null && problemFactory != null) callbackManager .pushCallback(problemFactory .createProblem( id, startOffset, bufferPos[(bufferStackPos == -1 ? 0 : bufferStackPos)], lineNumber, (fileName == null ? "".toCharArray() : fileName), emptyCharArray, false, true)); //$NON-NLS-1$ } private boolean isValidTokenSeparator(char c, char c2) throws EvalException { switch (c) { case '\t': case '\r': case '\n': case ' ': case '(': case ')': case ':': case '?': case '+': case '-': case '*': case '/': case '%': case '^': case '&': case '|': case '~': case '!': case '<': case '>': return true; case '=': if (c2 == '=') return true; return false; } return false; } }
true
true
private void nextToken() throws EvalException { boolean isHex = false; boolean isOctal = false; boolean isDecimal = false; contextLoop: while (bufferStackPos >= 0) { // Find the first thing we would care about skipWhiteSpace(); while (++bufferPos[bufferStackPos] >= bufferLimit[bufferStackPos]) { // We're at the end of a context, pop it off and try again popContext(); continue contextLoop; } // Tokens don't span buffers, stick to our current one char[] buffer = bufferStack[bufferStackPos]; int limit = bufferLimit[bufferStackPos]; pos = bufferPos[bufferStackPos]; if (buffer[pos] >= '1' && buffer[pos] <= '9') isDecimal = true; else if (buffer[pos] == '0' && pos + 1 < limit) if (buffer[pos + 1] == 'x' || buffer[pos + 1] == 'X') { isHex = true; ++bufferPos[bufferStackPos]; if (pos + 2 < limit) if ((buffer[pos + 2] < '0' || buffer[pos + 2] > '9') && (buffer[pos + 2] < 'a' || buffer[pos + 2] > 'f') && (buffer[pos + 2] < 'A' || buffer[pos + 2] > 'F')) handleProblem(IProblem.SCANNER_BAD_HEX_FORMAT, pos); } else isOctal = true; switch (buffer[pos]) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': int start = bufferPos[bufferStackPos]; int len = 1; while (++bufferPos[bufferStackPos] < limit) { char c = buffer[bufferPos[bufferStackPos]]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) { ++len; continue; } break; } --bufferPos[bufferStackPos]; // Check for defined( pos = bufferPos[bufferStackPos]; if (CharArrayUtils.equals(buffer, start, len, _defined)) { tokenType = t_defined; return; } // Check for macro expansion Object expObject = null; if (bufferData[bufferStackPos] instanceof FunctionStyleMacro.Expansion) { // first check if name is a macro arg expObject = ((FunctionStyleMacro.Expansion) bufferData[bufferStackPos]).definitions .get(buffer, start, len); } if (expObject == null) // now check regular macros expObject = definitions.get(buffer, start, len); if (expObject != null) { if (expObject instanceof FunctionStyleMacro) { handleFunctionStyleMacro((FunctionStyleMacro) expObject); } else if (expObject instanceof ObjectStyleMacro) { ObjectStyleMacro expMacro = (ObjectStyleMacro) expObject; char[] expText = expMacro.getExpansion(); if (expText.length > 0 ) { if (BaseScanner.shouldExpandMacro(expMacro, bufferStackPos, bufferData, -1, bufferPos, bufferStack )) pushContext(expText, new MacroData(start, start + len, expMacro)); else { if (len == 1) { // is a character tokenType = tCHAR; return; } // undefined macro, assume 0 tokenValue = 0; tokenType = tNUMBER; return; } } } else if (expObject instanceof char[]) { char[] expText = (char[]) expObject; if (expText.length > 0) pushContext(expText, null); } continue; } if (len == 1) { // is a character tokenType = tCHAR; return; } // undefined macro, assume 0 tokenValue = 0; tokenType = tNUMBER; return; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': tokenValue = buffer[pos] - '0'; tokenType = tNUMBER; while (++bufferPos[bufferStackPos] < limit) { char c = buffer[bufferPos[bufferStackPos]]; if (isHex) { if (c >= '0' && c <= '9') { tokenValue *= 16; tokenValue += c - '0'; continue; } else if (c >= 'a' && c <= 'f') { tokenValue = (tokenValue == 0 ? 10 : (tokenValue * 16) + 10); tokenValue += c - 'a'; continue; } else if (c >= 'A' && c <= 'F') { tokenValue = (tokenValue == 0 ? 10 : (tokenValue * 16) + 10); tokenValue += c - 'A'; continue; } else { if (bufferPos[bufferStackPos] + 1 < limit) if (!isValidTokenSeparator( c, buffer[bufferPos[bufferStackPos] + 1])) handleProblem( IProblem.SCANNER_BAD_HEX_FORMAT, pos); } } else if (isOctal) { if (c >= '0' && c <= '7') { tokenValue *= 8; tokenValue += c - '0'; continue; } if (bufferPos[bufferStackPos] + 1 < limit) if (!isValidTokenSeparator(c, buffer[bufferPos[bufferStackPos] + 1])) handleProblem( IProblem.SCANNER_BAD_OCTAL_FORMAT, pos); } else if (isDecimal) { if (c >= '0' && c <= '9') { tokenValue *= 10; tokenValue += c - '0'; continue; } if (bufferPos[bufferStackPos] + 1 < limit && !(c == 'L' || c == 'l' || c == 'U' || c == 'u')) if (!isValidTokenSeparator(c, buffer[bufferPos[bufferStackPos] + 1])) handleProblem( IProblem.SCANNER_BAD_DECIMAL_FORMAT, pos); } // end of number if (c == 'L' || c == 'l' || c == 'U' || c == 'u') { // eat the long/unsigned ++bufferPos[bufferStackPos]; } // done break; } --bufferPos[bufferStackPos]; return; case '(': tokenType = tLPAREN; return; case ')': tokenType = tRPAREN; return; case ':': tokenType = tCOLON; return; case '?': tokenType = tQUESTION; return; case '+': tokenType = tPLUS; return; case '-': tokenType = tMINUS; return; case '*': tokenType = tMULT; return; case '/': tokenType = tDIV; return; case '%': tokenType = tMOD; return; case '^': tokenType = tBITXOR; return; case '&': if (pos + 1 < limit && buffer[pos + 1] == '&') { ++bufferPos[bufferStackPos]; tokenType = tAND; return; } tokenType = tBITAND; return; case '|': if (pos + 1 < limit && buffer[pos + 1] == '|') { ++bufferPos[bufferStackPos]; tokenType = tOR; return; } tokenType = tBITOR; return; case '~': tokenType = tCOMPL; return; case '!': if (pos + 1 < limit && buffer[pos + 1] == '=') { ++bufferPos[bufferStackPos]; tokenType = tNOTEQUAL; return; } tokenType = tNOT; return; case '=': if (pos + 1 < limit && buffer[pos + 1] == '=') { ++bufferPos[bufferStackPos]; tokenType = tEQUAL; return; } handleProblem(IProblem.SCANNER_ASSIGNMENT_NOT_ALLOWED, pos); throw new EvalException("assignment not allowed"); //$NON-NLS-1$ case '<': if (pos + 1 < limit) { if (buffer[pos + 1] == '=') { ++bufferPos[bufferStackPos]; tokenType = tLTEQUAL; return; } else if (buffer[pos + 1] == '<') { ++bufferPos[bufferStackPos]; tokenType = tSHIFTL; return; } } tokenType = tLT; return; case '>': if (pos + 1 < limit) { if (buffer[pos + 1] == '=') { ++bufferPos[bufferStackPos]; tokenType = tGTEQUAL; return; } else if (buffer[pos + 1] == '>') { ++bufferPos[bufferStackPos]; tokenType = tSHIFTR; return; } } tokenType = tGT; return; default: // skip over anything we don't handle } } // We've run out of contexts, our work is done here tokenType = tEOF; return; }
private void nextToken() throws EvalException { boolean isHex = false; boolean isOctal = false; boolean isDecimal = false; contextLoop: while (bufferStackPos >= 0) { // Find the first thing we would care about skipWhiteSpace(); while (++bufferPos[bufferStackPos] >= bufferLimit[bufferStackPos]) { // We're at the end of a context, pop it off and try again popContext(); continue contextLoop; } // Tokens don't span buffers, stick to our current one char[] buffer = bufferStack[bufferStackPos]; int limit = bufferLimit[bufferStackPos]; pos = bufferPos[bufferStackPos]; if (buffer[pos] >= '1' && buffer[pos] <= '9') isDecimal = true; else if (buffer[pos] == '0' && pos + 1 < limit) if (buffer[pos + 1] == 'x' || buffer[pos + 1] == 'X') { isHex = true; ++bufferPos[bufferStackPos]; if (pos + 2 < limit) if ((buffer[pos + 2] < '0' || buffer[pos + 2] > '9') && (buffer[pos + 2] < 'a' || buffer[pos + 2] > 'f') && (buffer[pos + 2] < 'A' || buffer[pos + 2] > 'F')) handleProblem(IProblem.SCANNER_BAD_HEX_FORMAT, pos); } else isOctal = true; switch (buffer[pos]) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': int start = bufferPos[bufferStackPos]; int len = 1; while (++bufferPos[bufferStackPos] < limit) { char c = buffer[bufferPos[bufferStackPos]]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) { ++len; continue; } break; } --bufferPos[bufferStackPos]; // Check for defined( pos = bufferPos[bufferStackPos]; if (CharArrayUtils.equals(buffer, start, len, _defined)) { tokenType = t_defined; return; } // Check for macro expansion Object expObject = null; if (bufferData[bufferStackPos] instanceof FunctionStyleMacro.Expansion) { // first check if name is a macro arg expObject = ((FunctionStyleMacro.Expansion) bufferData[bufferStackPos]).definitions .get(buffer, start, len); } if (expObject == null) // now check regular macros expObject = definitions.get(buffer, start, len); if (expObject != null) { if (expObject instanceof FunctionStyleMacro) { handleFunctionStyleMacro((FunctionStyleMacro) expObject); } else if (expObject instanceof ObjectStyleMacro) { ObjectStyleMacro expMacro = (ObjectStyleMacro) expObject; char[] expText = expMacro.getExpansion(); if (expText.length > 0 ) { if (BaseScanner.shouldExpandMacro(expMacro, bufferStackPos, bufferData, -1, bufferPos, bufferStack )) pushContext(expText, new MacroData(start, start + len, expMacro)); else { if (len == 1) { // is a character tokenType = tCHAR; return; } // undefined macro, assume 0 tokenValue = 0; tokenType = tNUMBER; return; } } } else if (expObject instanceof char[]) { char[] expText = (char[]) expObject; if (expText.length > 0) pushContext(expText, null); } continue; } if (len == 1) { // is a character tokenType = tCHAR; return; } // undefined macro, assume 0 tokenValue = 0; tokenType = tNUMBER; return; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': tokenValue = buffer[pos] - '0'; tokenType = tNUMBER; while (++bufferPos[bufferStackPos] < limit) { char c = buffer[bufferPos[bufferStackPos]]; if (isHex) { if (c >= '0' && c <= '9') { tokenValue *= 16; tokenValue += c - '0'; continue; } else if (c >= 'a' && c <= 'f') { tokenValue = (tokenValue == 0 ? 10 : (tokenValue * 16) + 10); tokenValue += c - 'a'; continue; } else if (c >= 'A' && c <= 'F') { tokenValue = (tokenValue == 0 ? 10 : (tokenValue * 16) + 10); tokenValue += c - 'A'; continue; } else { if (bufferPos[bufferStackPos] + 1 < limit) if (!isValidTokenSeparator( c, buffer[bufferPos[bufferStackPos] + 1])) handleProblem( IProblem.SCANNER_BAD_HEX_FORMAT, pos); } } else if (isOctal) { if (c >= '0' && c <= '7') { tokenValue *= 8; tokenValue += c - '0'; continue; } if (bufferPos[bufferStackPos] + 1 < limit) if (!isValidTokenSeparator(c, buffer[bufferPos[bufferStackPos] + 1])) handleProblem( IProblem.SCANNER_BAD_OCTAL_FORMAT, pos); } else if (isDecimal) { if (c >= '0' && c <= '9') { tokenValue *= 10; tokenValue += c - '0'; continue; } if (bufferPos[bufferStackPos] + 1 < limit && !(c == 'L' || c == 'l' || c == 'U' || c == 'u')) if (!isValidTokenSeparator(c, buffer[bufferPos[bufferStackPos] + 1])) handleProblem( IProblem.SCANNER_BAD_DECIMAL_FORMAT, pos); } // end of number if (c == 'L' || c == 'l' || c == 'U' || c == 'u') { // eat the long/unsigned int pos= ++bufferPos[bufferStackPos]; if (pos < limit) { c= buffer[pos]; if (c == 'L' || c == 'l' || c == 'U' || c == 'u') { ++bufferPos[bufferStackPos]; } } } // done break; } --bufferPos[bufferStackPos]; return; case '(': tokenType = tLPAREN; return; case ')': tokenType = tRPAREN; return; case ':': tokenType = tCOLON; return; case '?': tokenType = tQUESTION; return; case '+': tokenType = tPLUS; return; case '-': tokenType = tMINUS; return; case '*': tokenType = tMULT; return; case '/': tokenType = tDIV; return; case '%': tokenType = tMOD; return; case '^': tokenType = tBITXOR; return; case '&': if (pos + 1 < limit && buffer[pos + 1] == '&') { ++bufferPos[bufferStackPos]; tokenType = tAND; return; } tokenType = tBITAND; return; case '|': if (pos + 1 < limit && buffer[pos + 1] == '|') { ++bufferPos[bufferStackPos]; tokenType = tOR; return; } tokenType = tBITOR; return; case '~': tokenType = tCOMPL; return; case '!': if (pos + 1 < limit && buffer[pos + 1] == '=') { ++bufferPos[bufferStackPos]; tokenType = tNOTEQUAL; return; } tokenType = tNOT; return; case '=': if (pos + 1 < limit && buffer[pos + 1] == '=') { ++bufferPos[bufferStackPos]; tokenType = tEQUAL; return; } handleProblem(IProblem.SCANNER_ASSIGNMENT_NOT_ALLOWED, pos); throw new EvalException("assignment not allowed"); //$NON-NLS-1$ case '<': if (pos + 1 < limit) { if (buffer[pos + 1] == '=') { ++bufferPos[bufferStackPos]; tokenType = tLTEQUAL; return; } else if (buffer[pos + 1] == '<') { ++bufferPos[bufferStackPos]; tokenType = tSHIFTL; return; } } tokenType = tLT; return; case '>': if (pos + 1 < limit) { if (buffer[pos + 1] == '=') { ++bufferPos[bufferStackPos]; tokenType = tGTEQUAL; return; } else if (buffer[pos + 1] == '>') { ++bufferPos[bufferStackPos]; tokenType = tSHIFTR; return; } } tokenType = tGT; return; default: // skip over anything we don't handle } } // We've run out of contexts, our work is done here tokenType = tEOF; return; }
diff --git a/src/com/onarandombox/MultiverseCore/MVConfigMigrator.java b/src/com/onarandombox/MultiverseCore/MVConfigMigrator.java index 0fb57f8..07f1231 100644 --- a/src/com/onarandombox/MultiverseCore/MVConfigMigrator.java +++ b/src/com/onarandombox/MultiverseCore/MVConfigMigrator.java @@ -1,115 +1,114 @@ package com.onarandombox.MultiverseCore; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import org.bukkit.plugin.Plugin; import org.bukkit.util.config.Configuration; public class MVConfigMigrator { private MultiverseCore core; public MVConfigMigrator(MultiverseCore core) { this.core = core; } public boolean migrate(String name, File folder) { File oldFolder = null; // They still have MV 1 installed! Good! if (this.core.getServer().getPluginManager().getPlugin("MultiVerse") != null) { this.core.log(Level.INFO, "Found MultiVerse 1. Starting Config Migration..."); if (!this.core.getServer().getPluginManager().isPluginEnabled("MultiVerse")) { Plugin plugin = this.core.getServer().getPluginManager().getPlugin("MultiVerse"); oldFolder = plugin.getDataFolder(); this.core.getServer().getPluginManager().disablePlugin(plugin); } } else { // They didn't have MV 1 enabled... let's try and find the folder... File[] folders = folder.getParentFile().listFiles(); List<File> folderList = Arrays.asList(folders); - File MV1Folder = null; for (File f : folderList) { if (f.getName().equalsIgnoreCase("MultiVerse")) { this.core.log(Level.INFO, "Found the MultiVerse 1 config folder. Starting Config Migration..."); - MV1Folder = f; + oldFolder = f; } } - if (MV1Folder == null) { + if (oldFolder == null) { this.core.log(Level.INFO, "Did not find the MV1 Folder. If you did not have MultiVerse 1 installed and this is the FIRST time you're running MV2, this message is GOOD. "); this.core.log(Level.INFO, "If you did, your configs were **NOT** migrated! Go Here: INSERTURLFORHELP"); return false; } } if (name.equalsIgnoreCase("worlds.yml")) { return this.migrateWorlds(name, oldFolder, folder); } if (name.equalsIgnoreCase("config.yml")) { return this.migrateMainConfig(name, oldFolder, folder); } return true; } private boolean migrateWorlds(String name, File oldFolder, File newFolder) { Configuration newConfig = new Configuration(new File(newFolder, "worlds.yml")); this.core.log(Level.INFO, "Trying to migrate worlds.yml..."); Configuration oldConfig = new Configuration(new File(oldFolder, "worlds.yml")); oldConfig.load(); List<String> keys = oldConfig.getKeys("worlds"); if (keys == null) { this.core.log(Level.WARNING, "Migration FAILURE!"); return false; } for (String key : keys) { newConfig.setProperty("worlds." + key + ".animals.spawn", oldConfig.getProperty("worlds." + key + ".animals")); newConfig.setProperty("worlds." + key + ".monsters.spawn", oldConfig.getProperty("worlds." + key + ".mobs")); newConfig.setProperty("worlds." + key + ".pvp", oldConfig.getProperty("worlds." + key + ".pvp")); newConfig.setProperty("worlds." + key + ".alias.name", oldConfig.getProperty("worlds." + key + ".alias")); newConfig.setProperty("worlds." + key + ".tempspawn", oldConfig.getProperty("worlds." + key + ".spawn")); newConfig.setProperty("worlds." + key + ".price", oldConfig.getProperty("worlds." + key + ".price")); newConfig.setProperty("worlds." + key + ".environment", oldConfig.getProperty("worlds." + key + ".environment")); // Have to convert CSLs to arrays migrateListItem(newConfig, oldConfig, key, ".blockBlacklist", ".blockblacklist"); migrateListItem(newConfig, oldConfig, key, ".worldBlacklist", ".worldblacklist"); migrateListItem(newConfig, oldConfig, key, ".playerBlacklist", ".playerblacklist"); migrateListItem(newConfig, oldConfig, key, ".playerWhitelist", ".playerwhitelist"); } newConfig.save(); this.core.log(Level.INFO, "Migration SUCCESS!"); return true; } private void migrateListItem(Configuration newConfig, Configuration oldConfig, String key, String oldProperty, String newProperty) { List<String> list = Arrays.asList(oldConfig.getString("worlds." + key + oldProperty).split(",")); if (list.size() > 0) { if (list.get(0).length() == 0) { list = new ArrayList<String>(); } } newConfig.setProperty("worlds." + key + newProperty, list); } private boolean migrateMainConfig(String name, File oldFolder, File newFolder) { Configuration newConfig = new Configuration(new File(newFolder, "config.yml")); this.core.log(Level.INFO, "Migrating config.yml..."); Configuration oldConfig = new Configuration(new File(oldFolder, "MultiVerse.yml")); oldConfig.load(); newConfig.setProperty("worldnameprefix", oldConfig.getProperty("prefix")); newConfig.setProperty("messagecooldown", oldConfig.getProperty("alertcooldown")); // Default values: newConfig.setProperty("opfallback", true); newConfig.setProperty("disableautoheal", false); newConfig.setProperty("fakepvp", false); newConfig.setProperty("bedrespawn", true); newConfig.setProperty("version", 2.0); newConfig.save(); return true; } }
false
true
public boolean migrate(String name, File folder) { File oldFolder = null; // They still have MV 1 installed! Good! if (this.core.getServer().getPluginManager().getPlugin("MultiVerse") != null) { this.core.log(Level.INFO, "Found MultiVerse 1. Starting Config Migration..."); if (!this.core.getServer().getPluginManager().isPluginEnabled("MultiVerse")) { Plugin plugin = this.core.getServer().getPluginManager().getPlugin("MultiVerse"); oldFolder = plugin.getDataFolder(); this.core.getServer().getPluginManager().disablePlugin(plugin); } } else { // They didn't have MV 1 enabled... let's try and find the folder... File[] folders = folder.getParentFile().listFiles(); List<File> folderList = Arrays.asList(folders); File MV1Folder = null; for (File f : folderList) { if (f.getName().equalsIgnoreCase("MultiVerse")) { this.core.log(Level.INFO, "Found the MultiVerse 1 config folder. Starting Config Migration..."); MV1Folder = f; } } if (MV1Folder == null) { this.core.log(Level.INFO, "Did not find the MV1 Folder. If you did not have MultiVerse 1 installed and this is the FIRST time you're running MV2, this message is GOOD. "); this.core.log(Level.INFO, "If you did, your configs were **NOT** migrated! Go Here: INSERTURLFORHELP"); return false; } } if (name.equalsIgnoreCase("worlds.yml")) { return this.migrateWorlds(name, oldFolder, folder); } if (name.equalsIgnoreCase("config.yml")) { return this.migrateMainConfig(name, oldFolder, folder); } return true; }
public boolean migrate(String name, File folder) { File oldFolder = null; // They still have MV 1 installed! Good! if (this.core.getServer().getPluginManager().getPlugin("MultiVerse") != null) { this.core.log(Level.INFO, "Found MultiVerse 1. Starting Config Migration..."); if (!this.core.getServer().getPluginManager().isPluginEnabled("MultiVerse")) { Plugin plugin = this.core.getServer().getPluginManager().getPlugin("MultiVerse"); oldFolder = plugin.getDataFolder(); this.core.getServer().getPluginManager().disablePlugin(plugin); } } else { // They didn't have MV 1 enabled... let's try and find the folder... File[] folders = folder.getParentFile().listFiles(); List<File> folderList = Arrays.asList(folders); for (File f : folderList) { if (f.getName().equalsIgnoreCase("MultiVerse")) { this.core.log(Level.INFO, "Found the MultiVerse 1 config folder. Starting Config Migration..."); oldFolder = f; } } if (oldFolder == null) { this.core.log(Level.INFO, "Did not find the MV1 Folder. If you did not have MultiVerse 1 installed and this is the FIRST time you're running MV2, this message is GOOD. "); this.core.log(Level.INFO, "If you did, your configs were **NOT** migrated! Go Here: INSERTURLFORHELP"); return false; } } if (name.equalsIgnoreCase("worlds.yml")) { return this.migrateWorlds(name, oldFolder, folder); } if (name.equalsIgnoreCase("config.yml")) { return this.migrateMainConfig(name, oldFolder, folder); } return true; }
diff --git a/src/main/java/org/mvel/AbstractParser.java b/src/main/java/org/mvel/AbstractParser.java index de5ced00..a41d098a 100644 --- a/src/main/java/org/mvel/AbstractParser.java +++ b/src/main/java/org/mvel/AbstractParser.java @@ -1,1420 +1,1420 @@ package org.mvel; import static org.mvel.Operator.*; import org.mvel.ast.*; import static org.mvel.util.ArrayTools.findFirst; import org.mvel.util.ExecutionStack; import org.mvel.util.ParseTools; import static org.mvel.util.ParseTools.*; import static org.mvel.util.PropertyTools.isDigit; import static org.mvel.util.PropertyTools.isIdentifierPart; import org.mvel.util.ThisLiteral; import org.mvel.util.Stack; import java.io.Serializable; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static java.lang.Character.isWhitespace; import static java.lang.Float.parseFloat; import static java.lang.System.arraycopy; import static java.lang.System.getProperty; import static java.util.Collections.synchronizedMap; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; /** * @author Christopher Brock */ public class AbstractParser implements Serializable { protected char[] expr; protected int cursor; protected int length; protected int fields; protected boolean greedy = true; protected boolean lastWasIdentifier = false; protected boolean lastWasLineLabel = false; protected boolean lastWasComment = false; protected boolean debugSymbols = false; private int line = 1; protected ASTNode lastNode; private static Map<String, char[]> EX_PRECACHE; public static final Map<String, Object> LITERALS = new HashMap<String, Object>(35, 0.4f); public static final Map<String, Integer> OPERATORS = new HashMap<String, Integer>(25 * 2, 0.4f); protected Stack stk; protected ExecutionStack splitAccumulator = new ExecutionStack(); protected static ThreadLocal<ParserContext> parserContext; static { configureFactory(); /** * Setup the basic literals */ AbstractParser.LITERALS.put("true", TRUE); AbstractParser.LITERALS.put("false", FALSE); AbstractParser.LITERALS.put("null", null); AbstractParser.LITERALS.put("nil", null); AbstractParser.LITERALS.put("empty", BlankLiteral.INSTANCE); AbstractParser.LITERALS.put("this", ThisLiteral.class); /** * Add System and all the class wrappers from the JCL. */ LITERALS.put("System", System.class); LITERALS.put("String", String.class); LITERALS.put("Integer", Integer.class); LITERALS.put("int", Integer.class); LITERALS.put("Long", Long.class); LITERALS.put("long", Long.class); LITERALS.put("Boolean", Boolean.class); LITERALS.put("boolean", Boolean.class); LITERALS.put("Short", Short.class); LITERALS.put("short", Short.class); LITERALS.put("Character", Character.class); LITERALS.put("char", Character.class); LITERALS.put("Double", Double.class); LITERALS.put("double", double.class); LITERALS.put("Float", Float.class); LITERALS.put("float", float.class); LITERALS.put("Math", Math.class); LITERALS.put("Void", Void.class); LITERALS.put("Object", Object.class); LITERALS.put("Class", Class.class); LITERALS.put("ClassLoader", ClassLoader.class); LITERALS.put("Runtime", Runtime.class); LITERALS.put("Thread", Thread.class); LITERALS.put("Compiler", Compiler.class); LITERALS.put("StringBuffer", StringBuffer.class); LITERALS.put("ThreadLocal", ThreadLocal.class); LITERALS.put("SecurityManager", SecurityManager.class); LITERALS.put("StrictMath", StrictMath.class); LITERALS.put("Array", java.lang.reflect.Array.class); if (parseFloat(getProperty("java.version").substring(0, 2)) >= 1.5) { try { LITERALS.put("StringBuilder", Thread.currentThread().getContextClassLoader().loadClass("java.lang.StringBuilder")); } catch (Exception e) { throw new RuntimeException("cannot resolve a built-in literal", e); } } _loadLanguageFeaturesByLevel(5); } static void configureFactory() { if (MVEL.THREAD_SAFE) { EX_PRECACHE = synchronizedMap(new WeakHashMap<String, char[]>(10)); } else { EX_PRECACHE = new WeakHashMap<String, char[]>(10); } } protected ASTNode nextTokenSkipSymbols() { ASTNode n = nextToken(); if (n != null && n.getFields() == -1) n = nextToken(); return n; } /** * Retrieve the next token in the expression. * * @return - */ protected ASTNode nextToken() { /** * If the cursor is at the end of the expression, we have nothing more to do: * return null. */ if (cursor >= length) { - if (debugSymbols && lastNode != null) { - /** - * Produce a trailing line label. This allows debuggers to step into the last line. - */ - lastNode = null; - return new LineLabel(getParserContext().getSourceFile(), getParserContext().getLineCount() + 1); - } +// if (debugSymbols && lastNode != null) { +// /** +// * Produce a trailing line label. This allows debuggers to step into the last line. +// */ +// lastNode = null; +// return new LineLabel(getParserContext().getSourceFile(), getParserContext().getLineCount() + 1); +// } return null; } else if (!splitAccumulator.isEmpty()) { return lastNode = (ASTNode) splitAccumulator.pop(); } int brace, start = cursor; /** * Because of parser recursion for sub-expression parsing, we sometimes need to remain * certain field states. We do not reset for assignments, boolean mode, list creation or * a capture only mode. */ fields = fields & (ASTNode.INLINE_COLLECTION | ASTNode.COMPILE_IMMEDIATE); boolean capture = false, union = false; if (debugSymbols) { if (!lastWasLineLabel) { if (getParserContext().getSourceFile() == null) { throw new CompileException("unable to produce debugging symbols: source name must be provided."); } ParserContext pCtx = getParserContext(); line = pCtx.getLineCount(); if (expr[cursor] == '\n' || expr[cursor] == '\r') { skipWhitespaceWithLineAccounting(); } pCtx.setLineCount(line); if (!pCtx.isKnownLine(pCtx.getSourceFile(), line)) { lastWasLineLabel = true; pCtx.setLineAndOffset(line, cursor); pCtx.addKnownLine(pCtx.getSourceFile(), line); LineLabel ll = new LineLabel(pCtx.getSourceFile(), line); pCtx.setLastLineLabel(ll); return lastNode = ll; } } else { lastWasComment = lastWasLineLabel = false; } } /** * Skip any whitespace currently under the starting point. */ while (start < length && isWhitespace(expr[start])) start++; /** * From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for * trouble unless you really know what you're doing. */ for (cursor = start; cursor < length;) { if (isIdentifierPart(expr[cursor])) { /** * If the current character under the cursor is a valid * part of an identifier, we keep capturing. */ capture = true; cursor++; } else if (capture) { String t; if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) { switch (OPERATORS.get(t)) { case NEW: start = cursor + 1; captureToEOT(); return lastNode = new NewObjectNode(subArray(start, cursor), fields); case ASSERT: start = cursor + 1; captureToEOS(); return lastNode = new AssertNode(subArray(start, cursor--), fields); case RETURN: start = cursor + 1; captureToEOS(); return lastNode = new ReturnNode(subArray(start, cursor), fields); case IF: fields |= ASTNode.BLOCK_IF; return captureCodeBlock(); case FOREACH: fields |= ASTNode.BLOCK_FOREACH; return captureCodeBlock(); case WITH: fields |= ASTNode.BLOCK_WITH; return captureCodeBlock(); case IMPORT: start = cursor + 1; captureToEOS(); ImportNode importNode = new ImportNode(subArray(start, cursor--), fields); getParserContext().addImport(getSimpleClassName(importNode.getImportClass()), importNode.getImportClass()); return importNode; case IMPORT_STATIC: start = cursor + 1; captureToEOS(); return lastNode = new StaticImportNode(subArray(start, cursor--), fields); } } /** * If we *were* capturing a token, and we just hit a non-identifier * character, we stop and figure out what to do. */ skipWhitespace(); if (expr[cursor] == '(') { fields |= ASTNode.METHOD; /** * If the current token is a method call or a constructor, we * simply capture the entire parenthesized range and allow * reduction to be dealt with through sub-parsing the property. */ cursor++; for (brace = 1; cursor < length && brace > 0;) { switch (expr[cursor++]) { case'(': brace++; break; case')': brace--; break; /** * String literals need to be skipped over or encountering a ')' in a String * will cause an explosion. */ case'\'': cursor = captureStringLiteral('\'', expr, cursor, length) + 1; break; case'"': cursor = captureStringLiteral('"', expr, cursor, length) + 1; break; } } /** * If the brace counter is greater than 0, we know we have * unbalanced braces in the expression. So we throw a * optimize error now. */ if (brace > 0) throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor); } /** * If we encounter any of the following cases, we are still dealing with * a contiguous token. */ String name; if (cursor < length) { switch (expr[cursor]) { case'+': switch (lookAhead(1)) { case'+': ASTNode n = new PostFixIncNode(subArray(start, cursor), fields); cursor += 2; return lastNode = n; case'=': name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields, Operator.ADD, t); } else { return lastNode = new AssignmentNode(subArray(start, cursor), fields, Operator.ADD, name); } } break; case'-': switch (lookAhead(1)) { case'-': ASTNode n = new PostFixDecNode(subArray(start, cursor), fields); cursor += 2; return lastNode = n; case'=': name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); return lastNode = new AssignSub(subArray(start, cursor), fields, name); } break; case'*': if (isAt('=', 1)) { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); return lastNode = new AssignMult(subArray(start, cursor), fields, name); } break; case'/': if (isAt('=', 1)) { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); return lastNode = new AssignDiv(subArray(start, cursor), fields, name); } break; case']': case'[': balancedCapture('['); cursor++; continue; case'.': union = true; cursor++; continue; case'~': if (isAt('=', 1)) { char[] stmt = subArray(start, trimLeft(cursor)); start = cursor += 2; captureToEOT(); return lastNode = new RegExMatch(stmt, fields, subArray(start, cursor)); } break; case'=': if (isAt('+', 1)) { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); return lastNode = new AssignAdd(subArray(start, cursor), fields, name); } if (greedy && !isAt('=', 1)) { cursor++; fields |= ASTNode.ASSIGN; skipWhitespace(); captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields); } else if (lastWasIdentifier) { /** * Check for typing information. */ if (lastNode.getLiteralValue() instanceof String) { if (getParserContext().hasImport((String) lastNode.getLiteralValue())) { lastNode.setLiteralValue(getParserContext().getImport((String) lastNode.getLiteralValue())); lastNode.setAsLiteral(); lastNode.discard(); } else if (stk != null && stk.peek() instanceof Class) { lastNode.setLiteralValue(stk.pop()); lastNode.setAsLiteral(); lastNode.discard(); } else { try { /** * take a stab in the dark and try and load the class */ lastNode.setLiteralValue(createClass((String) lastNode.getLiteralValue())); lastNode.setAsLiteral(); lastNode.discard(); } catch (ClassNotFoundException e) { /** * Just fail through. */ } } } if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) { lastNode.discard(); captureToEOS(); return new TypedVarNode(subArray(start, cursor), fields, (Class) lastNode.getLiteralValue()); } throw new ParseException("unknown class: " + lastNode.getLiteralValue()); } else { return lastNode = new AssignmentNode(subArray(start, cursor), fields); } } } } /** * Produce the token. */ trimWhitespace(); return createPropertyToken(start, cursor); } else switch (expr[cursor]) { case'@': { start++; captureToEOT(); String interceptorName = new String(expr, start, cursor - start); if (getParserContext().getInterceptors() == null || !getParserContext().getInterceptors(). containsKey(interceptorName)) { throw new CompileException("reference to undefined interceptor: " + interceptorName, expr, cursor); } return lastNode = new InterceptorWrapper(getParserContext().getInterceptors().get(interceptorName), nextToken()); } case'=': return createToken(expr, start, (cursor += 2), fields); case'-': if (isAt('-', 1)) { start = cursor += 2; captureToEOT(); return lastNode = new PreFixDecNode(subArray(start, cursor), fields); } else if ((cursor > 0 && !isWhitespace(lookBehind(1))) || !isDigit(lookAhead(1))) { return createToken(expr, start, cursor++ + 1, fields); } else if ((cursor - 1) < 0 || (!isDigit(lookBehind(1))) && isDigit(lookAhead(1))) { cursor++; break; } case'+': if (isAt('+', 1)) { start = cursor += 2; captureToEOT(); return lastNode = new PreFixIncNode(subArray(start, cursor), fields); } return createToken(expr, start, cursor++ + 1, fields); case'*': if (isAt('*', 1)) { cursor++; } return createToken(expr, start, cursor++ + 1, fields); case';': cursor++; lastWasIdentifier = false; return lastNode = new EndOfStatement(); case'#': case'/': if (isAt(expr[cursor], 1)) { /** * Handle single line comments. */ while (cursor < length && expr[cursor] != '\n') cursor++; if (debugSymbols) { line = getParserContext().getLineCount(); skipWhitespaceWithLineAccounting(); // getParserContext().setLineCount(line); if (lastNode instanceof LineLabel) { getParserContext().getLastLineLabel().setLineNumber(line); getParserContext().addKnownLine(line); } lastWasComment = true; getParserContext().setLineCount(line); } else if (cursor < length) { skipWhitespace(); } if ((start = cursor) >= length) return null; continue; } else if (expr[cursor] == '/' && isAt('*', 1)) { /** * Handle multi-line comments. */ int len = length - 1; /** * This probably seems highly redundant, but sub-compilations within the same * source will spawn a new compiler, and we need to sync this with the * parser context; */ if (debugSymbols) { line = getParserContext().getLineCount(); } while (true) { cursor++; /** * Since multi-line comments may cross lines, we must keep track of any line-break * we encounter. */ if (debugSymbols) { skipWhitespaceWithLineAccounting(); } if (cursor == len) { throw new CompileException("unterminated block comment", expr, cursor); } if (expr[cursor] == '*' && isAt('/', 1)) { if ((cursor += 2) >= length) return null; skipWhitespaceWithLineAccounting(); start = cursor; break; } } if (debugSymbols) { getParserContext().setLineCount(line); if (lastNode instanceof LineLabel) { getParserContext().getLastLineLabel().setLineNumber(line); getParserContext().addKnownLine(line); } lastWasComment = true; } continue; } case'?': case':': case'^': case'%': { return createToken(expr, start, cursor++ + 1, fields); } case'(': { cursor++; boolean singleToken = true; boolean lastWS = false; skipWhitespace(); for (brace = 1; cursor < length && brace > 0; cursor++) { switch (expr[cursor]) { case'(': brace++; break; case')': brace--; break; case'\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case'"': cursor = captureStringLiteral('"', expr, cursor, length); break; case'i': if (isAt('n', 1) && isWhitespace(lookAhead(2))) { fields |= ASTNode.FOLD; for (int level = brace; cursor < length; cursor++) { switch (expr[cursor]) { case'(': brace++; break; case')': if (--brace < level) { if (lookAhead(1) == '.') { ASTNode node = createToken(expr, trimRight(start), (start = cursor++), ASTNode.FOLD); captureToEOT(); return lastNode = new Union(expr, trimRight(start + 2), cursor, fields, node); } else { return createToken(expr, trimRight(start), cursor++, ASTNode.FOLD); } } break; case'\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case'"': cursor = captureStringLiteral('\'', expr, cursor, length); break; } } } break; default: /** * Check to see if we should disqualify this current token as a potential * type-cast candidate. */ if (lastWS || !isIdentifierPart(expr[cursor])) { singleToken = false; } else if (isWhitespace(expr[cursor])) { lastWS = true; skipWhitespace(); cursor--; } } } if (brace > 0) { throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor); } char[] _subset = null; if (singleToken) { int st; String tokenStr = new String(_subset = subset(expr, st = trimRight(start + 1), trimLeft(cursor - 1) - st)); if (getParserContext().hasImport(tokenStr)) { start = cursor; captureToEOS(); return lastNode = new TypeCast(expr, start, cursor, fields, getParserContext().getImport(tokenStr)); } else { try { /** * * take a stab in the dark and try and load the class */ int _start = cursor; captureToEOS(); return lastNode = new TypeCast(expr, _start, cursor, fields, createClass(tokenStr)); } catch (ClassNotFoundException e) { /** * Just fail through. */ } } } if (_subset != null) { return handleUnion(new Substatement(_subset, fields)); } else { return handleUnion(new Substatement(subset(expr, start = trimRight(start + 1), trimLeft(cursor - 1) - start), fields)); } } case'}': case']': case')': { throw new ParseException("unbalanced braces", expr, cursor); } case'>': { if (expr[cursor + 1] == '>') { if (expr[cursor += 2] == '>') cursor++; return createToken(expr, start, cursor, fields); } else if (expr[cursor + 1] == '=') { return createToken(expr, start, cursor += 2, fields); } else { return createToken(expr, start, ++cursor, fields); } } case'<': { if (expr[++cursor] == '<') { if (expr[++cursor] == '<') cursor++; return createToken(expr, start, cursor, fields); } else if (expr[cursor] == '=') { return createToken(expr, start, ++cursor, fields); } else { return createToken(expr, start, cursor, fields); } } case'\'': cursor = captureStringLiteral('\'', expr, cursor, length); return lastNode = new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class); case'"': cursor = captureStringLiteral('"', expr, cursor, length); return lastNode = new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class); case'&': { if (expr[cursor++ + 1] == '&') { return createToken(expr, start, ++cursor, fields); } else { return createToken(expr, start, cursor, fields); } } case'|': { if (expr[cursor++ + 1] == '|') { return createToken(expr, start, ++cursor, fields); } else { return createToken(expr, start, cursor, fields); } } case'~': if ((cursor - 1 < 0 || !isIdentifierPart(lookBehind(1))) && isDigit(expr[cursor + 1])) { fields |= ASTNode.INVERT; start++; cursor++; break; } else if (expr[cursor + 1] == '(') { fields |= ASTNode.INVERT; start = ++cursor; continue; } else { if (expr[cursor + 1] == '=') cursor++; return createToken(expr, start, ++cursor, fields); } case'!': { if (isIdentifierPart(expr[++cursor]) || expr[cursor] == '(') { start = cursor; fields |= ASTNode.NEGATION; continue; } else if (expr[cursor] != '=') throw new CompileException("unexpected operator '!'", expr, cursor, null); else { return createToken(expr, start, ++cursor, fields); } } case'[': case'{': if (balancedCapture(expr[cursor]) == -1) { if (cursor >= length) cursor--; throw new CompileException("unbalanced brace: in inline map/list/array creation", expr, cursor); } if (lookAhead(1) == '.') { InlineCollectionNode n = new InlineCollectionNode(expr, start, start = ++cursor, fields); captureToEOT(); return lastNode = new Union(expr, start + 1, cursor, fields, n); } else { return lastNode = new InlineCollectionNode(expr, start, ++cursor, fields); } default: cursor++; } } return createPropertyToken(start, cursor); } protected ASTNode handleUnion(ASTNode node) { if (cursor < length) { skipWhitespace(); if (expr[cursor] == '.') { int union = cursor + 1; captureToEOS(); return lastNode = new Union(expr, union, cursor, fields, node); } } return lastNode = node; } protected int balancedCapture(char type) { int depth = 1; char term = type; switch (type) { case'[': term = ']'; break; case'{': term = '}'; break; case'(': term = ')'; break; } for (cursor++; cursor < length; cursor++) { if (expr[cursor] == type) { depth++; } else if (expr[cursor] == term && --depth == 0) { return cursor; } } return -1; } /** * Most of this method should be self-explanatory. * * @param expr - * @param start - * @param end - * @param fields - * @return - */ private ASTNode createToken(final char[] expr, final int start, final int end, int fields) { ASTNode tk = new ASTNode(expr, start, end, fields); lastWasIdentifier = tk.isIdentifier(); return lastNode = tk; } private char[] subArray(final int start, final int end) { char[] newA = new char[end - start]; arraycopy(expr, start, newA, 0, newA.length); return newA; } private ASTNode createPropertyToken(int start, int end) { lastWasIdentifier = true; if (parserContext != null && parserContext.get() != null && parserContext.get().hasImports()) { char[] _subset = subset(expr, start, cursor - start); int offset; if ((offset = findFirst('.', _subset)) != -1) { String iStr = new String(_subset, 0, offset); if ("this".equals(iStr)) { return lastNode = new ThisValDeepPropertyNode(subset(_subset, offset + 1, _subset.length - offset - 1), fields); } else if (getParserContext().hasImport(iStr)) { return lastNode = new LiteralDeepPropertyNode(subset(_subset, offset + 1, _subset.length - offset - 1), fields, getParserContext().getImport(iStr)); } } else { String iStr = new String(_subset); if (getParserContext().hasImport(iStr)) { return lastNode = new LiteralNode(getParserContext().getImport(iStr), Class.class); } ASTNode node = new ASTNode(_subset, 0, _subset.length, fields); lastWasIdentifier = node.isIdentifier(); return lastNode = node; } } else if ((fields & ASTNode.METHOD) != 0) { return lastNode = new ASTNode(expr, start, end, fields); } return lastNode = new PropertyASTNode(expr, start, end, fields); } private ASTNode createBlockToken(final int condStart, final int condEnd, final int blockStart, final int blockEnd) { lastWasIdentifier = false; cursor++; if (!isStatementManuallyTerminated()) { splitAccumulator.add(new EndOfStatement()); } if (isFlag(ASTNode.BLOCK_IF)) { return new IfNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields); } else if (isFlag(ASTNode.BLOCK_FOREACH)) { return new ForEachNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields); } // DONT'T REMOVE THIS COMMENT! // else if (isFlag(ASTNode.BLOCK_WITH)) { else { return new WithNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields); } } private ASTNode captureCodeBlock() { boolean cond = true; ASTNode first = null; ASTNode tk = null; if (isFlag(ASTNode.BLOCK_IF)) { do { if (tk != null) { skipToNextTokenJunction(); skipWhitespace(); cond = expr[cursor] != '{' && expr[cursor] == 'i' && expr[++cursor] == 'f' && (isWhitespace(expr[++cursor]) || expr[cursor] == '('); } if (((IfNode) (tk = _captureBlock(tk, expr, cond))).getElseBlock() != null) { cursor++; return first; } if (first == null) first = tk; if (cursor < length && expr[cursor] != ';') { cursor++; } } while (blockContinues()); } else if (isFlag(ASTNode.BLOCK_FOREACH) || isFlag(ASTNode.BLOCK_WITH)) { skipToNextTokenJunction(); skipWhitespace(); return _captureBlock(null, expr, true); } return first; } private ASTNode _captureBlock(ASTNode node, final char[] expr, boolean cond) { skipWhitespace(); int startCond = 0; int endCond = 0; if (cond) { startCond = ++cursor; endCond = balancedCapture('('); cursor++; } int blockStart; int blockEnd; skipWhitespace(); if (cursor >= length) { throw new CompileException("unbalanced braces", expr, cursor); } else if (expr[cursor] == '{') { blockStart = cursor; if ((blockEnd = balancedCapture('{')) == -1) { throw new CompileException("unbalanced braces { }", expr, cursor); } } else { blockStart = cursor - 1; captureToEOLorOF(); blockEnd = cursor + 1; } if (isFlag(ASTNode.BLOCK_IF)) { IfNode ifNode = (IfNode) node; if (node != null) { if (!cond) { ifNode.setElseBlock(subArray(trimRight(blockStart + 1), trimLeft(blockEnd - 1))); return node; } else { IfNode tk = (IfNode) createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd)); ifNode.setElseIf(tk); return tk; } } else { return createBlockToken(startCond, endCond, blockStart + 1, blockEnd); } } // DON"T REMOVE THIS COMMENT! // else if (isFlag(ASTNode.BLOCK_FOREACH) || isFlag(ASTNode.BLOCK_WITH)) { else { return createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd)); } } protected boolean blockContinues() { if ((cursor + 4) < length) { if (expr[cursor] != ';') cursor--; skipWhitespace(); return expr[cursor] == 'e' && expr[cursor + 1] == 'l' && expr[cursor + 2] == 's' && expr[cursor + 3] == 'e' && (isWhitespace(expr[cursor + 4]) || expr[cursor + 4] == '{'); } return false; } protected void captureToEOS() { while (cursor < length && expr[cursor] != ';') { cursor++; } } protected void captureToEOLorOF() { while (cursor < length && (expr[cursor] != '\n' && expr[cursor] != '\r' && expr[cursor] != ';')) { cursor++; } } protected void captureToEOT() { skipWhitespace(); while (++cursor < length) { switch (expr[cursor]) { case'(': case'[': case'{': if ((cursor = ParseTools.balancedCapture(expr, cursor, expr[cursor])) == -1) { throw new CompileException("unbalanced braces", expr, cursor); } break; case'&': case'|': case';': return; case'.': skipWhitespace(); break; default: if (isWhitespace(expr[cursor])) { skipWhitespace(); if (expr[cursor] == '.') { if (cursor < length) cursor++; skipWhitespace(); break; } else { trimWhitespace(); return; } } } } } protected int trimLeft(int pos) { while (pos > 0 && isWhitespace(expr[pos - 1])) pos--; return pos; } protected int trimRight(int pos) { while (pos < length && isWhitespace(expr[pos])) pos++; return pos; } protected void skipWhitespace() { while (cursor < length && isWhitespace(expr[cursor])) cursor++; } protected void skipWhitespaceWithLineAccounting() { while (cursor < length && isWhitespace(expr[cursor])) { switch (expr[cursor]) { case'\r': cursor++; continue; case'\n': cursor++; line++; continue; } cursor++; } } protected void skipToNextTokenJunction() { while (cursor < length) { switch (expr[cursor]) { case'{': case'(': return; default: if (isWhitespace(expr[cursor])) return; cursor++; } } } protected void trimWhitespace() { while (cursor > 0 && isWhitespace(expr[cursor - 1])) cursor--; } protected ASTNode captureTokenToEOS() { int start = cursor; captureToEOS(); return lastNode = new ASTNode(expr, start, cursor, 0); } protected void setExpression(String expression) { if (expression != null && !"".equals(expression)) { if (!EX_PRECACHE.containsKey(expression)) { length = (this.expr = expression.toCharArray()).length; // trim any whitespace. while (length != 0 && isWhitespace(this.expr[length - 1])) length--; char[] e = new char[length]; arraycopy(this.expr, 0, e, 0, length); EX_PRECACHE.put(expression, e); } else { length = (expr = EX_PRECACHE.get(expression)).length; } } } protected void setExpression(char[] expression) { length = (this.expr = expression).length; while (length != 0 && isWhitespace(this.expr[length - 1])) length--; } private boolean isFlag(int bit) { return (fields & bit) != 0; } public static boolean isReservedWord(String name) { return LITERALS.containsKey(name) || OPERATORS.containsKey(name); } protected char lookBehind(int range) { if ((cursor - range) <= 0) return 0; else { return expr[cursor - range]; } } protected char lookAhead(int range) { if ((cursor + range) >= length) return 0; else { return expr[cursor + range]; } } protected boolean isStatementManuallyTerminated() { int c = cursor; while (c < length && isWhitespace(expr[c])) c++; return (c < length && expr[c] == ';'); } protected boolean isRemain(int range) { return (cursor + range) < length; } protected boolean isAt(char c, int range) { return lookAhead(range) == c; } protected ParserContext getParserContext() { if (parserContext == null || parserContext.get() == null) { newContext(); } return parserContext.get(); } public static ParserContext getCurrentThreadParserContext() { return contextControl(GET_OR_CREATE, null, null); } protected void newContext() { contextControl(SET, new ParserContext(), this); } protected void newContext(ParserContext pCtx) { contextControl(SET, pCtx, this); } protected void removeContext() { contextControl(REMOVE, null, this); } protected static ParserContext contextControl(int operation, ParserContext pCtx, AbstractParser parser) { synchronized (Runtime.getRuntime()) { if (parserContext == null) parserContext = new ThreadLocal<ParserContext>(); switch (operation) { case SET: pCtx.setRootParser(parser); parserContext.set(pCtx); return null; case REMOVE: parserContext.set(null); return null; case GET_OR_CREATE: if (parserContext.get() == null) { parserContext.set(new ParserContext(parser)); } case GET: return parserContext.get(); } } return null; } protected static final int SET = 0; protected static final int REMOVE = 1; protected static final int GET = 2; protected static final int GET_OR_CREATE = 3; public boolean isDebugSymbols() { return debugSymbols; } public void setDebugSymbols(boolean debugSymbols) { this.debugSymbols = debugSymbols; } protected static String getCurrentSourceFileName() { if (parserContext != null && parserContext.get() != null) { return parserContext.get().getSourceFile(); } return null; } protected void addFatalError(String message) { getParserContext().addError(new ErrorDetail(getParserContext().getLineCount(), cursor - getParserContext().getLineOffset(), true, message)); } protected void addFatalError(String message, int row, int cols) { getParserContext().addError(new ErrorDetail(row, cols, true, message)); } protected void addWarning(String message) { getParserContext().addError(new ErrorDetail(message, false)); } public static final int LEVEL_5_CONTROL_FLOW = 5; public static final int LEVEL_4_ASSIGNMENT = 4; public static final int LEVEL_3_ITERATION = 3; public static final int LEVEL_2_MULTI_STATEMENT = 2; public static final int LEVEL_1_BASIC_LANG = 1; public static final int LEVEL_0_PROPERTY_ONLY = 0; public static void setLanguageLevel(int level) { OPERATORS.clear(); _loadLanguageFeaturesByLevel(level); } private static void _loadLanguageFeaturesByLevel(int languageLevel) { switch (languageLevel) { case 5: // control flow operations OPERATORS.put("if", IF); OPERATORS.put("else", ELSE); OPERATORS.put("?", Operator.TERNARY); OPERATORS.put("switch", SWITCH); case 4: // assignment OPERATORS.put("=", Operator.ASSIGN); OPERATORS.put("var", TYPED_VAR); OPERATORS.put("+=", ASSIGN_ADD); OPERATORS.put("-=", ASSIGN_SUB); case 3: // iteration OPERATORS.put("foreach", FOREACH); OPERATORS.put("while", WHILE); OPERATORS.put("for", FOR); OPERATORS.put("do", DO); case 2: // multi-statement OPERATORS.put("return", RETURN); OPERATORS.put(";", END_OF_STMT); case 1: // boolean, math ops, projection, assertion, objection creation, block setters, imports OPERATORS.put("+", ADD); OPERATORS.put("-", SUB); OPERATORS.put("*", MULT); OPERATORS.put("**", POWER); OPERATORS.put("/", DIV); OPERATORS.put("%", MOD); OPERATORS.put("==", EQUAL); OPERATORS.put("!=", NEQUAL); OPERATORS.put(">", GTHAN); OPERATORS.put(">=", GETHAN); OPERATORS.put("<", LTHAN); OPERATORS.put("<=", LETHAN); OPERATORS.put("&&", AND); OPERATORS.put("and", AND); OPERATORS.put("||", OR); OPERATORS.put("or", CHOR); OPERATORS.put("~=", REGEX); OPERATORS.put("instanceof", INSTANCEOF); OPERATORS.put("is", INSTANCEOF); OPERATORS.put("contains", CONTAINS); OPERATORS.put("soundslike", SOUNDEX); OPERATORS.put("strsim", SIMILARITY); OPERATORS.put("convertable_to", CONVERTABLE_TO); OPERATORS.put("#", STR_APPEND); OPERATORS.put("&", BW_AND); OPERATORS.put("|", BW_OR); OPERATORS.put("^", BW_XOR); OPERATORS.put("<<", BW_SHIFT_LEFT); OPERATORS.put("<<<", BW_USHIFT_LEFT); OPERATORS.put(">>", BW_SHIFT_RIGHT); OPERATORS.put(">>>", BW_USHIFT_RIGHT); OPERATORS.put("new", Operator.NEW); OPERATORS.put("in", PROJECTION); OPERATORS.put("with", WITH); OPERATORS.put("assert", ASSERT); OPERATORS.put("import", IMPORT); OPERATORS.put("import_static", IMPORT_STATIC); OPERATORS.put("++", INC); OPERATORS.put("--", DEC); case 0: // Property access and inline collections OPERATORS.put(":", TERNARY_ELSE); } } public static void resetParserContext() { contextControl(REMOVE, null, null); } }
true
true
protected ASTNode nextToken() { /** * If the cursor is at the end of the expression, we have nothing more to do: * return null. */ if (cursor >= length) { if (debugSymbols && lastNode != null) { /** * Produce a trailing line label. This allows debuggers to step into the last line. */ lastNode = null; return new LineLabel(getParserContext().getSourceFile(), getParserContext().getLineCount() + 1); } return null; } else if (!splitAccumulator.isEmpty()) { return lastNode = (ASTNode) splitAccumulator.pop(); } int brace, start = cursor; /** * Because of parser recursion for sub-expression parsing, we sometimes need to remain * certain field states. We do not reset for assignments, boolean mode, list creation or * a capture only mode. */ fields = fields & (ASTNode.INLINE_COLLECTION | ASTNode.COMPILE_IMMEDIATE); boolean capture = false, union = false; if (debugSymbols) { if (!lastWasLineLabel) { if (getParserContext().getSourceFile() == null) { throw new CompileException("unable to produce debugging symbols: source name must be provided."); } ParserContext pCtx = getParserContext(); line = pCtx.getLineCount(); if (expr[cursor] == '\n' || expr[cursor] == '\r') { skipWhitespaceWithLineAccounting(); } pCtx.setLineCount(line); if (!pCtx.isKnownLine(pCtx.getSourceFile(), line)) { lastWasLineLabel = true; pCtx.setLineAndOffset(line, cursor); pCtx.addKnownLine(pCtx.getSourceFile(), line); LineLabel ll = new LineLabel(pCtx.getSourceFile(), line); pCtx.setLastLineLabel(ll); return lastNode = ll; } } else { lastWasComment = lastWasLineLabel = false; } } /** * Skip any whitespace currently under the starting point. */ while (start < length && isWhitespace(expr[start])) start++; /** * From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for * trouble unless you really know what you're doing. */ for (cursor = start; cursor < length;) { if (isIdentifierPart(expr[cursor])) { /** * If the current character under the cursor is a valid * part of an identifier, we keep capturing. */ capture = true; cursor++; } else if (capture) { String t; if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) { switch (OPERATORS.get(t)) { case NEW: start = cursor + 1; captureToEOT(); return lastNode = new NewObjectNode(subArray(start, cursor), fields); case ASSERT: start = cursor + 1; captureToEOS(); return lastNode = new AssertNode(subArray(start, cursor--), fields); case RETURN: start = cursor + 1; captureToEOS(); return lastNode = new ReturnNode(subArray(start, cursor), fields); case IF: fields |= ASTNode.BLOCK_IF; return captureCodeBlock(); case FOREACH: fields |= ASTNode.BLOCK_FOREACH; return captureCodeBlock(); case WITH: fields |= ASTNode.BLOCK_WITH; return captureCodeBlock(); case IMPORT: start = cursor + 1; captureToEOS(); ImportNode importNode = new ImportNode(subArray(start, cursor--), fields); getParserContext().addImport(getSimpleClassName(importNode.getImportClass()), importNode.getImportClass()); return importNode; case IMPORT_STATIC: start = cursor + 1; captureToEOS(); return lastNode = new StaticImportNode(subArray(start, cursor--), fields); } } /** * If we *were* capturing a token, and we just hit a non-identifier * character, we stop and figure out what to do. */ skipWhitespace(); if (expr[cursor] == '(') { fields |= ASTNode.METHOD; /** * If the current token is a method call or a constructor, we * simply capture the entire parenthesized range and allow * reduction to be dealt with through sub-parsing the property. */ cursor++; for (brace = 1; cursor < length && brace > 0;) { switch (expr[cursor++]) { case'(': brace++; break; case')': brace--; break; /** * String literals need to be skipped over or encountering a ')' in a String * will cause an explosion. */ case'\'': cursor = captureStringLiteral('\'', expr, cursor, length) + 1; break; case'"': cursor = captureStringLiteral('"', expr, cursor, length) + 1; break; } } /** * If the brace counter is greater than 0, we know we have * unbalanced braces in the expression. So we throw a * optimize error now. */ if (brace > 0) throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor); } /** * If we encounter any of the following cases, we are still dealing with * a contiguous token. */ String name; if (cursor < length) { switch (expr[cursor]) { case'+': switch (lookAhead(1)) { case'+': ASTNode n = new PostFixIncNode(subArray(start, cursor), fields); cursor += 2; return lastNode = n; case'=': name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields, Operator.ADD, t); } else { return lastNode = new AssignmentNode(subArray(start, cursor), fields, Operator.ADD, name); } } break; case'-': switch (lookAhead(1)) { case'-': ASTNode n = new PostFixDecNode(subArray(start, cursor), fields); cursor += 2; return lastNode = n; case'=': name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); return lastNode = new AssignSub(subArray(start, cursor), fields, name); } break; case'*': if (isAt('=', 1)) { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); return lastNode = new AssignMult(subArray(start, cursor), fields, name); } break; case'/': if (isAt('=', 1)) { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); return lastNode = new AssignDiv(subArray(start, cursor), fields, name); } break; case']': case'[': balancedCapture('['); cursor++; continue; case'.': union = true; cursor++; continue; case'~': if (isAt('=', 1)) { char[] stmt = subArray(start, trimLeft(cursor)); start = cursor += 2; captureToEOT(); return lastNode = new RegExMatch(stmt, fields, subArray(start, cursor)); } break; case'=': if (isAt('+', 1)) { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); return lastNode = new AssignAdd(subArray(start, cursor), fields, name); } if (greedy && !isAt('=', 1)) { cursor++; fields |= ASTNode.ASSIGN; skipWhitespace(); captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields); } else if (lastWasIdentifier) { /** * Check for typing information. */ if (lastNode.getLiteralValue() instanceof String) { if (getParserContext().hasImport((String) lastNode.getLiteralValue())) { lastNode.setLiteralValue(getParserContext().getImport((String) lastNode.getLiteralValue())); lastNode.setAsLiteral(); lastNode.discard(); } else if (stk != null && stk.peek() instanceof Class) { lastNode.setLiteralValue(stk.pop()); lastNode.setAsLiteral(); lastNode.discard(); } else { try { /** * take a stab in the dark and try and load the class */ lastNode.setLiteralValue(createClass((String) lastNode.getLiteralValue())); lastNode.setAsLiteral(); lastNode.discard(); } catch (ClassNotFoundException e) { /** * Just fail through. */ } } } if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) { lastNode.discard(); captureToEOS(); return new TypedVarNode(subArray(start, cursor), fields, (Class) lastNode.getLiteralValue()); } throw new ParseException("unknown class: " + lastNode.getLiteralValue()); } else { return lastNode = new AssignmentNode(subArray(start, cursor), fields); } } } } /** * Produce the token. */ trimWhitespace(); return createPropertyToken(start, cursor); } else switch (expr[cursor]) { case'@': { start++; captureToEOT(); String interceptorName = new String(expr, start, cursor - start); if (getParserContext().getInterceptors() == null || !getParserContext().getInterceptors(). containsKey(interceptorName)) { throw new CompileException("reference to undefined interceptor: " + interceptorName, expr, cursor); } return lastNode = new InterceptorWrapper(getParserContext().getInterceptors().get(interceptorName), nextToken()); } case'=': return createToken(expr, start, (cursor += 2), fields); case'-': if (isAt('-', 1)) { start = cursor += 2; captureToEOT(); return lastNode = new PreFixDecNode(subArray(start, cursor), fields); } else if ((cursor > 0 && !isWhitespace(lookBehind(1))) || !isDigit(lookAhead(1))) { return createToken(expr, start, cursor++ + 1, fields); } else if ((cursor - 1) < 0 || (!isDigit(lookBehind(1))) && isDigit(lookAhead(1))) { cursor++; break; } case'+': if (isAt('+', 1)) { start = cursor += 2; captureToEOT(); return lastNode = new PreFixIncNode(subArray(start, cursor), fields); } return createToken(expr, start, cursor++ + 1, fields); case'*': if (isAt('*', 1)) { cursor++; } return createToken(expr, start, cursor++ + 1, fields); case';': cursor++; lastWasIdentifier = false; return lastNode = new EndOfStatement(); case'#': case'/': if (isAt(expr[cursor], 1)) { /** * Handle single line comments. */ while (cursor < length && expr[cursor] != '\n') cursor++; if (debugSymbols) { line = getParserContext().getLineCount(); skipWhitespaceWithLineAccounting(); // getParserContext().setLineCount(line); if (lastNode instanceof LineLabel) { getParserContext().getLastLineLabel().setLineNumber(line); getParserContext().addKnownLine(line); } lastWasComment = true; getParserContext().setLineCount(line); } else if (cursor < length) { skipWhitespace(); } if ((start = cursor) >= length) return null; continue; } else if (expr[cursor] == '/' && isAt('*', 1)) { /** * Handle multi-line comments. */ int len = length - 1; /** * This probably seems highly redundant, but sub-compilations within the same * source will spawn a new compiler, and we need to sync this with the * parser context; */ if (debugSymbols) { line = getParserContext().getLineCount(); } while (true) { cursor++; /** * Since multi-line comments may cross lines, we must keep track of any line-break * we encounter. */ if (debugSymbols) { skipWhitespaceWithLineAccounting(); } if (cursor == len) { throw new CompileException("unterminated block comment", expr, cursor); } if (expr[cursor] == '*' && isAt('/', 1)) { if ((cursor += 2) >= length) return null; skipWhitespaceWithLineAccounting(); start = cursor; break; } } if (debugSymbols) { getParserContext().setLineCount(line); if (lastNode instanceof LineLabel) { getParserContext().getLastLineLabel().setLineNumber(line); getParserContext().addKnownLine(line); } lastWasComment = true; } continue; } case'?': case':': case'^': case'%': { return createToken(expr, start, cursor++ + 1, fields); } case'(': { cursor++; boolean singleToken = true; boolean lastWS = false; skipWhitespace(); for (brace = 1; cursor < length && brace > 0; cursor++) { switch (expr[cursor]) { case'(': brace++; break; case')': brace--; break; case'\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case'"': cursor = captureStringLiteral('"', expr, cursor, length); break; case'i': if (isAt('n', 1) && isWhitespace(lookAhead(2))) { fields |= ASTNode.FOLD; for (int level = brace; cursor < length; cursor++) { switch (expr[cursor]) { case'(': brace++; break; case')': if (--brace < level) { if (lookAhead(1) == '.') { ASTNode node = createToken(expr, trimRight(start), (start = cursor++), ASTNode.FOLD); captureToEOT(); return lastNode = new Union(expr, trimRight(start + 2), cursor, fields, node); } else { return createToken(expr, trimRight(start), cursor++, ASTNode.FOLD); } } break; case'\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case'"': cursor = captureStringLiteral('\'', expr, cursor, length); break; } } } break; default: /** * Check to see if we should disqualify this current token as a potential * type-cast candidate. */ if (lastWS || !isIdentifierPart(expr[cursor])) { singleToken = false; } else if (isWhitespace(expr[cursor])) { lastWS = true; skipWhitespace(); cursor--; } } } if (brace > 0) { throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor); } char[] _subset = null; if (singleToken) { int st; String tokenStr = new String(_subset = subset(expr, st = trimRight(start + 1), trimLeft(cursor - 1) - st)); if (getParserContext().hasImport(tokenStr)) { start = cursor; captureToEOS(); return lastNode = new TypeCast(expr, start, cursor, fields, getParserContext().getImport(tokenStr)); } else { try { /** * * take a stab in the dark and try and load the class */ int _start = cursor; captureToEOS(); return lastNode = new TypeCast(expr, _start, cursor, fields, createClass(tokenStr)); } catch (ClassNotFoundException e) { /** * Just fail through. */ } } } if (_subset != null) { return handleUnion(new Substatement(_subset, fields)); } else { return handleUnion(new Substatement(subset(expr, start = trimRight(start + 1), trimLeft(cursor - 1) - start), fields)); } } case'}': case']': case')': { throw new ParseException("unbalanced braces", expr, cursor); } case'>': { if (expr[cursor + 1] == '>') { if (expr[cursor += 2] == '>') cursor++; return createToken(expr, start, cursor, fields); } else if (expr[cursor + 1] == '=') { return createToken(expr, start, cursor += 2, fields); } else { return createToken(expr, start, ++cursor, fields); } } case'<': { if (expr[++cursor] == '<') { if (expr[++cursor] == '<') cursor++; return createToken(expr, start, cursor, fields); } else if (expr[cursor] == '=') { return createToken(expr, start, ++cursor, fields); } else { return createToken(expr, start, cursor, fields); } } case'\'': cursor = captureStringLiteral('\'', expr, cursor, length); return lastNode = new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class); case'"': cursor = captureStringLiteral('"', expr, cursor, length); return lastNode = new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class); case'&': { if (expr[cursor++ + 1] == '&') { return createToken(expr, start, ++cursor, fields); } else { return createToken(expr, start, cursor, fields); } } case'|': { if (expr[cursor++ + 1] == '|') { return createToken(expr, start, ++cursor, fields); } else { return createToken(expr, start, cursor, fields); } } case'~': if ((cursor - 1 < 0 || !isIdentifierPart(lookBehind(1))) && isDigit(expr[cursor + 1])) { fields |= ASTNode.INVERT; start++; cursor++; break; } else if (expr[cursor + 1] == '(') { fields |= ASTNode.INVERT; start = ++cursor; continue; } else { if (expr[cursor + 1] == '=') cursor++; return createToken(expr, start, ++cursor, fields); } case'!': { if (isIdentifierPart(expr[++cursor]) || expr[cursor] == '(') { start = cursor; fields |= ASTNode.NEGATION; continue; } else if (expr[cursor] != '=') throw new CompileException("unexpected operator '!'", expr, cursor, null); else { return createToken(expr, start, ++cursor, fields); } } case'[': case'{': if (balancedCapture(expr[cursor]) == -1) { if (cursor >= length) cursor--; throw new CompileException("unbalanced brace: in inline map/list/array creation", expr, cursor); } if (lookAhead(1) == '.') { InlineCollectionNode n = new InlineCollectionNode(expr, start, start = ++cursor, fields); captureToEOT(); return lastNode = new Union(expr, start + 1, cursor, fields, n); } else { return lastNode = new InlineCollectionNode(expr, start, ++cursor, fields); } default: cursor++; } } return createPropertyToken(start, cursor); }
protected ASTNode nextToken() { /** * If the cursor is at the end of the expression, we have nothing more to do: * return null. */ if (cursor >= length) { // if (debugSymbols && lastNode != null) { // /** // * Produce a trailing line label. This allows debuggers to step into the last line. // */ // lastNode = null; // return new LineLabel(getParserContext().getSourceFile(), getParserContext().getLineCount() + 1); // } return null; } else if (!splitAccumulator.isEmpty()) { return lastNode = (ASTNode) splitAccumulator.pop(); } int brace, start = cursor; /** * Because of parser recursion for sub-expression parsing, we sometimes need to remain * certain field states. We do not reset for assignments, boolean mode, list creation or * a capture only mode. */ fields = fields & (ASTNode.INLINE_COLLECTION | ASTNode.COMPILE_IMMEDIATE); boolean capture = false, union = false; if (debugSymbols) { if (!lastWasLineLabel) { if (getParserContext().getSourceFile() == null) { throw new CompileException("unable to produce debugging symbols: source name must be provided."); } ParserContext pCtx = getParserContext(); line = pCtx.getLineCount(); if (expr[cursor] == '\n' || expr[cursor] == '\r') { skipWhitespaceWithLineAccounting(); } pCtx.setLineCount(line); if (!pCtx.isKnownLine(pCtx.getSourceFile(), line)) { lastWasLineLabel = true; pCtx.setLineAndOffset(line, cursor); pCtx.addKnownLine(pCtx.getSourceFile(), line); LineLabel ll = new LineLabel(pCtx.getSourceFile(), line); pCtx.setLastLineLabel(ll); return lastNode = ll; } } else { lastWasComment = lastWasLineLabel = false; } } /** * Skip any whitespace currently under the starting point. */ while (start < length && isWhitespace(expr[start])) start++; /** * From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for * trouble unless you really know what you're doing. */ for (cursor = start; cursor < length;) { if (isIdentifierPart(expr[cursor])) { /** * If the current character under the cursor is a valid * part of an identifier, we keep capturing. */ capture = true; cursor++; } else if (capture) { String t; if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) { switch (OPERATORS.get(t)) { case NEW: start = cursor + 1; captureToEOT(); return lastNode = new NewObjectNode(subArray(start, cursor), fields); case ASSERT: start = cursor + 1; captureToEOS(); return lastNode = new AssertNode(subArray(start, cursor--), fields); case RETURN: start = cursor + 1; captureToEOS(); return lastNode = new ReturnNode(subArray(start, cursor), fields); case IF: fields |= ASTNode.BLOCK_IF; return captureCodeBlock(); case FOREACH: fields |= ASTNode.BLOCK_FOREACH; return captureCodeBlock(); case WITH: fields |= ASTNode.BLOCK_WITH; return captureCodeBlock(); case IMPORT: start = cursor + 1; captureToEOS(); ImportNode importNode = new ImportNode(subArray(start, cursor--), fields); getParserContext().addImport(getSimpleClassName(importNode.getImportClass()), importNode.getImportClass()); return importNode; case IMPORT_STATIC: start = cursor + 1; captureToEOS(); return lastNode = new StaticImportNode(subArray(start, cursor--), fields); } } /** * If we *were* capturing a token, and we just hit a non-identifier * character, we stop and figure out what to do. */ skipWhitespace(); if (expr[cursor] == '(') { fields |= ASTNode.METHOD; /** * If the current token is a method call or a constructor, we * simply capture the entire parenthesized range and allow * reduction to be dealt with through sub-parsing the property. */ cursor++; for (brace = 1; cursor < length && brace > 0;) { switch (expr[cursor++]) { case'(': brace++; break; case')': brace--; break; /** * String literals need to be skipped over or encountering a ')' in a String * will cause an explosion. */ case'\'': cursor = captureStringLiteral('\'', expr, cursor, length) + 1; break; case'"': cursor = captureStringLiteral('"', expr, cursor, length) + 1; break; } } /** * If the brace counter is greater than 0, we know we have * unbalanced braces in the expression. So we throw a * optimize error now. */ if (brace > 0) throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor); } /** * If we encounter any of the following cases, we are still dealing with * a contiguous token. */ String name; if (cursor < length) { switch (expr[cursor]) { case'+': switch (lookAhead(1)) { case'+': ASTNode n = new PostFixIncNode(subArray(start, cursor), fields); cursor += 2; return lastNode = n; case'=': name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields, Operator.ADD, t); } else { return lastNode = new AssignmentNode(subArray(start, cursor), fields, Operator.ADD, name); } } break; case'-': switch (lookAhead(1)) { case'-': ASTNode n = new PostFixDecNode(subArray(start, cursor), fields); cursor += 2; return lastNode = n; case'=': name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); return lastNode = new AssignSub(subArray(start, cursor), fields, name); } break; case'*': if (isAt('=', 1)) { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); return lastNode = new AssignMult(subArray(start, cursor), fields, name); } break; case'/': if (isAt('=', 1)) { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); return lastNode = new AssignDiv(subArray(start, cursor), fields, name); } break; case']': case'[': balancedCapture('['); cursor++; continue; case'.': union = true; cursor++; continue; case'~': if (isAt('=', 1)) { char[] stmt = subArray(start, trimLeft(cursor)); start = cursor += 2; captureToEOT(); return lastNode = new RegExMatch(stmt, fields, subArray(start, cursor)); } break; case'=': if (isAt('+', 1)) { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); return lastNode = new AssignAdd(subArray(start, cursor), fields, name); } if (greedy && !isAt('=', 1)) { cursor++; fields |= ASTNode.ASSIGN; skipWhitespace(); captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields); } else if (lastWasIdentifier) { /** * Check for typing information. */ if (lastNode.getLiteralValue() instanceof String) { if (getParserContext().hasImport((String) lastNode.getLiteralValue())) { lastNode.setLiteralValue(getParserContext().getImport((String) lastNode.getLiteralValue())); lastNode.setAsLiteral(); lastNode.discard(); } else if (stk != null && stk.peek() instanceof Class) { lastNode.setLiteralValue(stk.pop()); lastNode.setAsLiteral(); lastNode.discard(); } else { try { /** * take a stab in the dark and try and load the class */ lastNode.setLiteralValue(createClass((String) lastNode.getLiteralValue())); lastNode.setAsLiteral(); lastNode.discard(); } catch (ClassNotFoundException e) { /** * Just fail through. */ } } } if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) { lastNode.discard(); captureToEOS(); return new TypedVarNode(subArray(start, cursor), fields, (Class) lastNode.getLiteralValue()); } throw new ParseException("unknown class: " + lastNode.getLiteralValue()); } else { return lastNode = new AssignmentNode(subArray(start, cursor), fields); } } } } /** * Produce the token. */ trimWhitespace(); return createPropertyToken(start, cursor); } else switch (expr[cursor]) { case'@': { start++; captureToEOT(); String interceptorName = new String(expr, start, cursor - start); if (getParserContext().getInterceptors() == null || !getParserContext().getInterceptors(). containsKey(interceptorName)) { throw new CompileException("reference to undefined interceptor: " + interceptorName, expr, cursor); } return lastNode = new InterceptorWrapper(getParserContext().getInterceptors().get(interceptorName), nextToken()); } case'=': return createToken(expr, start, (cursor += 2), fields); case'-': if (isAt('-', 1)) { start = cursor += 2; captureToEOT(); return lastNode = new PreFixDecNode(subArray(start, cursor), fields); } else if ((cursor > 0 && !isWhitespace(lookBehind(1))) || !isDigit(lookAhead(1))) { return createToken(expr, start, cursor++ + 1, fields); } else if ((cursor - 1) < 0 || (!isDigit(lookBehind(1))) && isDigit(lookAhead(1))) { cursor++; break; } case'+': if (isAt('+', 1)) { start = cursor += 2; captureToEOT(); return lastNode = new PreFixIncNode(subArray(start, cursor), fields); } return createToken(expr, start, cursor++ + 1, fields); case'*': if (isAt('*', 1)) { cursor++; } return createToken(expr, start, cursor++ + 1, fields); case';': cursor++; lastWasIdentifier = false; return lastNode = new EndOfStatement(); case'#': case'/': if (isAt(expr[cursor], 1)) { /** * Handle single line comments. */ while (cursor < length && expr[cursor] != '\n') cursor++; if (debugSymbols) { line = getParserContext().getLineCount(); skipWhitespaceWithLineAccounting(); // getParserContext().setLineCount(line); if (lastNode instanceof LineLabel) { getParserContext().getLastLineLabel().setLineNumber(line); getParserContext().addKnownLine(line); } lastWasComment = true; getParserContext().setLineCount(line); } else if (cursor < length) { skipWhitespace(); } if ((start = cursor) >= length) return null; continue; } else if (expr[cursor] == '/' && isAt('*', 1)) { /** * Handle multi-line comments. */ int len = length - 1; /** * This probably seems highly redundant, but sub-compilations within the same * source will spawn a new compiler, and we need to sync this with the * parser context; */ if (debugSymbols) { line = getParserContext().getLineCount(); } while (true) { cursor++; /** * Since multi-line comments may cross lines, we must keep track of any line-break * we encounter. */ if (debugSymbols) { skipWhitespaceWithLineAccounting(); } if (cursor == len) { throw new CompileException("unterminated block comment", expr, cursor); } if (expr[cursor] == '*' && isAt('/', 1)) { if ((cursor += 2) >= length) return null; skipWhitespaceWithLineAccounting(); start = cursor; break; } } if (debugSymbols) { getParserContext().setLineCount(line); if (lastNode instanceof LineLabel) { getParserContext().getLastLineLabel().setLineNumber(line); getParserContext().addKnownLine(line); } lastWasComment = true; } continue; } case'?': case':': case'^': case'%': { return createToken(expr, start, cursor++ + 1, fields); } case'(': { cursor++; boolean singleToken = true; boolean lastWS = false; skipWhitespace(); for (brace = 1; cursor < length && brace > 0; cursor++) { switch (expr[cursor]) { case'(': brace++; break; case')': brace--; break; case'\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case'"': cursor = captureStringLiteral('"', expr, cursor, length); break; case'i': if (isAt('n', 1) && isWhitespace(lookAhead(2))) { fields |= ASTNode.FOLD; for (int level = brace; cursor < length; cursor++) { switch (expr[cursor]) { case'(': brace++; break; case')': if (--brace < level) { if (lookAhead(1) == '.') { ASTNode node = createToken(expr, trimRight(start), (start = cursor++), ASTNode.FOLD); captureToEOT(); return lastNode = new Union(expr, trimRight(start + 2), cursor, fields, node); } else { return createToken(expr, trimRight(start), cursor++, ASTNode.FOLD); } } break; case'\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case'"': cursor = captureStringLiteral('\'', expr, cursor, length); break; } } } break; default: /** * Check to see if we should disqualify this current token as a potential * type-cast candidate. */ if (lastWS || !isIdentifierPart(expr[cursor])) { singleToken = false; } else if (isWhitespace(expr[cursor])) { lastWS = true; skipWhitespace(); cursor--; } } } if (brace > 0) { throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor); } char[] _subset = null; if (singleToken) { int st; String tokenStr = new String(_subset = subset(expr, st = trimRight(start + 1), trimLeft(cursor - 1) - st)); if (getParserContext().hasImport(tokenStr)) { start = cursor; captureToEOS(); return lastNode = new TypeCast(expr, start, cursor, fields, getParserContext().getImport(tokenStr)); } else { try { /** * * take a stab in the dark and try and load the class */ int _start = cursor; captureToEOS(); return lastNode = new TypeCast(expr, _start, cursor, fields, createClass(tokenStr)); } catch (ClassNotFoundException e) { /** * Just fail through. */ } } } if (_subset != null) { return handleUnion(new Substatement(_subset, fields)); } else { return handleUnion(new Substatement(subset(expr, start = trimRight(start + 1), trimLeft(cursor - 1) - start), fields)); } } case'}': case']': case')': { throw new ParseException("unbalanced braces", expr, cursor); } case'>': { if (expr[cursor + 1] == '>') { if (expr[cursor += 2] == '>') cursor++; return createToken(expr, start, cursor, fields); } else if (expr[cursor + 1] == '=') { return createToken(expr, start, cursor += 2, fields); } else { return createToken(expr, start, ++cursor, fields); } } case'<': { if (expr[++cursor] == '<') { if (expr[++cursor] == '<') cursor++; return createToken(expr, start, cursor, fields); } else if (expr[cursor] == '=') { return createToken(expr, start, ++cursor, fields); } else { return createToken(expr, start, cursor, fields); } } case'\'': cursor = captureStringLiteral('\'', expr, cursor, length); return lastNode = new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class); case'"': cursor = captureStringLiteral('"', expr, cursor, length); return lastNode = new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class); case'&': { if (expr[cursor++ + 1] == '&') { return createToken(expr, start, ++cursor, fields); } else { return createToken(expr, start, cursor, fields); } } case'|': { if (expr[cursor++ + 1] == '|') { return createToken(expr, start, ++cursor, fields); } else { return createToken(expr, start, cursor, fields); } } case'~': if ((cursor - 1 < 0 || !isIdentifierPart(lookBehind(1))) && isDigit(expr[cursor + 1])) { fields |= ASTNode.INVERT; start++; cursor++; break; } else if (expr[cursor + 1] == '(') { fields |= ASTNode.INVERT; start = ++cursor; continue; } else { if (expr[cursor + 1] == '=') cursor++; return createToken(expr, start, ++cursor, fields); } case'!': { if (isIdentifierPart(expr[++cursor]) || expr[cursor] == '(') { start = cursor; fields |= ASTNode.NEGATION; continue; } else if (expr[cursor] != '=') throw new CompileException("unexpected operator '!'", expr, cursor, null); else { return createToken(expr, start, ++cursor, fields); } } case'[': case'{': if (balancedCapture(expr[cursor]) == -1) { if (cursor >= length) cursor--; throw new CompileException("unbalanced brace: in inline map/list/array creation", expr, cursor); } if (lookAhead(1) == '.') { InlineCollectionNode n = new InlineCollectionNode(expr, start, start = ++cursor, fields); captureToEOT(); return lastNode = new Union(expr, start + 1, cursor, fields, n); } else { return lastNode = new InlineCollectionNode(expr, start, ++cursor, fields); } default: cursor++; } } return createPropertyToken(start, cursor); }
diff --git a/src/cytoscape/CytoscapeInit.java b/src/cytoscape/CytoscapeInit.java index 9029418a7..eba9b7b46 100644 --- a/src/cytoscape/CytoscapeInit.java +++ b/src/cytoscape/CytoscapeInit.java @@ -1,628 +1,628 @@ /* File: CytoscapeInit.java Copyright (c) 2006, The Cytoscape Consortium (www.cytoscape.org) The Cytoscape Consortium is: - Institute for Systems Biology - University of California San Diego - Memorial Sloan-Kettering Cancer Center - Institut Pasteur - Agilent Technologies This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder is on an "as is" basis, and the Institute for Systems Biology and the Whitehead Institute have no obligations to provide maintenance, support, updates, enhancements or modifications. In no event shall the Institute for Systems Biology and the Whitehead Institute be liable to any party for direct, indirect, special, incidental or consequential damages, including lost profits, arising out of the use of this software and its documentation, even if the Institute for Systems Biology and the Whitehead Institute have been advised of the possibility of such damage. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ package cytoscape; import cytoscape.data.readers.CytoscapeSessionReader; import cytoscape.dialogs.logger.LoggerDialog; import cytoscape.init.CyInitParams; import cytoscape.logger.LogLevel; import cytoscape.logger.CyLogger; import cytoscape.logger.ConsoleLogger; import cytoscape.plugin.PluginManager; import cytoscape.util.FileUtil; import cytoscape.util.shadegrown.WindowUtilities; import java.awt.Cursor; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; //import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; //import java.util.Set; import javax.swing.ImageIcon; /** * <p> * Cytoscape Init is responsible for starting Cytoscape in a way that makes * sense. * </p> * <p> * The comments below are more hopeful than accurate. We currently do not * support a "headless" mode (meaning there is no GUI). We do, however, hope to * support this in the future. * </p> * * <p> * The two main modes of running Cytoscape are either in "headless" mode or in * "script" mode. This class will use the command-line options to figure out * which mode is desired, and run things accordingly. * </p> * * The order for doing things will be the following:<br> * <ol> * <li>deterimine script mode, or headless mode</li> * <li>get options from properties files</li> * <li>get options from command line ( these overwrite properties )</li> * <li>Load all Networks</li> * <li>Load all data</li> * <li>Load all Plugins</li> * <li>Initialize all plugins, in order if specified.</li> * <li>Start Desktop/Print Output exit.</li> * </ol> * * @since Cytoscape 1.0 * @author Cytoscape Core Team */ public class CytoscapeInit { private static final String SPLASH_SCREEN_LOCATION = "/cytoscape/images/CytoscapeSplashScreen.png"; private static Properties properties; private static Properties visualProperties; private static CyLogger logger = null; static { logger = CyLogger.getLogger(CytoscapeInit.class); logger.info("CytoscapeInit static initialization"); initProperties(); } private static CyInitParams initParams; // Most-Recently-Used directories and files private static File mrud; private static File mruf; // Error message private static String ErrorMsg = ""; /** * Creates a new CytoscapeInit object. */ public CytoscapeInit() { } /** * Cytoscape Init must be initialized using the command line arguments. * * @param args * the arguments from the command line * @return false, if we fail to initialize for some reason */ public boolean init(CyInitParams params) { long begintime = System.currentTimeMillis(); if (logger == null) logger = CyLogger.getLogger(CytoscapeInit.class); try { initParams = params; // setup properties initProperties(); // Reinitialize so we can pick up the debug flag logger = CyLogger.getLogger(CytoscapeInit.class); properties.putAll(initParams.getProps()); visualProperties.putAll(initParams.getVizProps()); // Build the OntologyServer. Cytoscape.buildOntologyServer(); // get the manager so it can test for webstart before menus are // created (little hacky) PluginManager.getPluginManager(); // see if we are in headless mode // show splash screen, if appropriate /* * Initialize as GUI mode */ if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { final ImageIcon image = new ImageIcon(this.getClass() .getResource(SPLASH_SCREEN_LOCATION)); WindowUtilities.showSplash(image, 8000); // Register the console logger, if we're not told not to String consoleLogger = properties.getProperty("logger.console"); - if (consoleLogger == null || Boolean.getBoolean(consoleLogger)) { + if (consoleLogger == null || Boolean.parseBoolean(consoleLogger)) { logger.addLogHandler(ConsoleLogger.getLogger(), LogLevel.LOG_DEBUG); } else { logger.info("Log information can now be found in the Help->Error Console menu"); } // Register the logger dialog as a log handler logger.addLogHandler(LoggerDialog.getLoggerDialog(), LogLevel.LOG_DEBUG); /* * Create Desktop. This includes Vizmapper GUI initialization. */ Cytoscape.getDesktop(); // set the wait cursor Cytoscape.getDesktop().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); setUpAttributesChangedListener(); } else { // Force logging to the console logger.addLogHandler(ConsoleLogger.getLogger(), LogLevel.LOG_DEBUG); } logger.info("init mode: " + initParams.getMode()); PluginManager mgr = PluginManager.getPluginManager(); try { logger.info("Updating plugins..."); mgr.delete(); } catch (cytoscape.plugin.ManagerException me) { logger.warn("Error updating plugins: "+me.getMessage()); } mgr.install(); logger.info("loading plugins...."); /* * TODO smart plugin loading. If there are multiple of the same * plugin (this will only work in the .cytoscape directory) load the * newest version first. Should be able to examine the directories * for this information. All installed plugins are named like * 'MyPlugin-1.0' currently this isn't necessary as old version are * not kept around */ List<String> InstalledPlugins = new ArrayList<String>(); // load from those listed on the command line InstalledPlugins.addAll(initParams.getPlugins()); // Get all directories where plugins have been installed // going to have to be a little smart...themes contain their plugins // in subdirectories List<cytoscape.plugin.DownloadableInfo> MgrInstalledPlugins = mgr.getDownloadables(cytoscape.plugin.PluginStatus.CURRENT); for (cytoscape.plugin.DownloadableInfo dInfo : MgrInstalledPlugins) { if (dInfo.getCategory().equals(cytoscape.plugin.Category.CORE.getCategoryText())) continue; switch (dInfo.getType()) { // TODO get rid of switches case PLUGIN: InstalledPlugins.add(((cytoscape.plugin.PluginInfo) dInfo) .getInstallLocation()); break; case THEME: cytoscape.plugin.ThemeInfo tInfo = (cytoscape.plugin.ThemeInfo) dInfo; for (cytoscape.plugin.PluginInfo plugin : tInfo.getPlugins()) { InstalledPlugins.add(plugin.getInstallLocation()); } break; } } mgr.loadPlugins(InstalledPlugins); List<Throwable> pluginLoadingErrors = mgr.getLoadingErrors(); for (Throwable t : pluginLoadingErrors) { logger.warn("Plugin loading error: "+t.toString()); } mgr.clearErrorList(); logger.info("loading session..."); boolean sessionLoaded = false; if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { loadSessionFile(); sessionLoaded = true; } logger.info("loading networks..."); loadNetworks(); logger.info("loading attributes..."); loadAttributes(); logger.info("loading expression files..."); loadExpressionFiles(); if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { if(sessionLoaded == false) { logger.info("Initializing VizMapper..."); initVizmapper(); } } } finally { // Always restore the cursor and hide the splash, even there is // exception if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { WindowUtilities.hideSplash(); Cytoscape.getDesktop().setCursor(Cursor.getDefaultCursor()); // to clean up anything that the plugins have messed up Cytoscape.getDesktop().repaint(); } } long endtime = System.currentTimeMillis() - begintime; logger.info("Cytoscape initialized successfully in: " + endtime + " ms"); Cytoscape.firePropertyChange(Cytoscape.CYTOSCAPE_INITIALIZED, null, null); return true; } /** * Returns the CyInitParams object used to initialize Cytoscape. */ public static CyInitParams getCyInitParams() { return initParams; } /** * Returns the properties used by Cytoscape, the result of cytoscape.props * and command line options. */ public static Properties getProperties() { return properties; } /** * @return the most recently used directory */ public static File getMRUD() { if (mrud == null) mrud = new File(properties.getProperty("mrud", System.getProperty("user.dir"))); return mrud; } /** * @return the most recently used file */ public static File getMRUF() { return mruf; } /** * @param mrud * the most recently used directory */ public static void setMRUD(File mrud_new) { mrud = mrud_new; } /** * @param mruf * the most recently used file */ public static void setMRUF(File mruf_new) { mruf = mruf_new; } /** * Within the .cytoscape directory create a version-specific directory * * @return the directory ".cytoscape/[cytoscape version] */ public static File getConfigVersionDirectory() { File Parent = getConfigDirectory(); File VersionDir = new File(Parent, (new CytoscapeVersion()).getMajorVersion()); VersionDir.mkdir(); return VersionDir; } /** * If .cytoscape directory does not exist, it creates it and returns it * * @return the directory ".cytoscape" in the users home directory. */ public static File getConfigDirectory() { File dir = null; try { String dirName = properties.getProperty("alternative.config.dir", System.getProperty("user.home")); File parent_dir = new File(dirName, ".cytoscape"); if (parent_dir.mkdir()) logger.info("Parent_Dir: " + parent_dir + " created."); return parent_dir; } catch (Exception e) { logger.warn("error getting config directory"); } return null; } /** * DOCUMENT ME! * * @param file_name * DOCUMENT ME! * * @return DOCUMENT ME! */ public static File getConfigFile(String file_name) { try { File parent_dir = getConfigDirectory(); File file = new File(parent_dir, file_name); if (file.createNewFile()) logger.info("Config file: " + file + " created."); return file; } catch (Exception e) { logger.warn("error getting config file:" + file_name); } return null; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public static Properties getVisualProperties() { return visualProperties; } private static void loadStaticProperties(String defaultName, Properties props) { if (props == null) { logger.info("input props is null"); props = new Properties(); } String tryName = ""; try { // load the props from the jar file tryName = "cytoscape.jar"; // This somewhat unusual way of getting the ClassLoader is because // other methods don't work from WebStart. ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL vmu = null; if (cl != null) vmu = cl.getResource(defaultName); else logger.warn("ClassLoader for reading cytoscape.jar is null"); if (vmu != null) // We'd like to use URLUtil.getBasicInputStream() to get // InputStream, but it is too early in the initialization of // Cytoscape and vmu is most likely out of a local resource, so // get // it directly: props.load(vmu.openStream()); else logger.warn("couldn't read " + defaultName + " from " + tryName); // load the props file from $HOME/.cytoscape tryName = "$HOME/.cytoscape"; File vmp = CytoscapeInit.getConfigFile(defaultName); if (vmp != null) props.load(new FileInputStream(vmp)); else logger.warn("couldn't read " + defaultName + " from " + tryName); } catch (IOException ioe) { logger.warn("couldn't open '" + tryName + " " + defaultName + "' file: "+ioe.getMessage()+" - creating a hardcoded default"); } } private static void loadExpressionFiles() { // load expression data if specified List ef = initParams.getExpressionFiles(); if ((ef != null) && (ef.size() > 0)) { for (Iterator iter = ef.iterator(); iter.hasNext();) { String expDataFilename = (String) iter.next(); if (expDataFilename != null) { try { Cytoscape.loadExpressionData(expDataFilename, true); } catch (Exception e) { logger.error("Couldn't open expression file: '"+expDataFilename+"': "+e.getMessage()); } } } } } private boolean loadSessionFile() { String sessionFile = initParams.getSessionFile(); try { String sessionName = ""; if (sessionFile != null) { CytoscapeSessionReader reader = null; if (sessionFile.matches(FileUtil.urlPattern)) { URL u = new URL(sessionFile); reader = new CytoscapeSessionReader(u); sessionName = u.getFile(); } else { Cytoscape.setCurrentSessionFileName(sessionFile); File shortName = new File(sessionFile); URL sessionURL = shortName.toURL(); reader = new CytoscapeSessionReader(sessionURL); sessionName = shortName.getName(); } if (reader != null) { reader.read(); Cytoscape.getDesktop() .setTitle("Cytoscape Desktop (Session Name: " + sessionName + ")"); return true; } } } catch (Exception e) { logger.error("couldn't create session from file '" + sessionFile + "': "+e.getMessage()); } finally { Cytoscape.getDesktop().getVizMapperUI().initVizmapperGUI(); System.gc(); } return false; } private static void initProperties() { if (properties == null) { properties = new Properties(); loadStaticProperties("cytoscape.props", properties); } if (visualProperties == null) { visualProperties = new Properties(); loadStaticProperties("vizmap.props", visualProperties); } } private void setUpAttributesChangedListener() { /* * This cannot be done in CytoscapeDesktop construction (like the other * menus) because we need CytoscapeDesktop created first. This is * because CytoPanel menu item listeners need to register for CytoPanel * events via a CytoPanel reference, and the only way to get a CytoPanel * reference is via CytoscapeDeskop: * Cytoscape.getDesktop().getCytoPanel(...) * Cytoscape.getDesktop().getCyMenus().initCytoPanelMenus(); Add a * listener that will apply vizmaps every time attributes change */ PropertyChangeListener attsChangeListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName().equals(Cytoscape.ATTRIBUTES_CHANGED)) { // apply vizmaps Cytoscape.getCurrentNetworkView().redrawGraph(false, true); } } }; Cytoscape.getSwingPropertyChangeSupport().addPropertyChangeListener(attsChangeListener); } // Load all requested networks private void loadNetworks() { for (Iterator i = initParams.getGraphFiles().iterator(); i.hasNext();) { String net = (String) i.next(); logger.info("Load: " + net); CyNetwork network = null; boolean createView = false; if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) createView = true; if (net.matches(FileUtil.urlPattern)) { try { network = Cytoscape.createNetworkFromURL(new URL(net), createView); } catch (Exception mue) { logger.error("Couldn't load network from URL '"+net+"': " + mue.getMessage()); } } else { try { network = Cytoscape.createNetworkFromFile(net, createView); } catch (Exception mue) { logger.error("Couldn't load network from file '"+net+"': " + mue.getMessage()); } } // This is for browser and other plugins. Object[] ret_val = new Object[3]; ret_val[0] = network; ret_val[1] = net; ret_val[2] = new Integer(0); Cytoscape.firePropertyChange(Cytoscape.NETWORK_LOADED, null, ret_val); } } // load any specified data attribute files private void loadAttributes() { try { Cytoscape.loadAttributes((String[]) initParams.getNodeAttributeFiles() .toArray(new String[] { }), (String[]) initParams.getEdgeAttributeFiles() .toArray(new String[] { })); } catch (Exception ex) { logger.error("failure loading specified attributes: "+ex.getMessage()); } } private void initVizmapper() { Cytoscape.getDesktop().getVizMapperUI().initVizmapperGUI(); } }
true
true
public boolean init(CyInitParams params) { long begintime = System.currentTimeMillis(); if (logger == null) logger = CyLogger.getLogger(CytoscapeInit.class); try { initParams = params; // setup properties initProperties(); // Reinitialize so we can pick up the debug flag logger = CyLogger.getLogger(CytoscapeInit.class); properties.putAll(initParams.getProps()); visualProperties.putAll(initParams.getVizProps()); // Build the OntologyServer. Cytoscape.buildOntologyServer(); // get the manager so it can test for webstart before menus are // created (little hacky) PluginManager.getPluginManager(); // see if we are in headless mode // show splash screen, if appropriate /* * Initialize as GUI mode */ if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { final ImageIcon image = new ImageIcon(this.getClass() .getResource(SPLASH_SCREEN_LOCATION)); WindowUtilities.showSplash(image, 8000); // Register the console logger, if we're not told not to String consoleLogger = properties.getProperty("logger.console"); if (consoleLogger == null || Boolean.getBoolean(consoleLogger)) { logger.addLogHandler(ConsoleLogger.getLogger(), LogLevel.LOG_DEBUG); } else { logger.info("Log information can now be found in the Help->Error Console menu"); } // Register the logger dialog as a log handler logger.addLogHandler(LoggerDialog.getLoggerDialog(), LogLevel.LOG_DEBUG); /* * Create Desktop. This includes Vizmapper GUI initialization. */ Cytoscape.getDesktop(); // set the wait cursor Cytoscape.getDesktop().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); setUpAttributesChangedListener(); } else { // Force logging to the console logger.addLogHandler(ConsoleLogger.getLogger(), LogLevel.LOG_DEBUG); } logger.info("init mode: " + initParams.getMode()); PluginManager mgr = PluginManager.getPluginManager(); try { logger.info("Updating plugins..."); mgr.delete(); } catch (cytoscape.plugin.ManagerException me) { logger.warn("Error updating plugins: "+me.getMessage()); } mgr.install(); logger.info("loading plugins...."); /* * TODO smart plugin loading. If there are multiple of the same * plugin (this will only work in the .cytoscape directory) load the * newest version first. Should be able to examine the directories * for this information. All installed plugins are named like * 'MyPlugin-1.0' currently this isn't necessary as old version are * not kept around */ List<String> InstalledPlugins = new ArrayList<String>(); // load from those listed on the command line InstalledPlugins.addAll(initParams.getPlugins()); // Get all directories where plugins have been installed // going to have to be a little smart...themes contain their plugins // in subdirectories List<cytoscape.plugin.DownloadableInfo> MgrInstalledPlugins = mgr.getDownloadables(cytoscape.plugin.PluginStatus.CURRENT); for (cytoscape.plugin.DownloadableInfo dInfo : MgrInstalledPlugins) { if (dInfo.getCategory().equals(cytoscape.plugin.Category.CORE.getCategoryText())) continue; switch (dInfo.getType()) { // TODO get rid of switches case PLUGIN: InstalledPlugins.add(((cytoscape.plugin.PluginInfo) dInfo) .getInstallLocation()); break; case THEME: cytoscape.plugin.ThemeInfo tInfo = (cytoscape.plugin.ThemeInfo) dInfo; for (cytoscape.plugin.PluginInfo plugin : tInfo.getPlugins()) { InstalledPlugins.add(plugin.getInstallLocation()); } break; } } mgr.loadPlugins(InstalledPlugins); List<Throwable> pluginLoadingErrors = mgr.getLoadingErrors(); for (Throwable t : pluginLoadingErrors) { logger.warn("Plugin loading error: "+t.toString()); } mgr.clearErrorList(); logger.info("loading session..."); boolean sessionLoaded = false; if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { loadSessionFile(); sessionLoaded = true; } logger.info("loading networks..."); loadNetworks(); logger.info("loading attributes..."); loadAttributes(); logger.info("loading expression files..."); loadExpressionFiles(); if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { if(sessionLoaded == false) { logger.info("Initializing VizMapper..."); initVizmapper(); } } } finally { // Always restore the cursor and hide the splash, even there is // exception if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { WindowUtilities.hideSplash(); Cytoscape.getDesktop().setCursor(Cursor.getDefaultCursor()); // to clean up anything that the plugins have messed up Cytoscape.getDesktop().repaint(); } } long endtime = System.currentTimeMillis() - begintime; logger.info("Cytoscape initialized successfully in: " + endtime + " ms"); Cytoscape.firePropertyChange(Cytoscape.CYTOSCAPE_INITIALIZED, null, null); return true; }
public boolean init(CyInitParams params) { long begintime = System.currentTimeMillis(); if (logger == null) logger = CyLogger.getLogger(CytoscapeInit.class); try { initParams = params; // setup properties initProperties(); // Reinitialize so we can pick up the debug flag logger = CyLogger.getLogger(CytoscapeInit.class); properties.putAll(initParams.getProps()); visualProperties.putAll(initParams.getVizProps()); // Build the OntologyServer. Cytoscape.buildOntologyServer(); // get the manager so it can test for webstart before menus are // created (little hacky) PluginManager.getPluginManager(); // see if we are in headless mode // show splash screen, if appropriate /* * Initialize as GUI mode */ if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { final ImageIcon image = new ImageIcon(this.getClass() .getResource(SPLASH_SCREEN_LOCATION)); WindowUtilities.showSplash(image, 8000); // Register the console logger, if we're not told not to String consoleLogger = properties.getProperty("logger.console"); if (consoleLogger == null || Boolean.parseBoolean(consoleLogger)) { logger.addLogHandler(ConsoleLogger.getLogger(), LogLevel.LOG_DEBUG); } else { logger.info("Log information can now be found in the Help->Error Console menu"); } // Register the logger dialog as a log handler logger.addLogHandler(LoggerDialog.getLoggerDialog(), LogLevel.LOG_DEBUG); /* * Create Desktop. This includes Vizmapper GUI initialization. */ Cytoscape.getDesktop(); // set the wait cursor Cytoscape.getDesktop().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); setUpAttributesChangedListener(); } else { // Force logging to the console logger.addLogHandler(ConsoleLogger.getLogger(), LogLevel.LOG_DEBUG); } logger.info("init mode: " + initParams.getMode()); PluginManager mgr = PluginManager.getPluginManager(); try { logger.info("Updating plugins..."); mgr.delete(); } catch (cytoscape.plugin.ManagerException me) { logger.warn("Error updating plugins: "+me.getMessage()); } mgr.install(); logger.info("loading plugins...."); /* * TODO smart plugin loading. If there are multiple of the same * plugin (this will only work in the .cytoscape directory) load the * newest version first. Should be able to examine the directories * for this information. All installed plugins are named like * 'MyPlugin-1.0' currently this isn't necessary as old version are * not kept around */ List<String> InstalledPlugins = new ArrayList<String>(); // load from those listed on the command line InstalledPlugins.addAll(initParams.getPlugins()); // Get all directories where plugins have been installed // going to have to be a little smart...themes contain their plugins // in subdirectories List<cytoscape.plugin.DownloadableInfo> MgrInstalledPlugins = mgr.getDownloadables(cytoscape.plugin.PluginStatus.CURRENT); for (cytoscape.plugin.DownloadableInfo dInfo : MgrInstalledPlugins) { if (dInfo.getCategory().equals(cytoscape.plugin.Category.CORE.getCategoryText())) continue; switch (dInfo.getType()) { // TODO get rid of switches case PLUGIN: InstalledPlugins.add(((cytoscape.plugin.PluginInfo) dInfo) .getInstallLocation()); break; case THEME: cytoscape.plugin.ThemeInfo tInfo = (cytoscape.plugin.ThemeInfo) dInfo; for (cytoscape.plugin.PluginInfo plugin : tInfo.getPlugins()) { InstalledPlugins.add(plugin.getInstallLocation()); } break; } } mgr.loadPlugins(InstalledPlugins); List<Throwable> pluginLoadingErrors = mgr.getLoadingErrors(); for (Throwable t : pluginLoadingErrors) { logger.warn("Plugin loading error: "+t.toString()); } mgr.clearErrorList(); logger.info("loading session..."); boolean sessionLoaded = false; if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { loadSessionFile(); sessionLoaded = true; } logger.info("loading networks..."); loadNetworks(); logger.info("loading attributes..."); loadAttributes(); logger.info("loading expression files..."); loadExpressionFiles(); if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { if(sessionLoaded == false) { logger.info("Initializing VizMapper..."); initVizmapper(); } } } finally { // Always restore the cursor and hide the splash, even there is // exception if ((initParams.getMode() == CyInitParams.GUI) || (initParams.getMode() == CyInitParams.EMBEDDED_WINDOW)) { WindowUtilities.hideSplash(); Cytoscape.getDesktop().setCursor(Cursor.getDefaultCursor()); // to clean up anything that the plugins have messed up Cytoscape.getDesktop().repaint(); } } long endtime = System.currentTimeMillis() - begintime; logger.info("Cytoscape initialized successfully in: " + endtime + " ms"); Cytoscape.firePropertyChange(Cytoscape.CYTOSCAPE_INITIALIZED, null, null); return true; }
diff --git a/ffxieq/src/com/github/kanata3249/ffxieq/android/AtmaListView.java b/ffxieq/src/com/github/kanata3249/ffxieq/android/AtmaListView.java index 3bb98c8..6253842 100644 --- a/ffxieq/src/com/github/kanata3249/ffxieq/android/AtmaListView.java +++ b/ffxieq/src/com/github/kanata3249/ffxieq/android/AtmaListView.java @@ -1,85 +1,89 @@ /* Copyright 2011 kanata3249 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.github.kanata3249.ffxieq.android; import com.github.kanata3249.ffxi.FFXIDAO; import com.github.kanata3249.ffxieq.R; import com.github.kanata3249.ffxieq.android.db.AtmaTable; import com.github.kanata3249.ffxieq.android.db.FFXIDatabase; import android.content.Context; import android.database.Cursor; import android.util.AttributeSet; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class AtmaListView extends ListView { FFXIDatabase mDao; String mOrderBy; String mFilter; long mFilterID; final String [] columns = { AtmaTable.C_Id, AtmaTable.C_Name, AtmaTable.C_Description }; final int []views = { 0, R.id.Name, R.id.Description }; public AtmaListView(Context context, AttributeSet attrs) { super(context, attrs); mOrderBy = null; mFilter = ""; mFilterID = -1; } public boolean setParam(FFXIDAO dao) { AtmaListViewAdapter adapter; Cursor cursor; mDao = (FFXIDatabase)dao; if (mFilterID != -1) { mFilter = ((FFXIEQBaseActivity)getContext()).getSettings().getFilter(mFilterID); } cursor = mDao.getAtmaCursor(columns, mOrderBy, mFilter); - adapter = new AtmaListViewAdapter(getContext(), R.layout.atmalistview, cursor, columns, views); - setAdapter(adapter); + if (getAdapter() != null) { + ((AtmaListViewAdapter)getAdapter()).changeCursor(cursor); + } else { + adapter = new AtmaListViewAdapter(getContext(), R.layout.atmalistview, cursor, columns, views); + setAdapter(adapter); + } return true; } private class AtmaListViewAdapter extends SimpleCursorAdapter { public AtmaListViewAdapter(Context context, int textViewResourceId, Cursor c, String[] from, int[] to) { super(context, textViewResourceId, c, from, to); } } public String getFilter() { return mFilter; } public void setFilter(String filter) { AtmaListViewAdapter adapter; mFilter = filter; adapter = (AtmaListViewAdapter)getAdapter(); if (adapter != null) { Cursor cursor = mDao.getAtmaCursor(columns, mOrderBy, mFilter); adapter.changeCursor(cursor); } } public void setFilterByID(long filterid) { mFilterID = filterid; } }
true
true
public boolean setParam(FFXIDAO dao) { AtmaListViewAdapter adapter; Cursor cursor; mDao = (FFXIDatabase)dao; if (mFilterID != -1) { mFilter = ((FFXIEQBaseActivity)getContext()).getSettings().getFilter(mFilterID); } cursor = mDao.getAtmaCursor(columns, mOrderBy, mFilter); adapter = new AtmaListViewAdapter(getContext(), R.layout.atmalistview, cursor, columns, views); setAdapter(adapter); return true; }
public boolean setParam(FFXIDAO dao) { AtmaListViewAdapter adapter; Cursor cursor; mDao = (FFXIDatabase)dao; if (mFilterID != -1) { mFilter = ((FFXIEQBaseActivity)getContext()).getSettings().getFilter(mFilterID); } cursor = mDao.getAtmaCursor(columns, mOrderBy, mFilter); if (getAdapter() != null) { ((AtmaListViewAdapter)getAdapter()).changeCursor(cursor); } else { adapter = new AtmaListViewAdapter(getContext(), R.layout.atmalistview, cursor, columns, views); setAdapter(adapter); } return true; }
diff --git a/basic/enricher/src/main/java/org/springframework/integration/samples/enricher/Main.java b/basic/enricher/src/main/java/org/springframework/integration/samples/enricher/Main.java index 92f67e0c..76b6ce67 100644 --- a/basic/enricher/src/main/java/org/springframework/integration/samples/enricher/Main.java +++ b/basic/enricher/src/main/java/org/springframework/integration/samples/enricher/Main.java @@ -1,142 +1,142 @@ /* * Copyright 2002-2010 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.integration.samples.enricher; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.integration.samples.enricher.service.UserService; /** * Starts the Spring Context and will initialize the Spring Integration routes. * * @author Gunnar Hillert * @version 1.0 * */ public final class Main { private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private static final String LINE_SEPARATOR = "\n=========================================================================="; private static final String EMPTY_LINE = "\n "; private Main() { } /** * Load the Spring Integration Application Context * * @param args - command line arguments */ public static void main(final String... args) { LOGGER.info(LINE_SEPARATOR + EMPTY_LINE + "\n Welcome to Spring Integration! " + EMPTY_LINE + "\n For more information please visit: " + "\n http://www.springsource.org/spring-integration " + EMPTY_LINE + LINE_SEPARATOR ); final AbstractApplicationContext context = new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/*-context.xml"); context.registerShutdownHook(); final Scanner scanner = new Scanner(System.in); final UserService service = context.getBean(UserService.class); LOGGER.info(LINE_SEPARATOR + EMPTY_LINE + "\n Please press 'q + Enter' to quit the application. " + EMPTY_LINE + LINE_SEPARATOR + EMPTY_LINE + "\n This example illustrates the usage of the Content Enricher. " + EMPTY_LINE + "\n Usage: Please enter 1 or 2 or 3 + Enter " + EMPTY_LINE + "\n 3 different message flows are triggered. For sample 1+2 a " + "\n user object containing only the username is passed in. " + "\n For sample 3 a Map with the 'username' key is passed in and enriched " + "\n with the user object using the 'user' key. " + EMPTY_LINE + "\n 1: In the Enricher, pass the full User object to the request channel. " + "\n 2: In the Enricher, pass only the username to the request channel. " + "\n 3: In the Enricher, pass only the username to the request channel. " + EMPTY_LINE + LINE_SEPARATOR); while (!scanner.hasNext("q")) { final String input = scanner.nextLine(); User user = new User("foo", null, null); if ("1".equals(input)) { final User fullUser = service.findUser(user); printUserInformation(fullUser); } else if ("2".equals(input)) { final User fullUser = service.findUserByUsername(user); printUserInformation(fullUser); } else if ("3".equals(input)) { final Map<String, Object> userData = new HashMap<String, Object>(); userData.put("username", "foo_map"); final Map<String, Object> enrichedUserData = service.findUserWithUsernameInMap(userData); final User fullUser = (User) enrichedUserData.get("user"); printUserInformation(fullUser); } else { - LOGGER.info("\n\n Please enter '1' or '2' <enter>:\n\n"); + LOGGER.info("\n\n Please enter '1', '2', or '3' <enter>:\n\n"); } } LOGGER.info("\n\nExiting application...bye."); System.exit(0); } private static void printUserInformation(User user) { if (user != null) { LOGGER.info("\n\n User found - Username: '{}', Email: '{}', Password: '{}'.\n\n", new Object[] {user.getUsername(), user.getEmail(), user.getPassword()}); } else { LOGGER.info("\n\n No User found for username: 'foo'.\n\n"); } } }
true
true
public static void main(final String... args) { LOGGER.info(LINE_SEPARATOR + EMPTY_LINE + "\n Welcome to Spring Integration! " + EMPTY_LINE + "\n For more information please visit: " + "\n http://www.springsource.org/spring-integration " + EMPTY_LINE + LINE_SEPARATOR ); final AbstractApplicationContext context = new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/*-context.xml"); context.registerShutdownHook(); final Scanner scanner = new Scanner(System.in); final UserService service = context.getBean(UserService.class); LOGGER.info(LINE_SEPARATOR + EMPTY_LINE + "\n Please press 'q + Enter' to quit the application. " + EMPTY_LINE + LINE_SEPARATOR + EMPTY_LINE + "\n This example illustrates the usage of the Content Enricher. " + EMPTY_LINE + "\n Usage: Please enter 1 or 2 or 3 + Enter " + EMPTY_LINE + "\n 3 different message flows are triggered. For sample 1+2 a " + "\n user object containing only the username is passed in. " + "\n For sample 3 a Map with the 'username' key is passed in and enriched " + "\n with the user object using the 'user' key. " + EMPTY_LINE + "\n 1: In the Enricher, pass the full User object to the request channel. " + "\n 2: In the Enricher, pass only the username to the request channel. " + "\n 3: In the Enricher, pass only the username to the request channel. " + EMPTY_LINE + LINE_SEPARATOR); while (!scanner.hasNext("q")) { final String input = scanner.nextLine(); User user = new User("foo", null, null); if ("1".equals(input)) { final User fullUser = service.findUser(user); printUserInformation(fullUser); } else if ("2".equals(input)) { final User fullUser = service.findUserByUsername(user); printUserInformation(fullUser); } else if ("3".equals(input)) { final Map<String, Object> userData = new HashMap<String, Object>(); userData.put("username", "foo_map"); final Map<String, Object> enrichedUserData = service.findUserWithUsernameInMap(userData); final User fullUser = (User) enrichedUserData.get("user"); printUserInformation(fullUser); } else { LOGGER.info("\n\n Please enter '1' or '2' <enter>:\n\n"); } } LOGGER.info("\n\nExiting application...bye."); System.exit(0); }
public static void main(final String... args) { LOGGER.info(LINE_SEPARATOR + EMPTY_LINE + "\n Welcome to Spring Integration! " + EMPTY_LINE + "\n For more information please visit: " + "\n http://www.springsource.org/spring-integration " + EMPTY_LINE + LINE_SEPARATOR ); final AbstractApplicationContext context = new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/*-context.xml"); context.registerShutdownHook(); final Scanner scanner = new Scanner(System.in); final UserService service = context.getBean(UserService.class); LOGGER.info(LINE_SEPARATOR + EMPTY_LINE + "\n Please press 'q + Enter' to quit the application. " + EMPTY_LINE + LINE_SEPARATOR + EMPTY_LINE + "\n This example illustrates the usage of the Content Enricher. " + EMPTY_LINE + "\n Usage: Please enter 1 or 2 or 3 + Enter " + EMPTY_LINE + "\n 3 different message flows are triggered. For sample 1+2 a " + "\n user object containing only the username is passed in. " + "\n For sample 3 a Map with the 'username' key is passed in and enriched " + "\n with the user object using the 'user' key. " + EMPTY_LINE + "\n 1: In the Enricher, pass the full User object to the request channel. " + "\n 2: In the Enricher, pass only the username to the request channel. " + "\n 3: In the Enricher, pass only the username to the request channel. " + EMPTY_LINE + LINE_SEPARATOR); while (!scanner.hasNext("q")) { final String input = scanner.nextLine(); User user = new User("foo", null, null); if ("1".equals(input)) { final User fullUser = service.findUser(user); printUserInformation(fullUser); } else if ("2".equals(input)) { final User fullUser = service.findUserByUsername(user); printUserInformation(fullUser); } else if ("3".equals(input)) { final Map<String, Object> userData = new HashMap<String, Object>(); userData.put("username", "foo_map"); final Map<String, Object> enrichedUserData = service.findUserWithUsernameInMap(userData); final User fullUser = (User) enrichedUserData.get("user"); printUserInformation(fullUser); } else { LOGGER.info("\n\n Please enter '1', '2', or '3' <enter>:\n\n"); } } LOGGER.info("\n\nExiting application...bye."); System.exit(0); }
diff --git a/wdb-api/src/main/java/org/wdbuilder/service/PluginFacadeRepository.java b/wdb-api/src/main/java/org/wdbuilder/service/PluginFacadeRepository.java index e18c152..67a2b49 100644 --- a/wdb-api/src/main/java/org/wdbuilder/service/PluginFacadeRepository.java +++ b/wdb-api/src/main/java/org/wdbuilder/service/PluginFacadeRepository.java @@ -1,36 +1,36 @@ package org.wdbuilder.service; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import org.wdbuilder.domain.Entity; import org.wdbuilder.plugin.IPluginFacade; public class PluginFacadeRepository<T extends Entity, S extends IPluginFacade<T>> implements IPluginFacadeRepository<T, S> { private final Map<Class<?>, S> plugins = new LinkedHashMap<Class<?>, S>(2); - PluginFacadeRepository(Collection<S> plugins) { + public PluginFacadeRepository(Collection<S> plugins) { for (S plugin : plugins) { this.plugins.put(plugin.getEntityClass(), plugin); } } @Override public Iterable<S> getPlugins() { return this.plugins.values(); } @Override public S getFacade(Class<?> klass) { return this.plugins.get(klass); } @Override public Collection<Class<?>> getEntityClasses() { return this.plugins.keySet(); } }
true
true
PluginFacadeRepository(Collection<S> plugins) { for (S plugin : plugins) { this.plugins.put(plugin.getEntityClass(), plugin); } }
public PluginFacadeRepository(Collection<S> plugins) { for (S plugin : plugins) { this.plugins.put(plugin.getEntityClass(), plugin); } }
diff --git a/Modmode/src/iggy/Modmode/Modmode.java b/Modmode/src/iggy/Modmode/Modmode.java index cdeb6c5..d34f538 100644 --- a/Modmode/src/iggy/Modmode/Modmode.java +++ b/Modmode/src/iggy/Modmode/Modmode.java @@ -1,160 +1,161 @@ package iggy.Modmode; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; //import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; //import org.bukkit.potion.PotionEffect; //import org.bukkit.potion.PotionEffectType; public class Modmode extends JavaPlugin{ Logger logger = Logger.getLogger("Minecraft"); String pluginTitle; PluginDescriptionFile pdFile; public Map<Player, Double> lightningDegree = new HashMap<Player, Double>(); public double distance = 7; ////////////////////////////////////////////////////////////////////////////// ////////////////////////////// ENABLE / DISABLE ////////////////////////////// ////////////////////////////////////////////////////////////////////////////// @Override public void onDisable() { info(" Version " + pdFile.getVersion() +" is disabled"); } @Override public void onEnable () { pdFile = this.getDescription(); String pluginName = pdFile.getName(); pluginTitle = "[\033[2;35m"+pluginName+"\033[0m]"; getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable () { public void run() { for (Entry<Player,Double> p : lightningDegree.entrySet()) { Player player = p.getKey(); info (player.getName() + " is in GODMODE at x=" + player.getLocation().getBlockX() + " z="+player.getLocation().getBlockZ()); double deg = (double)p.getValue(); if (deg >= 360) deg -= 360; //player.sendMessage("HI! DEG AT "+deg+" "+Math.sin(Math.PI*deg/180)*distance+":"+Math.cos(Math.PI*deg/180)*distance); //World world = player.getWorld(); Location location = player.getLocation(); //location.add(Math.acos(deg)*distance, 0, Math.asin(deg)*distance); location.add(Math.sin(Math.PI*deg/180)*distance, 0, Math.cos(Math.PI*deg/180)*distance); location.setY(player.getWorld().getHighestBlockYAt(location)); p.getKey().getWorld().strikeLightningEffect(location); lightningDegree.put(player, deg+20); } } }, 2L, 2L); info ("Version " + pdFile.getVersion() +" is enabled"); } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (player == null) { info("This command can only be run by a player"); return false; } info (player.getName() + " tried to run the command " + commandLabel); if (!player.isOp()) { player.sendMessage(ChatColor.RED+"This command can only be run by an Admin" + ChatColor.WHITE); + return false; } //World world = player.getWorld(); if (commandLabel.equalsIgnoreCase("GODMODE")){ if (lightningDegree.containsKey(player)){ lightningDegree.remove(player); player.sendMessage("Godmode deactivated"); info (player.getName() + "Left Godmode at x=" + player.getLocation().getBlockX() + " z="+player.getLocation().getBlockZ()); } else { info (player.getName() + "Entered Godmode at x=" + player.getLocation().getBlockX() + " z="+player.getLocation().getBlockZ()); player.sendMessage("Godmode activated"); lightningDegree.put(player, 0D); if (player.getItemInHand().getType() == Material.DIAMOND_SWORD) { info (player.getName() + " recieved the admin sword"); player.getItemInHand().addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 999); player.getItemInHand().addUnsafeEnchantment(Enchantment.DURABILITY, 999); player.getItemInHand().setType(Material.WOOD_SWORD); } } } if (commandLabel.equalsIgnoreCase("RAGE")) { info (player.getName() + " lighnign raged at x=" + player.getLocation().getBlockX() + " z="+player.getLocation().getBlockZ()); for (double deg = 0; deg < 360; deg += 10){ Location location = player.getLocation(); //location.add(Math.acos(deg)*distance, 0, Math.asin(deg)*distance); location.add(Math.sin(Math.PI*deg/180)*distance, 0, Math.cos(Math.PI*deg/180)*distance); location.setY(player.getWorld().getHighestBlockYAt(location)); player.getWorld().strikeLightningEffect(location); } } if (commandLabel.equalsIgnoreCase("OPEN")) { if (args.length != 1) { player.sendMessage("Correct usage /open <playername>"); return false; } Player target = getServer().getPlayer(args[0]); if (target == null) { player.sendMessage(args[0] + " not found online"); return false; } player.openInventory(target.getInventory()); } return false; } ////////////////////////////////////////////////////////////////////////////// /////////////////////////////// DISPLAY HELPERS ////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /********************************** LOG INFO **********************************\ | The log info function is a simple function to display info to the console | | logger. It also prepends the plugin title (with color) to the message so | | that the plugin that sent the message can easily be identified | \******************************************************************************/ public void info(String input) { this.logger.info(" " + pluginTitle + " " + input); } /********************************* LOG SEVERE *********************************\ | The log severe function is very similar to the log info function in that it | | displays information to the console, but the severe function sends a SEVERE | | message instead of an INFO. It also turns the message text red | \******************************************************************************/ public void severe (String input) { this.logger.severe(pluginTitle+" \033[31m"+input+"\033[0m"); } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (player == null) { info("This command can only be run by a player"); return false; } info (player.getName() + " tried to run the command " + commandLabel); if (!player.isOp()) { player.sendMessage(ChatColor.RED+"This command can only be run by an Admin" + ChatColor.WHITE); } //World world = player.getWorld(); if (commandLabel.equalsIgnoreCase("GODMODE")){ if (lightningDegree.containsKey(player)){ lightningDegree.remove(player); player.sendMessage("Godmode deactivated"); info (player.getName() + "Left Godmode at x=" + player.getLocation().getBlockX() + " z="+player.getLocation().getBlockZ()); } else { info (player.getName() + "Entered Godmode at x=" + player.getLocation().getBlockX() + " z="+player.getLocation().getBlockZ()); player.sendMessage("Godmode activated"); lightningDegree.put(player, 0D); if (player.getItemInHand().getType() == Material.DIAMOND_SWORD) { info (player.getName() + " recieved the admin sword"); player.getItemInHand().addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 999); player.getItemInHand().addUnsafeEnchantment(Enchantment.DURABILITY, 999); player.getItemInHand().setType(Material.WOOD_SWORD); } } } if (commandLabel.equalsIgnoreCase("RAGE")) { info (player.getName() + " lighnign raged at x=" + player.getLocation().getBlockX() + " z="+player.getLocation().getBlockZ()); for (double deg = 0; deg < 360; deg += 10){ Location location = player.getLocation(); //location.add(Math.acos(deg)*distance, 0, Math.asin(deg)*distance); location.add(Math.sin(Math.PI*deg/180)*distance, 0, Math.cos(Math.PI*deg/180)*distance); location.setY(player.getWorld().getHighestBlockYAt(location)); player.getWorld().strikeLightningEffect(location); } } if (commandLabel.equalsIgnoreCase("OPEN")) { if (args.length != 1) { player.sendMessage("Correct usage /open <playername>"); return false; } Player target = getServer().getPlayer(args[0]); if (target == null) { player.sendMessage(args[0] + " not found online"); return false; } player.openInventory(target.getInventory()); } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (player == null) { info("This command can only be run by a player"); return false; } info (player.getName() + " tried to run the command " + commandLabel); if (!player.isOp()) { player.sendMessage(ChatColor.RED+"This command can only be run by an Admin" + ChatColor.WHITE); return false; } //World world = player.getWorld(); if (commandLabel.equalsIgnoreCase("GODMODE")){ if (lightningDegree.containsKey(player)){ lightningDegree.remove(player); player.sendMessage("Godmode deactivated"); info (player.getName() + "Left Godmode at x=" + player.getLocation().getBlockX() + " z="+player.getLocation().getBlockZ()); } else { info (player.getName() + "Entered Godmode at x=" + player.getLocation().getBlockX() + " z="+player.getLocation().getBlockZ()); player.sendMessage("Godmode activated"); lightningDegree.put(player, 0D); if (player.getItemInHand().getType() == Material.DIAMOND_SWORD) { info (player.getName() + " recieved the admin sword"); player.getItemInHand().addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 999); player.getItemInHand().addUnsafeEnchantment(Enchantment.DURABILITY, 999); player.getItemInHand().setType(Material.WOOD_SWORD); } } } if (commandLabel.equalsIgnoreCase("RAGE")) { info (player.getName() + " lighnign raged at x=" + player.getLocation().getBlockX() + " z="+player.getLocation().getBlockZ()); for (double deg = 0; deg < 360; deg += 10){ Location location = player.getLocation(); //location.add(Math.acos(deg)*distance, 0, Math.asin(deg)*distance); location.add(Math.sin(Math.PI*deg/180)*distance, 0, Math.cos(Math.PI*deg/180)*distance); location.setY(player.getWorld().getHighestBlockYAt(location)); player.getWorld().strikeLightningEffect(location); } } if (commandLabel.equalsIgnoreCase("OPEN")) { if (args.length != 1) { player.sendMessage("Correct usage /open <playername>"); return false; } Player target = getServer().getPlayer(args[0]); if (target == null) { player.sendMessage(args[0] + " not found online"); return false; } player.openInventory(target.getInventory()); } return false; }
diff --git a/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/client/ui/views/historybrowserview/graph/AbstractPlotRenderer.java b/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/client/ui/views/historybrowserview/graph/AbstractPlotRenderer.java index 9451bf0b..f1b7ec90 100644 --- a/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/client/ui/views/historybrowserview/graph/AbstractPlotRenderer.java +++ b/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/client/ui/views/historybrowserview/graph/AbstractPlotRenderer.java @@ -1,273 +1,273 @@ /* * Copyright (C) 2008, Shawn O. Pearce <[email protected]> * Copyright (C) 2012, Alexander Aumann <[email protected]> * and other copyright owners as documented in the project's IP log. * This program and the accompanying materials are made available * under the terms of the Eclipse Distribution License v1.0 which * accompanies this distribution, is reproduced below, and is * available at http://www.eclipse.org/org/documents/edl-v10.php * All rights reserved. * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * - Neither the name of the Eclipse Foundation, Inc. nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.eclipse.emf.emfstore.client.ui.views.historybrowserview.graph; import org.eclipse.swt.graphics.Color; /** * Basic commit graph renderer for graphical user interfaces. * <p> * Lanes are drawn as columns left-to-right in the graph, and the commit short message is drawn to the right of the lane * lines for this cell. It is assumed that the commits are being drawn as rows of some sort of table. * <p> * Client applications can subclass this implementation to provide the necessary drawing primitives required to display * a commit graph. Most of the graph layout is handled by this class, allowing applications to implement only a handful * of primitive stubs. * <p> * This class is suitable for us within an AWT TableCellRenderer or within a SWT PaintListener registered on a Table * instance. It is meant to rubber stamp the graphics necessary for one row of a plotted commit list. * <p> * Subclasses should call {@link #paintCommit(PlotCommit, int)} after they have otherwise configured their instance to * draw one commit into the current location. * <p> * All drawing methods assume the coordinate space for the current commit's cell starts at (upper left corner is) 0,0. * If this is not true (like say in SWT) the implementation must perform the cell offset computations within the various * draw methods. * * Adapted from: org.eclipse.jgit.revplot.PlotCommitList.AbstractPlotRenderer * */ public abstract class AbstractPlotRenderer { private static final int LANE_WIDTH = 14; private static final int LINE_WIDTH = 2; private static final int LEFT_PAD = 2; /** * Paint one commit using the underlying graphics library. * * @param commit * the commit to render in this cell. Must not be null. * @param h * total height (in pixels) of this cell. */ protected void paintCommit(final IPlotCommit commit, final int h) { final int dotSize = computeDotSize(h); final PlotLane myLane = commit.getLane(); final int myLaneX = laneC(myLane); final Color myColor = laneColor(myLane, true); int maxCenter = 0; for (final PlotLane passingLane : commit.getPassingLanes()) { final int cx = laneC(passingLane); final Color c; c = laneColor(passingLane, commit.isRealCommit()); drawLine(c, cx, 0, cx, h, LINE_WIDTH); maxCenter = Math.max(maxCenter, cx); } final int nParent = commit.getParentCount(); for (int i = 0; i < nParent; i++) { final IPlotCommit p; final PlotLane pLane; final Color pColor; final int cx; p = commit.getParent(i); pLane = p.getLane(); if (pLane == null) { continue; } pColor = laneColor(pLane, true); cx = laneC(pLane); if (commit.isRealCommit()) { if (Math.abs(myLaneX - cx) > LANE_WIDTH) { if (myLaneX < cx) { final int ix = cx - LANE_WIDTH / 2; drawLine(pColor, myLaneX, h / 2, ix, h / 2, LINE_WIDTH); drawLine(pColor, ix, h / 2, cx, h, LINE_WIDTH); } else { final int ix = cx + LANE_WIDTH / 2; drawLine(pColor, myLaneX, h / 2, ix, h / 2, LINE_WIDTH); drawLine(pColor, ix, h / 2, cx, h, LINE_WIDTH); } } else { drawLine(pColor, myLaneX, h / 2, cx, h, LINE_WIDTH); } } else { // for children only draw the parent lanes in gray drawLine(laneColor(pLane, false), cx, 0, cx, h, LINE_WIDTH); } maxCenter = Math.max(maxCenter, cx); } final int dotX = myLaneX - dotSize / 2 - 1; final int dotY = (h - dotSize) / 2; - if (commit.isRealCommit() && commit.getChildCount() > 0) { + if (commit.isRealCommit() && !commit.isLocalHistoryOnly() && commit.getChildCount() > 0) { drawLine(myColor, myLaneX, 0, myLaneX, dotY, LINE_WIDTH); } // if (commit.has(RevFlag.UNINTERESTING)) // drawBoundaryDot(dotX, dotY, dotSize, dotSize); // else int textx; if (commit.isRealCommit() && !commit.isLocalHistoryOnly()) { drawCommitDot(dotX, dotY, dotSize, dotSize); textx = Math.max(maxCenter + LANE_WIDTH / 2, dotX + dotSize) + 8; } else { textx = -dotSize / 2; } // int n = commit.refs.length; // for (int i = 0; i < n; ++i) { // textx += drawLabel(textx + dotSize, h / 2, commit.refs[i]); // } if (commit.isRealCommit()) { textx += drawLabel(textx + dotSize, h / 2, commit); // final String msg = commit.getShortMessage(); // drawText(msg, textx + dotSize + n * 2, h / 2); } } /** * Draw a decoration for the IPlotCommit at x,y. * * @param x * left * @param y * top * @param commit * A plot commit * @return width of label in pixels */ protected abstract int drawLabel(int x, int y, IPlotCommit commit); private int computeDotSize(final int h) { int d = (int) (Math.min(h, LANE_WIDTH) * 0.50f); d += (d & 1); return d; } /** * Obtain the color reference used to paint this lane. * <p> * Colors returned by this method will be passed to the other drawing primitives, so the color returned should be * application specific. * <p> * If a null lane is supplied the return value must still be acceptable to a drawing method. Usually this means the * implementation should return a default color. * * @param myLane * the current lane. May be null. * @param fullSaturation if true a fully saturated color is returned, otherwise a lighter, washed-out one * @return graphics specific color reference. Must be a valid color. */ protected abstract Color laneColor(PlotLane myLane, boolean fullSaturation); /** * Draw a single line within this cell. * * @param color * the color to use while drawing the line. * @param x1 * starting X coordinate, 0 based. * @param y1 * starting Y coordinate, 0 based. * @param x2 * ending X coordinate, 0 based. * @param y2 * ending Y coordinate, 0 based. * @param width * number of pixels wide for the line. Always at least 1. */ protected abstract void drawLine(Color color, int x1, int y1, int x2, int y2, int width); /** * Draw a single commit dot. * <p> * Usually the commit dot is a filled oval in blue, then a drawn oval in black, using the same coordinates for both * operations. * * @param x * upper left of the oval's bounding box. * @param y * upper left of the oval's bounding box. * @param w * width of the oval's bounding box. * @param h * height of the oval's bounding box. */ protected abstract void drawCommitDot(int x, int y, int w, int h); /** * Draw a single boundary commit (aka uninteresting commit) dot. * <p> * Usually a boundary commit dot is a light gray oval with a white center. * * @param x * upper left of the oval's bounding box. * @param y * upper left of the oval's bounding box. * @param w * width of the oval's bounding box. * @param h * height of the oval's bounding box. */ protected abstract void drawBoundaryDot(int x, int y, int w, int h); /** * Draw a single line of text. * <p> * The font and colors used to render the text are left up to the implementation. * * @param msg * the text to draw. Does not contain LFs. * @param x * first pixel from the left that the text can be drawn at. * Character data must not appear before this position. * @param y * pixel coordinate of the centerline of the text. * Implementations must adjust this coordinate to account for the * way their implementation handles font rendering. */ protected abstract void drawText(String msg, int x, int y); private int laneX(final PlotLane myLane) { final int p = myLane != null ? myLane.getPosition() : 0; return LEFT_PAD + LANE_WIDTH * p; } private int laneC(final PlotLane myLane) { return laneX(myLane) + LANE_WIDTH / 2; } }
true
true
protected void paintCommit(final IPlotCommit commit, final int h) { final int dotSize = computeDotSize(h); final PlotLane myLane = commit.getLane(); final int myLaneX = laneC(myLane); final Color myColor = laneColor(myLane, true); int maxCenter = 0; for (final PlotLane passingLane : commit.getPassingLanes()) { final int cx = laneC(passingLane); final Color c; c = laneColor(passingLane, commit.isRealCommit()); drawLine(c, cx, 0, cx, h, LINE_WIDTH); maxCenter = Math.max(maxCenter, cx); } final int nParent = commit.getParentCount(); for (int i = 0; i < nParent; i++) { final IPlotCommit p; final PlotLane pLane; final Color pColor; final int cx; p = commit.getParent(i); pLane = p.getLane(); if (pLane == null) { continue; } pColor = laneColor(pLane, true); cx = laneC(pLane); if (commit.isRealCommit()) { if (Math.abs(myLaneX - cx) > LANE_WIDTH) { if (myLaneX < cx) { final int ix = cx - LANE_WIDTH / 2; drawLine(pColor, myLaneX, h / 2, ix, h / 2, LINE_WIDTH); drawLine(pColor, ix, h / 2, cx, h, LINE_WIDTH); } else { final int ix = cx + LANE_WIDTH / 2; drawLine(pColor, myLaneX, h / 2, ix, h / 2, LINE_WIDTH); drawLine(pColor, ix, h / 2, cx, h, LINE_WIDTH); } } else { drawLine(pColor, myLaneX, h / 2, cx, h, LINE_WIDTH); } } else { // for children only draw the parent lanes in gray drawLine(laneColor(pLane, false), cx, 0, cx, h, LINE_WIDTH); } maxCenter = Math.max(maxCenter, cx); } final int dotX = myLaneX - dotSize / 2 - 1; final int dotY = (h - dotSize) / 2; if (commit.isRealCommit() && commit.getChildCount() > 0) { drawLine(myColor, myLaneX, 0, myLaneX, dotY, LINE_WIDTH); } // if (commit.has(RevFlag.UNINTERESTING)) // drawBoundaryDot(dotX, dotY, dotSize, dotSize); // else int textx; if (commit.isRealCommit() && !commit.isLocalHistoryOnly()) { drawCommitDot(dotX, dotY, dotSize, dotSize); textx = Math.max(maxCenter + LANE_WIDTH / 2, dotX + dotSize) + 8; } else { textx = -dotSize / 2; } // int n = commit.refs.length; // for (int i = 0; i < n; ++i) { // textx += drawLabel(textx + dotSize, h / 2, commit.refs[i]); // } if (commit.isRealCommit()) { textx += drawLabel(textx + dotSize, h / 2, commit); // final String msg = commit.getShortMessage(); // drawText(msg, textx + dotSize + n * 2, h / 2); } }
protected void paintCommit(final IPlotCommit commit, final int h) { final int dotSize = computeDotSize(h); final PlotLane myLane = commit.getLane(); final int myLaneX = laneC(myLane); final Color myColor = laneColor(myLane, true); int maxCenter = 0; for (final PlotLane passingLane : commit.getPassingLanes()) { final int cx = laneC(passingLane); final Color c; c = laneColor(passingLane, commit.isRealCommit()); drawLine(c, cx, 0, cx, h, LINE_WIDTH); maxCenter = Math.max(maxCenter, cx); } final int nParent = commit.getParentCount(); for (int i = 0; i < nParent; i++) { final IPlotCommit p; final PlotLane pLane; final Color pColor; final int cx; p = commit.getParent(i); pLane = p.getLane(); if (pLane == null) { continue; } pColor = laneColor(pLane, true); cx = laneC(pLane); if (commit.isRealCommit()) { if (Math.abs(myLaneX - cx) > LANE_WIDTH) { if (myLaneX < cx) { final int ix = cx - LANE_WIDTH / 2; drawLine(pColor, myLaneX, h / 2, ix, h / 2, LINE_WIDTH); drawLine(pColor, ix, h / 2, cx, h, LINE_WIDTH); } else { final int ix = cx + LANE_WIDTH / 2; drawLine(pColor, myLaneX, h / 2, ix, h / 2, LINE_WIDTH); drawLine(pColor, ix, h / 2, cx, h, LINE_WIDTH); } } else { drawLine(pColor, myLaneX, h / 2, cx, h, LINE_WIDTH); } } else { // for children only draw the parent lanes in gray drawLine(laneColor(pLane, false), cx, 0, cx, h, LINE_WIDTH); } maxCenter = Math.max(maxCenter, cx); } final int dotX = myLaneX - dotSize / 2 - 1; final int dotY = (h - dotSize) / 2; if (commit.isRealCommit() && !commit.isLocalHistoryOnly() && commit.getChildCount() > 0) { drawLine(myColor, myLaneX, 0, myLaneX, dotY, LINE_WIDTH); } // if (commit.has(RevFlag.UNINTERESTING)) // drawBoundaryDot(dotX, dotY, dotSize, dotSize); // else int textx; if (commit.isRealCommit() && !commit.isLocalHistoryOnly()) { drawCommitDot(dotX, dotY, dotSize, dotSize); textx = Math.max(maxCenter + LANE_WIDTH / 2, dotX + dotSize) + 8; } else { textx = -dotSize / 2; } // int n = commit.refs.length; // for (int i = 0; i < n; ++i) { // textx += drawLabel(textx + dotSize, h / 2, commit.refs[i]); // } if (commit.isRealCommit()) { textx += drawLabel(textx + dotSize, h / 2, commit); // final String msg = commit.getShortMessage(); // drawText(msg, textx + dotSize + n * 2, h / 2); } }
diff --git a/engine/src/main/java/org/archive/crawler/frontier/BucketQueueAssignmentPolicy.java b/engine/src/main/java/org/archive/crawler/frontier/BucketQueueAssignmentPolicy.java index b89b4fe2..79fbe7ad 100644 --- a/engine/src/main/java/org/archive/crawler/frontier/BucketQueueAssignmentPolicy.java +++ b/engine/src/main/java/org/archive/crawler/frontier/BucketQueueAssignmentPolicy.java @@ -1,74 +1,73 @@ /* BucketQueueAssignmentPolicy * * $Header$ * * Created on May 06, 2005 * * Copyright (C) 2005 Christian Kohlschuetter * * This file is part of the Heritrix web crawler (crawler.archive.org). * * Heritrix is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * any later version. * * Heritrix 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Heritrix; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package org.archive.crawler.frontier; import org.archive.modules.CrawlURI; import org.archive.modules.net.CrawlHost; import org.archive.modules.net.ServerCache; import org.springframework.beans.factory.annotation.Autowired; /** * Uses the target IPs as basis for queue-assignment, * distributing them over a fixed number of sub-queues. * * @author Christian Kohlschuetter */ public class BucketQueueAssignmentPolicy extends QueueAssignmentPolicy { private static final long serialVersionUID = 3L; private static final int DEFAULT_NOIP_BITMASK = 1023; private static final int DEFAULT_QUEUES_HOSTS_MODULO = 1021; protected ServerCache serverCache; public ServerCache getServerCache() { return this.serverCache; } @Autowired public void setServerCache(ServerCache serverCache) { this.serverCache = serverCache; } public String getClassKey(final CrawlURI curi) { CrawlHost host; host = serverCache.getHostFor(curi.getUURI()); if(host == null) { return "NO-HOST"; } else if(host.getIP() == null) { - return "NO-IP-".concat(Integer.toString(Math.abs(host.getHostName() - .hashCode()) - & DEFAULT_NOIP_BITMASK)); + return "NO-IP-".concat(Long.toString(Math.abs((long) host + .getHostName().hashCode()) & DEFAULT_NOIP_BITMASK)); } else { - return Integer.toString(Math.abs(host.getIP().hashCode()) - % DEFAULT_QUEUES_HOSTS_MODULO); + return Long.toString(Math.abs((long) host.getIP().hashCode()) + % DEFAULT_QUEUES_HOSTS_MODULO); } } public int maximumNumberOfKeys() { return DEFAULT_NOIP_BITMASK + DEFAULT_QUEUES_HOSTS_MODULO + 2; } }
false
true
public String getClassKey(final CrawlURI curi) { CrawlHost host; host = serverCache.getHostFor(curi.getUURI()); if(host == null) { return "NO-HOST"; } else if(host.getIP() == null) { return "NO-IP-".concat(Integer.toString(Math.abs(host.getHostName() .hashCode()) & DEFAULT_NOIP_BITMASK)); } else { return Integer.toString(Math.abs(host.getIP().hashCode()) % DEFAULT_QUEUES_HOSTS_MODULO); } }
public String getClassKey(final CrawlURI curi) { CrawlHost host; host = serverCache.getHostFor(curi.getUURI()); if(host == null) { return "NO-HOST"; } else if(host.getIP() == null) { return "NO-IP-".concat(Long.toString(Math.abs((long) host .getHostName().hashCode()) & DEFAULT_NOIP_BITMASK)); } else { return Long.toString(Math.abs((long) host.getIP().hashCode()) % DEFAULT_QUEUES_HOSTS_MODULO); } }
diff --git a/src/org/bh/platform/PlatformActionListener.java b/src/org/bh/platform/PlatformActionListener.java index 03b9c0e6..69f803e9 100644 --- a/src/org/bh/platform/PlatformActionListener.java +++ b/src/org/bh/platform/PlatformActionListener.java @@ -1,277 +1,278 @@ package org.bh.platform; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.WindowConstants; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import org.bh.data.DTOPeriod; import org.bh.data.DTOProject; import org.bh.data.DTOScenario; import org.bh.data.types.StringValue; import org.bh.gui.swing.BHMainFrame; import org.bh.gui.swing.BHTreeNode; import org.bh.gui.swing.IBHAction; import org.bh.platform.PlatformController.BHTreeModel; /** * The PlatformActionListener handles all actions that are fired by a button * etc. of the platform. */ class PlatformActionListener implements ActionListener { BHMainFrame bhmf; ProjectRepositoryManager projectRepoManager; public PlatformActionListener(BHMainFrame bhmf, ProjectRepositoryManager projectRepoManager){ this.bhmf = bhmf; this.projectRepoManager = projectRepoManager; } @Override public void actionPerformed(ActionEvent aEvent) { // get actionKey of fired action PlatformKey actionKey = ((IBHAction) aEvent.getSource()).getPlatformKey(); //do right action... switch (actionKey) { case FILENEW: break; // TODO Loeckelt.Michael case FILEOPEN: System.out.println("FILEOPEN gefeuert"); int returnVal = bhmf.getChooser().showOpenDialog(bhmf); if (returnVal == JFileChooser.APPROVE_OPTION) { System.out.println("You chose to open this file: " + bhmf.getChooser().getSelectedFile().getName()); } break; // TODO Loeckelt.Michael case FILESAVE: System.out.println("bla"); break; // TODO Loeckelt.Michael case FILESAVEAS: break; case FILEQUIT: //TODO Prüfen und ggf. implementieren! break; case PROJECTCREATE: //TODO Prüfen und ggf. implementieren! break; case PROJECTRENAME: //TODO Prüfen und ggf. implementieren! break; case PROJECTDUPLICATE: //TODO Prüfen und ggf. implementieren! break; // TODO Katzor.Marcus case PROJECTIMPORT: break; // TODO Katzor.Marcus case PROJECTEXPORT: break; case PROJECTREMOVE: //TODO Prüfen und ggf. implementieren! break; case SCENARIOCREATE: //TODO Prüfen und ggf. implementieren! break; case SCENARIORENAME: //TODO Prüfen und ggf. implementieren! break; case SCENARIODUPLICATE: //TODO Prüfen und ggf. implementieren! break; case SCENARIOMOVE: //TODO Prüfen und ggf. implementieren! break; case SCENARIOREMOVE: //TODO Prüfen und ggf. implementieren! break; case BILANZGUVSHOW: //TODO Prüfen und ggf. implementieren! break; case BILANZGUVCREATE: //TODO Prüfen und ggf. implementieren! break; case BILANZGUVIMPORT: //TODO Prüfen und ggf. implementieren! break; case BILANZGUVREMOVE: //TODO Prüfen und ggf. implementieren! break; case OPTIONSCHANGE: //TODO Prüfen und ggf. implementieren! break; case HELPUSERHELP: System.out.println("HELPUSERHELP gefeuert"); JFrame frame = new JFrame(); frame.setTitle("Business Horizon Help"); frame.setSize(610,600); frame.getContentPane().add(new BHHelpSystem()); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + frame.setResizable(false); frame.setVisible(true); break; case HELPMATHHELP: //TODO Prüfen und ggf. implementieren! break; case HELPINFO: //TODO Prüfen und ggf. implementieren! break; case TOOLBAROPEN: //TODO Prüfen und ggf. implementieren! break; case TOOLBARSAVE: //TODO Prüfen und ggf. implementieren! break; case TOOLBARADDPRO: //Create new project DTOProject newProject = new DTOProject(); //TODO hardgecodeder String raus! AS newProject.put(DTOProject.Key.NAME, new StringValue("neues Projekt")); //add it to DTO-Repository projectRepoManager.addProject(newProject); //and create a Node for tree on gui BHTreeNode newProjectNode = new BHTreeNode(newProject); ((DefaultTreeModel)bhmf.getBHTree().getModel()).insertNodeInto( newProjectNode, (DefaultMutableTreeNode)bhmf.getBHTree().getModel().getRoot(), ((DefaultMutableTreeNode)bhmf.getBHTree().getModel().getRoot()).getChildCount() ); //last steps: unfold tree to new element, set focus and start editing bhmf.getBHTree().scrollPathToVisible(new TreePath(newProjectNode.getPath())); bhmf.getBHTree().startEditingAtPath(new TreePath(newProjectNode.getPath())); break; case TOOLBARADDS: //If a path is selected... if(bhmf.getBHTree().getSelectionPath() != null){ //...create new scenario DTOScenario newScenario = new DTOScenario(); //TODO hardgecodeder String raus! AS newScenario.put(DTOScenario.Key.NAME, new StringValue("neues Scenario")); //...add it to DTO-Repository ((DTOProject)((BHTreeNode)bhmf.getBHTree().getSelectionPath().getPathComponent(1)).getUserObject()).addChild(newScenario); //...and insert it into GUI-Tree BHTreeNode newScenarioNode = new BHTreeNode(newScenario); ((BHTreeModel)bhmf.getBHTree().getModel()).insertNodeInto( newScenarioNode, (BHTreeNode)(bhmf.getBHTree().getSelectionPath().getPathComponent(1)), ((BHTreeNode) bhmf.getBHTree().getSelectionPath().getPathComponent(1)).getChildCount() ); //last steps: unfold tree to new element, set focus and start editing bhmf.getBHTree().scrollPathToVisible(new TreePath(newScenarioNode.getPath())); bhmf.getBHTree().startEditingAtPath(new TreePath(newScenarioNode.getPath())); } break; case TOOLBARADDPER: //If a scenario or a period is selected... if(bhmf.getBHTree().getSelectionPath()!=null && bhmf.getBHTree().getSelectionPath().getPathCount()>2){ //...create new period DTOPeriod newPeriod = new DTOPeriod(); //TODO hardgecodeder String raus! AS newPeriod.put(DTOPeriod.Key.NAME, new StringValue("neue Periode")); //...add it to DTO-Repository ((DTOScenario)((BHTreeNode)bhmf.getBHTree().getSelectionPath().getPathComponent(2)).getUserObject()).addChild(newPeriod); //...and insert it into GUI-Tree BHTreeNode newPeriodNode = new BHTreeNode(newPeriod); ((BHTreeModel)bhmf.getBHTree().getModel()).insertNodeInto( newPeriodNode, (BHTreeNode)(bhmf.getBHTree().getSelectionPath().getPathComponent(2)), ((BHTreeNode) bhmf.getBHTree().getSelectionPath().getPathComponent(2)).getChildCount() ); //last steps: unfold tree to new element, set focus and start editing bhmf.getBHTree().scrollPathToVisible(new TreePath(newPeriodNode.getPath())); bhmf.getBHTree().startEditingAtPath(new TreePath(newPeriodNode.getPath())); } break; case TOOLBARREMOVE: TreePath currentSelection = bhmf.getBHTree().getSelectionPath(); //is a node selected? if (currentSelection != null) { //remove node from GUI... BHTreeNode currentNode = (BHTreeNode)bhmf.getBHTree().getSelectionPath().getLastPathComponent(); ((BHTreeModel) bhmf.getBHTree().getModel()).removeNodeFromParent(currentNode); //..and from data model if(currentNode.getUserObject() instanceof DTOProject){ projectRepoManager.removeProject((DTOProject) currentNode.getUserObject()); }else if(currentNode.getUserObject() instanceof DTOScenario){ ((DTOProject)((BHTreeNode)currentNode.getParent()).getUserObject()).removeChild((DTOScenario) currentNode.getUserObject()); }else if(currentNode.getUserObject() instanceof DTOPeriod){ ((DTOScenario)((BHTreeNode)currentNode.getParent()).getUserObject()).removeChild((DTOPeriod) currentNode.getUserObject()); } } break; default: System.out.println("Was anderes, und zwar: "+actionKey.getActionKey()); break; } } }
true
true
public void actionPerformed(ActionEvent aEvent) { // get actionKey of fired action PlatformKey actionKey = ((IBHAction) aEvent.getSource()).getPlatformKey(); //do right action... switch (actionKey) { case FILENEW: break; // TODO Loeckelt.Michael case FILEOPEN: System.out.println("FILEOPEN gefeuert"); int returnVal = bhmf.getChooser().showOpenDialog(bhmf); if (returnVal == JFileChooser.APPROVE_OPTION) { System.out.println("You chose to open this file: " + bhmf.getChooser().getSelectedFile().getName()); } break; // TODO Loeckelt.Michael case FILESAVE: System.out.println("bla"); break; // TODO Loeckelt.Michael case FILESAVEAS: break; case FILEQUIT: //TODO Prüfen und ggf. implementieren! break; case PROJECTCREATE: //TODO Prüfen und ggf. implementieren! break; case PROJECTRENAME: //TODO Prüfen und ggf. implementieren! break; case PROJECTDUPLICATE: //TODO Prüfen und ggf. implementieren! break; // TODO Katzor.Marcus case PROJECTIMPORT: break; // TODO Katzor.Marcus case PROJECTEXPORT: break; case PROJECTREMOVE: //TODO Prüfen und ggf. implementieren! break; case SCENARIOCREATE: //TODO Prüfen und ggf. implementieren! break; case SCENARIORENAME: //TODO Prüfen und ggf. implementieren! break; case SCENARIODUPLICATE: //TODO Prüfen und ggf. implementieren! break; case SCENARIOMOVE: //TODO Prüfen und ggf. implementieren! break; case SCENARIOREMOVE: //TODO Prüfen und ggf. implementieren! break; case BILANZGUVSHOW: //TODO Prüfen und ggf. implementieren! break; case BILANZGUVCREATE: //TODO Prüfen und ggf. implementieren! break; case BILANZGUVIMPORT: //TODO Prüfen und ggf. implementieren! break; case BILANZGUVREMOVE: //TODO Prüfen und ggf. implementieren! break; case OPTIONSCHANGE: //TODO Prüfen und ggf. implementieren! break; case HELPUSERHELP: System.out.println("HELPUSERHELP gefeuert"); JFrame frame = new JFrame(); frame.setTitle("Business Horizon Help"); frame.setSize(610,600); frame.getContentPane().add(new BHHelpSystem()); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.setVisible(true); break; case HELPMATHHELP: //TODO Prüfen und ggf. implementieren! break; case HELPINFO: //TODO Prüfen und ggf. implementieren! break; case TOOLBAROPEN: //TODO Prüfen und ggf. implementieren! break; case TOOLBARSAVE: //TODO Prüfen und ggf. implementieren! break; case TOOLBARADDPRO: //Create new project DTOProject newProject = new DTOProject(); //TODO hardgecodeder String raus! AS newProject.put(DTOProject.Key.NAME, new StringValue("neues Projekt")); //add it to DTO-Repository projectRepoManager.addProject(newProject); //and create a Node for tree on gui BHTreeNode newProjectNode = new BHTreeNode(newProject); ((DefaultTreeModel)bhmf.getBHTree().getModel()).insertNodeInto( newProjectNode, (DefaultMutableTreeNode)bhmf.getBHTree().getModel().getRoot(), ((DefaultMutableTreeNode)bhmf.getBHTree().getModel().getRoot()).getChildCount() ); //last steps: unfold tree to new element, set focus and start editing bhmf.getBHTree().scrollPathToVisible(new TreePath(newProjectNode.getPath())); bhmf.getBHTree().startEditingAtPath(new TreePath(newProjectNode.getPath())); break; case TOOLBARADDS: //If a path is selected... if(bhmf.getBHTree().getSelectionPath() != null){ //...create new scenario DTOScenario newScenario = new DTOScenario(); //TODO hardgecodeder String raus! AS newScenario.put(DTOScenario.Key.NAME, new StringValue("neues Scenario")); //...add it to DTO-Repository ((DTOProject)((BHTreeNode)bhmf.getBHTree().getSelectionPath().getPathComponent(1)).getUserObject()).addChild(newScenario); //...and insert it into GUI-Tree BHTreeNode newScenarioNode = new BHTreeNode(newScenario); ((BHTreeModel)bhmf.getBHTree().getModel()).insertNodeInto( newScenarioNode, (BHTreeNode)(bhmf.getBHTree().getSelectionPath().getPathComponent(1)), ((BHTreeNode) bhmf.getBHTree().getSelectionPath().getPathComponent(1)).getChildCount() ); //last steps: unfold tree to new element, set focus and start editing bhmf.getBHTree().scrollPathToVisible(new TreePath(newScenarioNode.getPath())); bhmf.getBHTree().startEditingAtPath(new TreePath(newScenarioNode.getPath())); } break; case TOOLBARADDPER: //If a scenario or a period is selected... if(bhmf.getBHTree().getSelectionPath()!=null && bhmf.getBHTree().getSelectionPath().getPathCount()>2){ //...create new period DTOPeriod newPeriod = new DTOPeriod(); //TODO hardgecodeder String raus! AS newPeriod.put(DTOPeriod.Key.NAME, new StringValue("neue Periode")); //...add it to DTO-Repository ((DTOScenario)((BHTreeNode)bhmf.getBHTree().getSelectionPath().getPathComponent(2)).getUserObject()).addChild(newPeriod); //...and insert it into GUI-Tree BHTreeNode newPeriodNode = new BHTreeNode(newPeriod); ((BHTreeModel)bhmf.getBHTree().getModel()).insertNodeInto( newPeriodNode, (BHTreeNode)(bhmf.getBHTree().getSelectionPath().getPathComponent(2)), ((BHTreeNode) bhmf.getBHTree().getSelectionPath().getPathComponent(2)).getChildCount() ); //last steps: unfold tree to new element, set focus and start editing bhmf.getBHTree().scrollPathToVisible(new TreePath(newPeriodNode.getPath())); bhmf.getBHTree().startEditingAtPath(new TreePath(newPeriodNode.getPath())); } break; case TOOLBARREMOVE: TreePath currentSelection = bhmf.getBHTree().getSelectionPath(); //is a node selected? if (currentSelection != null) { //remove node from GUI... BHTreeNode currentNode = (BHTreeNode)bhmf.getBHTree().getSelectionPath().getLastPathComponent(); ((BHTreeModel) bhmf.getBHTree().getModel()).removeNodeFromParent(currentNode); //..and from data model if(currentNode.getUserObject() instanceof DTOProject){ projectRepoManager.removeProject((DTOProject) currentNode.getUserObject()); }else if(currentNode.getUserObject() instanceof DTOScenario){ ((DTOProject)((BHTreeNode)currentNode.getParent()).getUserObject()).removeChild((DTOScenario) currentNode.getUserObject()); }else if(currentNode.getUserObject() instanceof DTOPeriod){ ((DTOScenario)((BHTreeNode)currentNode.getParent()).getUserObject()).removeChild((DTOPeriod) currentNode.getUserObject()); } } break; default: System.out.println("Was anderes, und zwar: "+actionKey.getActionKey()); break; } }
public void actionPerformed(ActionEvent aEvent) { // get actionKey of fired action PlatformKey actionKey = ((IBHAction) aEvent.getSource()).getPlatformKey(); //do right action... switch (actionKey) { case FILENEW: break; // TODO Loeckelt.Michael case FILEOPEN: System.out.println("FILEOPEN gefeuert"); int returnVal = bhmf.getChooser().showOpenDialog(bhmf); if (returnVal == JFileChooser.APPROVE_OPTION) { System.out.println("You chose to open this file: " + bhmf.getChooser().getSelectedFile().getName()); } break; // TODO Loeckelt.Michael case FILESAVE: System.out.println("bla"); break; // TODO Loeckelt.Michael case FILESAVEAS: break; case FILEQUIT: //TODO Prüfen und ggf. implementieren! break; case PROJECTCREATE: //TODO Prüfen und ggf. implementieren! break; case PROJECTRENAME: //TODO Prüfen und ggf. implementieren! break; case PROJECTDUPLICATE: //TODO Prüfen und ggf. implementieren! break; // TODO Katzor.Marcus case PROJECTIMPORT: break; // TODO Katzor.Marcus case PROJECTEXPORT: break; case PROJECTREMOVE: //TODO Prüfen und ggf. implementieren! break; case SCENARIOCREATE: //TODO Prüfen und ggf. implementieren! break; case SCENARIORENAME: //TODO Prüfen und ggf. implementieren! break; case SCENARIODUPLICATE: //TODO Prüfen und ggf. implementieren! break; case SCENARIOMOVE: //TODO Prüfen und ggf. implementieren! break; case SCENARIOREMOVE: //TODO Prüfen und ggf. implementieren! break; case BILANZGUVSHOW: //TODO Prüfen und ggf. implementieren! break; case BILANZGUVCREATE: //TODO Prüfen und ggf. implementieren! break; case BILANZGUVIMPORT: //TODO Prüfen und ggf. implementieren! break; case BILANZGUVREMOVE: //TODO Prüfen und ggf. implementieren! break; case OPTIONSCHANGE: //TODO Prüfen und ggf. implementieren! break; case HELPUSERHELP: System.out.println("HELPUSERHELP gefeuert"); JFrame frame = new JFrame(); frame.setTitle("Business Horizon Help"); frame.setSize(610,600); frame.getContentPane().add(new BHHelpSystem()); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); break; case HELPMATHHELP: //TODO Prüfen und ggf. implementieren! break; case HELPINFO: //TODO Prüfen und ggf. implementieren! break; case TOOLBAROPEN: //TODO Prüfen und ggf. implementieren! break; case TOOLBARSAVE: //TODO Prüfen und ggf. implementieren! break; case TOOLBARADDPRO: //Create new project DTOProject newProject = new DTOProject(); //TODO hardgecodeder String raus! AS newProject.put(DTOProject.Key.NAME, new StringValue("neues Projekt")); //add it to DTO-Repository projectRepoManager.addProject(newProject); //and create a Node for tree on gui BHTreeNode newProjectNode = new BHTreeNode(newProject); ((DefaultTreeModel)bhmf.getBHTree().getModel()).insertNodeInto( newProjectNode, (DefaultMutableTreeNode)bhmf.getBHTree().getModel().getRoot(), ((DefaultMutableTreeNode)bhmf.getBHTree().getModel().getRoot()).getChildCount() ); //last steps: unfold tree to new element, set focus and start editing bhmf.getBHTree().scrollPathToVisible(new TreePath(newProjectNode.getPath())); bhmf.getBHTree().startEditingAtPath(new TreePath(newProjectNode.getPath())); break; case TOOLBARADDS: //If a path is selected... if(bhmf.getBHTree().getSelectionPath() != null){ //...create new scenario DTOScenario newScenario = new DTOScenario(); //TODO hardgecodeder String raus! AS newScenario.put(DTOScenario.Key.NAME, new StringValue("neues Scenario")); //...add it to DTO-Repository ((DTOProject)((BHTreeNode)bhmf.getBHTree().getSelectionPath().getPathComponent(1)).getUserObject()).addChild(newScenario); //...and insert it into GUI-Tree BHTreeNode newScenarioNode = new BHTreeNode(newScenario); ((BHTreeModel)bhmf.getBHTree().getModel()).insertNodeInto( newScenarioNode, (BHTreeNode)(bhmf.getBHTree().getSelectionPath().getPathComponent(1)), ((BHTreeNode) bhmf.getBHTree().getSelectionPath().getPathComponent(1)).getChildCount() ); //last steps: unfold tree to new element, set focus and start editing bhmf.getBHTree().scrollPathToVisible(new TreePath(newScenarioNode.getPath())); bhmf.getBHTree().startEditingAtPath(new TreePath(newScenarioNode.getPath())); } break; case TOOLBARADDPER: //If a scenario or a period is selected... if(bhmf.getBHTree().getSelectionPath()!=null && bhmf.getBHTree().getSelectionPath().getPathCount()>2){ //...create new period DTOPeriod newPeriod = new DTOPeriod(); //TODO hardgecodeder String raus! AS newPeriod.put(DTOPeriod.Key.NAME, new StringValue("neue Periode")); //...add it to DTO-Repository ((DTOScenario)((BHTreeNode)bhmf.getBHTree().getSelectionPath().getPathComponent(2)).getUserObject()).addChild(newPeriod); //...and insert it into GUI-Tree BHTreeNode newPeriodNode = new BHTreeNode(newPeriod); ((BHTreeModel)bhmf.getBHTree().getModel()).insertNodeInto( newPeriodNode, (BHTreeNode)(bhmf.getBHTree().getSelectionPath().getPathComponent(2)), ((BHTreeNode) bhmf.getBHTree().getSelectionPath().getPathComponent(2)).getChildCount() ); //last steps: unfold tree to new element, set focus and start editing bhmf.getBHTree().scrollPathToVisible(new TreePath(newPeriodNode.getPath())); bhmf.getBHTree().startEditingAtPath(new TreePath(newPeriodNode.getPath())); } break; case TOOLBARREMOVE: TreePath currentSelection = bhmf.getBHTree().getSelectionPath(); //is a node selected? if (currentSelection != null) { //remove node from GUI... BHTreeNode currentNode = (BHTreeNode)bhmf.getBHTree().getSelectionPath().getLastPathComponent(); ((BHTreeModel) bhmf.getBHTree().getModel()).removeNodeFromParent(currentNode); //..and from data model if(currentNode.getUserObject() instanceof DTOProject){ projectRepoManager.removeProject((DTOProject) currentNode.getUserObject()); }else if(currentNode.getUserObject() instanceof DTOScenario){ ((DTOProject)((BHTreeNode)currentNode.getParent()).getUserObject()).removeChild((DTOScenario) currentNode.getUserObject()); }else if(currentNode.getUserObject() instanceof DTOPeriod){ ((DTOScenario)((BHTreeNode)currentNode.getParent()).getUserObject()).removeChild((DTOPeriod) currentNode.getUserObject()); } } break; default: System.out.println("Was anderes, und zwar: "+actionKey.getActionKey()); break; } }
diff --git a/service/mcs/rest/src/main/java/eu/europeana/cloud/service/mcs/rest/JerseyConfig.java b/service/mcs/rest/src/main/java/eu/europeana/cloud/service/mcs/rest/JerseyConfig.java index daf56e86a..e629420bc 100644 --- a/service/mcs/rest/src/main/java/eu/europeana/cloud/service/mcs/rest/JerseyConfig.java +++ b/service/mcs/rest/src/main/java/eu/europeana/cloud/service/mcs/rest/JerseyConfig.java @@ -1,68 +1,69 @@ package eu.europeana.cloud.service.mcs.rest; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.spring.scope.RequestContextFilter; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.CannotModifyPersistentRepresentationExceptionMapper; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.CannotPersistEmptyRepresentationExceptionMapper; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.DataSetAlreadyExistsExceptionMapper; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.DataSetNotExistsExceptionMapper; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.FileAlreadyExistsExceptionMapper; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.FileNotExistsExceptionMapper; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.ProviderNotExistsExceptionMapper; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.RecordNotExistsExceptionMapper; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.RepresentationNotExistsExceptionMapper; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.RuntimeExceptionMapper; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.VersionNotExistsExceptionMapper; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.WebApplicationExceptionMapper; import eu.europeana.cloud.service.mcs.rest.exceptionmappers.WrongContentRangeExceptionMapper; /** * Jersey Configuration for Exception Mappers and Resources * */ public class JerseyConfig extends ResourceConfig { /** * Register JAX-RS application components. */ public JerseyConfig() { super(); //features register(MultiPartFeature.class); // filters register(RequestContextFilter.class); register(LoggingFilter.class); // exception mappers + register(CannotPersistEmptyRepresentationExceptionMapper.class); register(CannotModifyPersistentRepresentationExceptionMapper.class); register(CannotPersistEmptyRepresentationExceptionMapper.class); register(DataSetAlreadyExistsExceptionMapper.class); register(DataSetNotExistsExceptionMapper.class); register(FileAlreadyExistsExceptionMapper.class); register(FileNotExistsExceptionMapper.class); register(RecordNotExistsExceptionMapper.class); register(RepresentationNotExistsExceptionMapper.class); register(VersionNotExistsExceptionMapper.class); register(WrongContentRangeExceptionMapper.class); register(ProviderNotExistsExceptionMapper.class); register(WebApplicationExceptionMapper.class); register(RuntimeExceptionMapper.class); // resources register(RecordsResource.class); register(RepresentationResource.class); register(RepresentationsResource.class); register(RepresentationVersionResource.class); register(RepresentationVersionsResource.class); register(RepresentationSearchResource.class); register(FilesResource.class); register(FileResource.class); register(DataSetResource.class); register(DataSetsResource.class); register(DataSetAssignmentsResource.class); } }
true
true
public JerseyConfig() { super(); //features register(MultiPartFeature.class); // filters register(RequestContextFilter.class); register(LoggingFilter.class); // exception mappers register(CannotModifyPersistentRepresentationExceptionMapper.class); register(CannotPersistEmptyRepresentationExceptionMapper.class); register(DataSetAlreadyExistsExceptionMapper.class); register(DataSetNotExistsExceptionMapper.class); register(FileAlreadyExistsExceptionMapper.class); register(FileNotExistsExceptionMapper.class); register(RecordNotExistsExceptionMapper.class); register(RepresentationNotExistsExceptionMapper.class); register(VersionNotExistsExceptionMapper.class); register(WrongContentRangeExceptionMapper.class); register(ProviderNotExistsExceptionMapper.class); register(WebApplicationExceptionMapper.class); register(RuntimeExceptionMapper.class); // resources register(RecordsResource.class); register(RepresentationResource.class); register(RepresentationsResource.class); register(RepresentationVersionResource.class); register(RepresentationVersionsResource.class); register(RepresentationSearchResource.class); register(FilesResource.class); register(FileResource.class); register(DataSetResource.class); register(DataSetsResource.class); register(DataSetAssignmentsResource.class); }
public JerseyConfig() { super(); //features register(MultiPartFeature.class); // filters register(RequestContextFilter.class); register(LoggingFilter.class); // exception mappers register(CannotPersistEmptyRepresentationExceptionMapper.class); register(CannotModifyPersistentRepresentationExceptionMapper.class); register(CannotPersistEmptyRepresentationExceptionMapper.class); register(DataSetAlreadyExistsExceptionMapper.class); register(DataSetNotExistsExceptionMapper.class); register(FileAlreadyExistsExceptionMapper.class); register(FileNotExistsExceptionMapper.class); register(RecordNotExistsExceptionMapper.class); register(RepresentationNotExistsExceptionMapper.class); register(VersionNotExistsExceptionMapper.class); register(WrongContentRangeExceptionMapper.class); register(ProviderNotExistsExceptionMapper.class); register(WebApplicationExceptionMapper.class); register(RuntimeExceptionMapper.class); // resources register(RecordsResource.class); register(RepresentationResource.class); register(RepresentationsResource.class); register(RepresentationVersionResource.class); register(RepresentationVersionsResource.class); register(RepresentationSearchResource.class); register(FilesResource.class); register(FileResource.class); register(DataSetResource.class); register(DataSetsResource.class); register(DataSetAssignmentsResource.class); }
diff --git a/src/com/android/stk/StkApp.java b/src/com/android/stk/StkApp.java index 0b1f208..0f0af52 100644 --- a/src/com/android/stk/StkApp.java +++ b/src/com/android/stk/StkApp.java @@ -1,66 +1,66 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.stk; import android.app.Application; import com.android.internal.telephony.cat.Duration; /** * Top-level Application class for STK app. */ abstract class StkApp extends Application { // Application constants public static final boolean DBG = true; // Identifiers for option menu items static final int MENU_ID_END_SESSION = android.view.Menu.FIRST; static final int MENU_ID_BACK = android.view.Menu.FIRST + 1; static final int MENU_ID_HELP = android.view.Menu.FIRST + 2; // UI timeout, 30 seconds - used for display dialog and activities. static final int UI_TIMEOUT = (40 * 1000); // Tone default timeout - 2 seconds static final int TONE_DFEAULT_TIMEOUT = (2 * 1000); public static final String TAG = "STK App"; /** * This function calculate the time in MS from a duration instance. * returns zero when duration is null. */ public static int calculateDurationInMilis(Duration duration) { int timeout = 0; if (duration != null) { switch (duration.timeUnit) { case MINUTE: timeout = 1000 * 60; break; case TENTH_SECOND: - timeout = 1000 * 10; + timeout = 1000 / 10; break; case SECOND: default: timeout = 1000; break; } timeout *= duration.timeInterval; } return timeout; } }
true
true
public static int calculateDurationInMilis(Duration duration) { int timeout = 0; if (duration != null) { switch (duration.timeUnit) { case MINUTE: timeout = 1000 * 60; break; case TENTH_SECOND: timeout = 1000 * 10; break; case SECOND: default: timeout = 1000; break; } timeout *= duration.timeInterval; } return timeout; }
public static int calculateDurationInMilis(Duration duration) { int timeout = 0; if (duration != null) { switch (duration.timeUnit) { case MINUTE: timeout = 1000 * 60; break; case TENTH_SECOND: timeout = 1000 / 10; break; case SECOND: default: timeout = 1000; break; } timeout *= duration.timeInterval; } return timeout; }
diff --git a/strategoxt-java-backend/java/runtime/org/strategoxt/HybridInterpreter.java b/strategoxt-java-backend/java/runtime/org/strategoxt/HybridInterpreter.java index b6602ec1c..ee7c323c6 100644 --- a/strategoxt-java-backend/java/runtime/org/strategoxt/HybridInterpreter.java +++ b/strategoxt-java-backend/java/runtime/org/strategoxt/HybridInterpreter.java @@ -1,357 +1,358 @@ package org.strategoxt; import java.io.File; import java.io.IOException; import java.net.JarURLConnection; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.spoofax.interpreter.core.IContext; import org.spoofax.interpreter.core.Interpreter; import org.spoofax.interpreter.core.InterpreterErrorExit; import org.spoofax.interpreter.core.InterpreterException; import org.spoofax.interpreter.core.InterpreterExit; import org.spoofax.interpreter.core.StackTracer; import org.spoofax.interpreter.core.UndefinedStrategyException; import org.spoofax.interpreter.library.IOperatorRegistry; import org.spoofax.interpreter.stratego.SDefT; import org.spoofax.interpreter.terms.IStrategoString; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import org.strategoxt.lang.Context; import org.strategoxt.lang.InteropRegisterer; import org.strategoxt.lang.InteropSDefT; import org.strategoxt.lang.MissingStrategyException; import org.strategoxt.lang.StrategoErrorExit; import org.strategoxt.lang.StrategoException; import org.strategoxt.lang.StrategoExit; import org.strategoxt.lang.terms.TermFactory; import org.strategoxt.stratego_lib.stratego_lib; /** * An interpreter that uses STRJ-compiled versions of the Stratego standard libraries. * * This interpreter typically loads much faster than the standard interpreter. * Custom libraries can be added using their <code>registerInterop</code> * method: * * <code> * HybridInterpreter i = new HybridInterpreter(); * mylib.registerInterop(i.getContext(), i.getCompiledContext()); * </code> * * @author Lennart Kats <lennart add lclnet.nl> */ public class HybridInterpreter extends Interpreter { private static final String USAGE = "Uses: run [FILE.ctree | FILE.jar]... MAINCLASS [ARGUMENT]...\n" + " run PACKAGE.MAINCLASS [ARGUMENT]..."; private final HybridCompiledContext compiledContext; private boolean registeredLibraries; private boolean loadedJars; public HybridInterpreter() { this(new TermFactory()); } public HybridInterpreter(ITermFactory factory) { this(factory, factory); } public HybridInterpreter(ITermFactory termFactory, ITermFactory programFactory) { super(termFactory, programFactory); compiledContext = new HybridCompiledContext(termFactory); } public static void main(String... args) { if (args == null || args.length < 1) { System.out.println(USAGE); System.exit(127); } HybridInterpreter interpreter = new HybridInterpreter(); int i = mainLoadAll(interpreter, args); boolean nothingLoaded = i == 0; String main = args[i++]; if (nothingLoaded) warnUnqualifiedInvoke(interpreter, main); IStrategoString[] mainArgs = new IStrategoString[args.length - i + 1]; mainArgs[0] = interpreter.getFactory().makeString(main); for (int j = 1; j < mainArgs.length; i++, j++) { mainArgs[j] = interpreter.getFactory().makeString(args[i]); } interpreter.setCurrent(interpreter.getFactory().makeList(mainArgs)); try { interpreter.invoke(main); } catch (InterpreterExit e) { System.exit(e.getValue()); } catch (UndefinedStrategyException e) { System.err.println(e.getMessage()); System.exit(125); } catch (InterpreterException e) { e.printStackTrace(); System.exit(124); } } private static void warnUnqualifiedInvoke(HybridInterpreter interpreter, String main) { interpreter.init(); SDefT invoked = interpreter.lookupUncifiedSVar(main); if (invoked != null) { String name = ((InteropSDefT) invoked).getStrategy().getClass().getName(); System.err.println("Warning: unqualified invocation of " + name); } } private static int mainLoadAll(HybridInterpreter interpreter, String... args) { int i = 0; while (i < args.length) { try { if (args[i].endsWith(".ctree")) { interpreter.load(args[i++]); } else if (args[i].endsWith(".jar")) { URL[] jars = { new File(args[i++]).toURL() }; interpreter.loadJars(jars); } else { break; } } catch (Exception e) { System.err.println("Could not open input file " + args[i] + ": " + e.getClass().getSimpleName() + " - " + e.getMessage()); System.exit(126); } } boolean nothingLoaded = i == 0; if (i == args.length || (!nothingLoaded && args[i].indexOf('.') > -1)) { System.err.println(USAGE); System.exit(1); } else if (nothingLoaded && args[i].indexOf('.') > -1) { mainLocalJar(args); // avoid HybridInterpreter/InteropRegisters } return i; } private static void mainLocalJar(String... args) { String strategy = args[0]; String[] mainArgs = new String[args.length - 1]; System.arraycopy(args, 1, mainArgs, 0, mainArgs.length); try { Context context = new Context(); IStrategoTerm result; try { result = context.invokeStrategyCLI(strategy, strategy, mainArgs); } finally { context.getIOAgent().closeAllFiles(); } if (result == null) { System.err.println(strategy + (context.getTraceDepth() != 0 ? ": rewriting failed, trace:" : ": rewriting failed")); context.printStackTrace(); System.exit(1); } else { System.exit(0); } } catch (MissingStrategyException e) { System.err.println(e.getMessage()); System.exit(125); } catch (StrategoExit e) { System.exit(e.getValue()); } } @Override protected org.spoofax.interpreter.core.Context createContext(ITermFactory termFactory, ITermFactory programFactory) { return new HybridContext(termFactory, programFactory); } @Override public void load(IStrategoTerm term) throws InterpreterException { // Lazily register library strategies // (since this interpreter may only be used with compiled strategies) init(); super.load(term); } public void loadJars(URL... jars) throws SecurityException, IncompatibleJarException, IOException { loadJars(HybridInterpreter.class.getClassLoader(), jars); } public void loadJars(ClassLoader parentClassLoader, URL... jars) throws SecurityException, IncompatibleJarException, IOException { URLClassLoader classLoader = new URLClassLoader(jars, stratego_lib.class.getClassLoader()); loadedJars = true; for (URL jar : jars) { registerJar(classLoader, jar); } } private void registerJar(URLClassLoader classLoader, URL jar) throws SecurityException, IncompatibleJarException, IOException { URL protocolfulUrl = new URL("jar", "", jar + "!/"); JarURLConnection connection = (JarURLConnection) protocolfulUrl.openConnection(); + connection.setUseCaches(false); JarFile jarFile = connection.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); boolean foundRegisterer = false; while (jarEntries.hasMoreElements()) { String entry = jarEntries.nextElement().getName(); if (entry.endsWith("/InteropRegisterer.class") || entry.endsWith("$InteropRegisterer.class") || entry.equals("InteropRegisterer.class")) { final int POSTFIX = ".class".length(); String className = entry.substring(0, entry.length() - POSTFIX); className = className.replace('/', '.'); Class<?> registerClass; try { registerClass = classLoader.loadClass(className); Object registerObject = registerClass.newInstance(); if (registerObject instanceof InteropRegisterer) { ((InteropRegisterer) registerObject).registerLazy(getContext(), getCompiledContext(), classLoader); foundRegisterer = true; } else { throw new IncompatibleJarException(jar, new ClassCastException("Unknown type for InteropRegisterer")); } } catch (InstantiationException e) { throw new IncompatibleJarException(jar, e); } catch (IllegalAccessException e) { throw new IncompatibleJarException(jar, e); } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load listed class", e); } } } if (!foundRegisterer) throw new IncompatibleJarException(jar, "No STRJ InteropRegisterer classes found"); } /** * Eagerly initializes this interpreter, loading the standard libraries. * (If not invoked, load() ensures lazy initialization.) */ public void init() { if (!registeredLibraries) { registeredLibraries = true; registerLibraries(); } } /** * Initialize the interpreter register with all standard library strategies. */ protected void registerLibraries() { IContext context = getContext(); Context compiledContext = getCompiledContext(); // FIXME: HybridInterpreter loads all libs into the same namespace // Which may affect interpreted code and invoke() org.strategoxt.tools.Main.registerInterop(context, compiledContext); org.strategoxt.stratego_gpp.Main.registerInterop(context, compiledContext); org.strategoxt.stratego_aterm.Main.registerInterop(context, compiledContext); org.strategoxt.stratego_rtg.Main.registerInterop(context, compiledContext); org.strategoxt.stratego_sdf.Main.registerInterop(context, compiledContext); org.strategoxt.stratego_sglr.Main.registerInterop(context, compiledContext); org.strategoxt.stratego_tool_doc.Main.registerInterop(context, compiledContext); org.strategoxt.stratego_xtc.Main.registerInterop(context, compiledContext); org.strategoxt.java_front.Main.registerInterop(context, compiledContext); org.strategoxt.stratego_lib.Main.registerInterop(context, compiledContext); org.strategoxt.strc.Main.registerInterop(context, compiledContext); } public final Context getCompiledContext() { return compiledContext; } /** * Invokes a compiled or interpreted strategy bound to this instance. * * Wraps any StrategoException into checked InterpreterException exceptions. */ @Override public boolean invoke(String name) throws InterpreterErrorExit, InterpreterExit, UndefinedStrategyException, InterpreterException { try { if (!loadedJars) init(); return super.invoke(name); } catch (StrategoErrorExit e) { throw new InterpreterErrorExit(e.getMessage(), e.getTerm(), e); } catch (StrategoExit e) { throw new InterpreterExit(e.getValue(), e); } catch (MissingStrategyException e) { throw new UndefinedStrategyException(e); } catch (StrategoException e) { throw new InterpreterException(e); } } /** * A hybrid interpreter context. * * @author Lennart Kats <lennart add lclnet.nl> */ private class HybridContext extends org.spoofax.interpreter.core.Context { public HybridContext(ITermFactory termFactory, ITermFactory programFactory) { super(termFactory, programFactory, true); } @Override public void addOperatorRegistry(IOperatorRegistry or) { super.addOperatorRegistry(or); compiledContext.internalAddOperatorRegistry(or); } @Override @Deprecated public void addOperatorRegistry(String domain, IOperatorRegistry or) { super.addOperatorRegistry(domain, or); compiledContext.internalAddOperatorRegistry(or); } protected void internalAddOperatorRegistry(IOperatorRegistry or) { super.addOperatorRegistry(or); } @Override public StackTracer getStackTracer() { return compiledContext; } } /** * A hybrid compiled Stratego context. * * @author Lennart Kats <lennart add lclnet.nl> */ private class HybridCompiledContext extends Context { public HybridCompiledContext(ITermFactory factory) { super(factory); } @Override public void addOperatorRegistry(IOperatorRegistry or) { super.addOperatorRegistry(or); ((HybridContext) getContext()).internalAddOperatorRegistry(or); } protected void internalAddOperatorRegistry(IOperatorRegistry or) { super.addOperatorRegistry(or); } } }
true
true
private void registerJar(URLClassLoader classLoader, URL jar) throws SecurityException, IncompatibleJarException, IOException { URL protocolfulUrl = new URL("jar", "", jar + "!/"); JarURLConnection connection = (JarURLConnection) protocolfulUrl.openConnection(); JarFile jarFile = connection.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); boolean foundRegisterer = false; while (jarEntries.hasMoreElements()) { String entry = jarEntries.nextElement().getName(); if (entry.endsWith("/InteropRegisterer.class") || entry.endsWith("$InteropRegisterer.class") || entry.equals("InteropRegisterer.class")) { final int POSTFIX = ".class".length(); String className = entry.substring(0, entry.length() - POSTFIX); className = className.replace('/', '.'); Class<?> registerClass; try { registerClass = classLoader.loadClass(className); Object registerObject = registerClass.newInstance(); if (registerObject instanceof InteropRegisterer) { ((InteropRegisterer) registerObject).registerLazy(getContext(), getCompiledContext(), classLoader); foundRegisterer = true; } else { throw new IncompatibleJarException(jar, new ClassCastException("Unknown type for InteropRegisterer")); } } catch (InstantiationException e) { throw new IncompatibleJarException(jar, e); } catch (IllegalAccessException e) { throw new IncompatibleJarException(jar, e); } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load listed class", e); } } } if (!foundRegisterer) throw new IncompatibleJarException(jar, "No STRJ InteropRegisterer classes found"); }
private void registerJar(URLClassLoader classLoader, URL jar) throws SecurityException, IncompatibleJarException, IOException { URL protocolfulUrl = new URL("jar", "", jar + "!/"); JarURLConnection connection = (JarURLConnection) protocolfulUrl.openConnection(); connection.setUseCaches(false); JarFile jarFile = connection.getJarFile(); Enumeration<JarEntry> jarEntries = jarFile.entries(); boolean foundRegisterer = false; while (jarEntries.hasMoreElements()) { String entry = jarEntries.nextElement().getName(); if (entry.endsWith("/InteropRegisterer.class") || entry.endsWith("$InteropRegisterer.class") || entry.equals("InteropRegisterer.class")) { final int POSTFIX = ".class".length(); String className = entry.substring(0, entry.length() - POSTFIX); className = className.replace('/', '.'); Class<?> registerClass; try { registerClass = classLoader.loadClass(className); Object registerObject = registerClass.newInstance(); if (registerObject instanceof InteropRegisterer) { ((InteropRegisterer) registerObject).registerLazy(getContext(), getCompiledContext(), classLoader); foundRegisterer = true; } else { throw new IncompatibleJarException(jar, new ClassCastException("Unknown type for InteropRegisterer")); } } catch (InstantiationException e) { throw new IncompatibleJarException(jar, e); } catch (IllegalAccessException e) { throw new IncompatibleJarException(jar, e); } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load listed class", e); } } } if (!foundRegisterer) throw new IncompatibleJarException(jar, "No STRJ InteropRegisterer classes found"); }
diff --git a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/TypeInferencer2.java b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/TypeInferencer2.java index aeaac387..93f89d44 100644 --- a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/TypeInferencer2.java +++ b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/TypeInferencer2.java @@ -1,849 +1,851 @@ /******************************************************************************* * Copyright (c) 2010 xored software, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * xored software, Inc. - initial API and Implementation (Alex Panchenko) *******************************************************************************/ package org.eclipse.dltk.internal.javascript.ti; 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.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.eclipse.core.runtime.Assert; import org.eclipse.dltk.ast.ASTNode; import org.eclipse.dltk.core.IModelElement; import org.eclipse.dltk.javascript.ast.Script; import org.eclipse.dltk.javascript.core.JavaScriptPlugin; import org.eclipse.dltk.javascript.parser.JSProblem; import org.eclipse.dltk.javascript.parser.JSProblemReporter; import org.eclipse.dltk.javascript.typeinference.IValueCollection; import org.eclipse.dltk.javascript.typeinference.IValueReference; import org.eclipse.dltk.javascript.typeinference.ReferenceKind; import org.eclipse.dltk.javascript.typeinfo.IElementResolver; import org.eclipse.dltk.javascript.typeinfo.IMemberEvaluator; import org.eclipse.dltk.javascript.typeinfo.IModelBuilder; import org.eclipse.dltk.javascript.typeinfo.ITypeInfoContext; import org.eclipse.dltk.javascript.typeinfo.ITypeProvider; import org.eclipse.dltk.javascript.typeinfo.JSType2; import org.eclipse.dltk.javascript.typeinfo.JSTypeSet; import org.eclipse.dltk.javascript.typeinfo.ReferenceSource; import org.eclipse.dltk.javascript.typeinfo.TypeInfoManager; import org.eclipse.dltk.javascript.typeinfo.TypeMode; import org.eclipse.dltk.javascript.typeinfo.TypeUtil; import org.eclipse.dltk.javascript.typeinfo.model.AnyType; import org.eclipse.dltk.javascript.typeinfo.model.ArrayType; import org.eclipse.dltk.javascript.typeinfo.model.ClassType; import org.eclipse.dltk.javascript.typeinfo.model.FunctionType; import org.eclipse.dltk.javascript.typeinfo.model.JSType; import org.eclipse.dltk.javascript.typeinfo.model.MapType; import org.eclipse.dltk.javascript.typeinfo.model.Member; import org.eclipse.dltk.javascript.typeinfo.model.Parameter; import org.eclipse.dltk.javascript.typeinfo.model.Property; import org.eclipse.dltk.javascript.typeinfo.model.RecordType; import org.eclipse.dltk.javascript.typeinfo.model.Type; import org.eclipse.dltk.javascript.typeinfo.model.TypeInfoModelFactory; import org.eclipse.dltk.javascript.typeinfo.model.TypeInfoModelLoader; import org.eclipse.dltk.javascript.typeinfo.model.TypeKind; import org.eclipse.dltk.javascript.typeinfo.model.TypeRef; import org.eclipse.dltk.javascript.typeinfo.model.UndefinedType; import org.eclipse.dltk.javascript.typeinfo.model.UnionType; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.impl.ResourceImpl; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; public class TypeInferencer2 implements ITypeInferenceContext { private TypeInferencerVisitor visitor; private ReferenceSource source; private void initializeVisitor() { if (visitor == null) { visitor = new TypeInferencerVisitor(this); } visitor.initialize(); } public void setVisitor(TypeInferencerVisitor visitor) { this.visitor = visitor; } public void setModelElement(IModelElement modelElement) { setSource(new ReferenceSource(modelElement)); } public void setSource(ReferenceSource source) { this.source = source; } private static final boolean DEBUG = false; public void doInferencing(Script script) { if (DEBUG) System.out.println("Visiting " + source + " with " + visitor.getClass().getName() + " in " + Thread.currentThread().getName()); try { elements.clear(); modelBuilders = null; typeProviders = null; initializeVisitor(); visitor.visit(script); // IValueCollection collection = visitor.getCollection(); // visitor = null; // return collection; } catch (PositionReachedException e) { // visitor = null; throw e; } catch (RuntimeException e) { log(e); } catch (AssertionError e) { log(e); } // return null; } protected void log(Throwable e) { final JSProblemReporter reporter = visitor.getProblemReporter(); if (reporter != null) { reporter.reportProblem(new JSProblem(e)); } else { JavaScriptPlugin.error(e); } } public IValueReference evaluate(ASTNode node) { initializeVisitor(); return visitor.visit(node); } public IValueCollection getCollection() { return visitor.getCollection(); } public IValueCollection currentCollection() { return visitor.peekContext(); } private final Map<String, Type> types = new ConcurrentHashMap<String, Type>(); public Type getType(String typeName) { if (typeName == null || typeName.length() == 0) { return null; } final boolean queryProviders = canQueryTypeProviders(); return getType(typeName, null, queryProviders, true, !queryProviders, true); } public TypeRef getTypeRef(String typeName) { return TypeUtil.ref(getType(typeName)); } public Type getKnownType(String typeName, TypeMode mode) { if (typeName == null || typeName.length() == 0) { return null; } final boolean queryProviders = canQueryTypeProviders(); return getType(typeName, mode, queryProviders, true, !queryProviders, false); } private boolean isResolved(JSType type) { if (type instanceof TypeRef) { return !((TypeRef) type).getTarget().isProxy(); } else if (type instanceof ClassType) { final Type t = ((ClassType) type).getTarget(); return t == null || !t.isProxy(); } else if (type instanceof ArrayType) { return isResolved(((ArrayType) type).getItemType()); } else if (type instanceof MapType) { final MapType mapType = (MapType) type; return isResolved(mapType.getValueType()) && isResolved(mapType.getKeyType()); } else if (type instanceof AnyType || type instanceof UndefinedType) { return true; } else if (type instanceof UnionType) { for (JSType t : ((UnionType) type).getTargets()) { if (!isResolved(t)) { return false; } } return true; } else if (type instanceof RecordType) { for (Member member : ((RecordType) type).getMembers()) { if (!isResolved(member.getType())) { return false; } } return true; } else if (type instanceof FunctionType) { final FunctionType funcType = (FunctionType) type; if (!isResolved(funcType.getReturnType())) { return false; } for (Parameter parameter : funcType.getParameters()) { if (!isResolved(parameter.getType())) { return false; } } return true; } return false; } public JSType resolveTypeRef(JSType type) { if (type == null || isResolved(type)) { return type; } return doResolveTypeRef(type); } private JSType2 doResolveTypeRef(JSType type) { if (type instanceof TypeRef) { final TypeRef r = (TypeRef) type; return JSTypeSet.ref(doResolveType(r.getTarget())); } else if (type instanceof ClassType) { final ClassType c = (ClassType) type; - return JSTypeSet.classType(doResolveType(c.getTarget())); + final Type target = c.getTarget(); + return JSTypeSet.classType(target != null ? doResolveType(target) + : null); } else if (type instanceof ArrayType) { return JSTypeSet.arrayOf(doResolveTypeRef(((ArrayType) type) .getItemType())); } else if (type instanceof MapType) { final MapType mapType = (MapType) type; return JSTypeSet.mapOf(doResolveTypeRef(mapType.getKeyType()), doResolveTypeRef(mapType.getValueType())); } else if (type instanceof UnionType) { final List<JSType2> targets = new ArrayList<JSType2>(); for (JSType t : ((UnionType) type).getTargets()) { targets.add(doResolveTypeRef(t)); } return JSTypeSet.union(targets); } else if (type instanceof AnyType) { return JSTypeSet.any(); } else if (type instanceof FunctionType) { final FunctionType funcType = (FunctionType) type; final EList<Parameter> params = new BasicEList<Parameter>(); for (Parameter parameter : funcType.getParameters()) { params.add(JSTypeSet.parameter(parameter.getName(), doResolveTypeRef(parameter.getType()))); } return JSTypeSet.functionType(funcType.getParameters(), doResolveTypeRef(funcType.getReturnType())); } else if (type instanceof RecordType) { // TODO (alex) make a copy of Type? final Type target = ((RecordType) type).getTarget(); for (Member member : target.getMembers()) { if (member.getType() instanceof TypeRef) { final TypeRef ref = (TypeRef) member.getType(); ref.setTarget(doResolveType(ref.getTarget())); } } return JSTypeSet.record(target); } return (JSType2) type; } private Type doResolveType(Type type) { if (type.isProxy()) { final String typeName = URI.decode(((InternalEObject) type) .eProxyURI().fragment()); final Type resolved = getType(typeName, null, true, true, false, true); if (resolved != null) { return resolved; } } return type; } public Set<String> listTypes(TypeMode mode, String prefix) { Set<String> result = new HashSet<String>(); Set<String> typeNames = TypeInfoModelLoader.getInstance().listTypes( prefix); if (typeNames != null) { result.addAll(typeNames); } for (ITypeProvider provider : getTypeProviders()) { typeNames = provider.listTypes(this, mode, prefix); if (typeNames != null) { result.addAll(typeNames); } } return result; } /** * @return the source */ public ReferenceSource getSource() { return source; } public IValueCollection getTopValueCollection() { if (resolve) { for (IMemberEvaluator evaluator : TypeInfoManager .getMemberEvaluators()) { final IValueCollection collection = evaluator .getTopValueCollection(this); if (collection != null) { return collection; } } } return null; } public IModelElement getModelElement() { return source != null ? source.getModelElement() : null; } public String getContext() { return null; } private enum TypeResolveMode { SIMPLE, PROXY, UNKNOWN } private Type getType(String typeName, TypeMode mode, boolean queryProviders, boolean queryPredefined, boolean allowProxy, boolean allowUnknown) { Type type = types.get(typeName); if (type != null) { if (!allowUnknown && type.getKind() == TypeKind.UNKNOWN) { return null; } return type; } type = invariantRS.getCachedType(typeName); if (type != null) { types.put(typeName, type); return type; } type = loadType(typeName, mode, queryProviders, queryPredefined); if (type != null) { validateTypeInfo(type); types.put(typeName, type); typeRS.addToResource(type); return type; } if (allowProxy) { type = TypeUtil.createProxy(typeName); return type; } if (allowUnknown) { type = createUnknown(typeName); typeRS.addToResource(type); types.put(typeName, type); return type; } return null; } private void validateTypeInfo(Type type) { final Resource resource = ((EObject) type).eResource(); if (resource != null) { final URI u = resource.getURI(); if (u != null && (u.isFile() || u.isPlatform())) { return; } boolean validResource = resource == invariantRS.getResource() || TypeInfoModelLoader.getInstance().hasResource(resource); if (!validResource) { Iterator<InvariantTypeResourceSet> iterator = invariantContextRS .values().iterator(); while (iterator.hasNext()) { validResource = iterator.next().getResource() == resource; if (validResource) break; } Assert.isTrue(validResource, "Type " + type.getName() + " has invalid resource: " + resource); } } // TODO check that member referenced types are contained or proxy } public void markInvariant(Type type) { if (((EObject) type).eResource() != null) { return; } invariantRS.add(type); } public void markInvariant(Type type, String context) { if (((EObject) type).eResource() != null) { return; } if (context == null) { markInvariant(type); } else { Assert.isLegal(((EObject) type).eContainer() == null); Assert.isLegal(((EObject) type).eResource() == null); InvariantTypeResourceSet invariantTypeResourceSet = invariantContextRS .get(context); if (invariantTypeResourceSet == null) { invariantTypeResourceSet = new InvariantTypeResourceSet( context, invariantRS, invariantContextRS); InvariantTypeResourceSet set = invariantContextRS.putIfAbsent( context, invariantTypeResourceSet); if (set != null) { invariantTypeResourceSet = set; } } invariantTypeResourceSet.add(type); } } public Type getInvariantType(String typeName, String context) { if (context == null) { return invariantRS.getCachedType(typeName); } else { InvariantTypeResourceSet invariantTypeResourceSet = invariantContextRS .get(context); if (invariantTypeResourceSet != null) { return invariantTypeResourceSet.getCachedType(typeName); } } return null; } protected static Type createUnknown(String typeName) { final Type type = TypeInfoModelFactory.eINSTANCE.createType(); type.setName(typeName); type.setKind(TypeKind.UNKNOWN); return type; } private final Map<String, Boolean> activeTypeRequests = new HashMap<String, Boolean>(); private boolean canQueryTypeProviders() { return activeTypeRequests.isEmpty(); } private Type loadType(String typeName, TypeMode mode, boolean queryProviders, boolean queryPredefined) { if (queryProviders && activeTypeRequests.put(typeName, Boolean.FALSE) == null) { try { Type type = invariantRS.getCachedType(typeName); if (type != null) { return type; } for (ITypeProvider provider : getTypeProviders()) { type = provider.getType(this, mode, typeName); if (type != null && !isProxy(type)) { return type; } } } finally { activeTypeRequests.remove(typeName); } } if (queryPredefined) { Type type = TypeInfoModelLoader.getInstance().getType(typeName); if (type != null) { return type; } } return null; } private ITypeProvider[] typeProviders = null; public ITypeProvider[] getTypeProviders() { if (typeProviders == null) { typeProviders = createTypeProviders(); } return typeProviders; } protected ITypeProvider[] createTypeProviders() { return TypeInfoManager.createTypeProviders(this); } static abstract class TypeResourceSet extends ResourceSetImpl { @Override public EObject getEObject(URI uri, boolean loadOnDemand) { if (TypeUtil.isTypeProxy(uri)) { final String typeName = URI.decode(uri.fragment()); final Type type = resolveTypeProxy(typeName); if (type == null) { return (EObject) createUnknown(typeName); } else if (type instanceof EObject) { return (EObject) type; } else { JavaScriptPlugin.error("proxy resolved to " + type.getClass().getName() + " which is not EObject"); return (EObject) createUnknown(typeName); } } return super.getEObject(uri, loadOnDemand); } protected abstract Type resolveTypeProxy(String typeName); public synchronized Resource getResource() { if (typesResource == null) { typesResource = new ResourceImpl( TypeUtil.createProxyResourceURI()); getResources().add(typesResource); } return typesResource; } private Resource typesResource = null; public void addToResource(final Type type) { final EObject object = (EObject) type; if (object.eResource() == null) { add(type); } } protected synchronized void add(Type type) { getResource().getContents().add((EObject) type); } } private final TypeResourceSet typeRS = new TypeResourceSet() { @Override protected Type resolveTypeProxy(String typeName) { return getType(typeName, null, true, false, false, false); } }; static class InvariantTypeResourceSet extends TypeResourceSet implements ITypeInfoContext { private final String context; private final InvariantTypeResourceSet staticInvariants; private final ConcurrentMap<String, InvariantTypeResourceSet> contextInvariants; public InvariantTypeResourceSet( ConcurrentMap<String, InvariantTypeResourceSet> contextInvariants) { this(null, null, contextInvariants); } public InvariantTypeResourceSet( String context, InvariantTypeResourceSet staticInvariants, ConcurrentMap<String, InvariantTypeResourceSet> contextInvariants) { this.context = context; this.staticInvariants = staticInvariants; this.contextInvariants = contextInvariants; } private final Set<String> activeTypeRequests = new HashSet<String>(); private final Map<String, Type> types = new ConcurrentHashMap<String, Type>(); private boolean canQueryTypeProviders() { synchronized (activeTypeRequests) { return activeTypeRequests.isEmpty(); } } public String getContext() { return context; } private Type getType(String typeName, TypeMode mode, boolean queryProviders, boolean queryPredefined, boolean allowProxy, boolean allowUnknown) { Type type = types.get(typeName); if (type != null) { return type; } type = loadType(typeName, mode, queryProviders, queryPredefined); if (type != null) { // TODO validateTypeInfo(type); addToResource(type); return type; } if (allowProxy) { type = TypeUtil.createProxy(typeName); return type; } if (allowUnknown) { type = createUnknown(typeName); addToResource(type); return type; } return null; } public TypeRef getTypeRef(String typeName) { return TypeUtil.ref(getType(typeName)); } private ITypeProvider[] typeProviders = null; public ITypeProvider[] getTypeProviders() { if (typeProviders == null) { typeProviders = TypeInfoManager.createTypeProviders(this); } return typeProviders; } private Type loadType(String typeName, TypeMode mode, boolean queryProviders, boolean queryPredefined) { if (queryProviders) { synchronized (activeTypeRequests) { while (!activeTypeRequests.add(typeName)) { try { activeTypeRequests.wait(); } catch (InterruptedException e) { } } } try { Type type = types.get(typeName); if (type != null) { return type; } for (ITypeProvider provider : getTypeProviders()) { type = provider.getType(this, mode, typeName); if (type != null && !isProxy(type)) { return type; } } } finally { synchronized (activeTypeRequests) { activeTypeRequests.remove(typeName); activeTypeRequests.notifyAll(); } } } if (queryPredefined) { Type type = TypeInfoModelLoader.getInstance().getType(typeName); if (type != null) { return type; } } return null; } @Override protected Type resolveTypeProxy(String typeName) { if (staticInvariants != null) { Type cachedType = staticInvariants.getCachedType(typeName); if (cachedType != null) return cachedType; } return getType(typeName, null, true, false, false, false); } public Type getType(String typeName) { if (typeName == null || typeName.length() == 0) { return null; } final boolean queryProviders = canQueryTypeProviders(); return getType(typeName, null, queryProviders, true, !queryProviders, true); } public Type getKnownType(String typeName, TypeMode mode) { if (typeName == null || typeName.length() == 0) { return null; } final boolean queryProviders = canQueryTypeProviders(); return getType(typeName, null, queryProviders, true, !queryProviders, false); } public void markInvariant(Type type) { if (((EObject) type).eResource() != null) { return; } // context == null, this is a static one if (staticInvariants == null) add(type); else staticInvariants.add(type); } public void markInvariant(Type type, String context) { if (((EObject) type).eResource() != null) { return; } if (context.equals(this.context)) { add(type); } else { InvariantTypeResourceSet invariantTypeResourceSet = this.contextInvariants .get(context); if (invariantTypeResourceSet == null) { invariantTypeResourceSet = new InvariantTypeResourceSet( context, invariantRS, invariantContextRS); InvariantTypeResourceSet set = invariantContextRS .putIfAbsent(context, invariantTypeResourceSet); if (set != null) { invariantTypeResourceSet = set; } } invariantTypeResourceSet.add(type); } } public Type getInvariantType(String typeName, String context) { if (context == null) { if (staticInvariants == null) { return getCachedType(typeName); } else { return staticInvariants.getCachedType(typeName); } } else if (context.equals(this.context)) { return getCachedType(typeName); } else { InvariantTypeResourceSet invariantTypeResourceSet = invariantContextRS .get(context); if (invariantTypeResourceSet != null) { return invariantTypeResourceSet.getCachedType(typeName); } } return null; } public IModelElement getModelElement() { return null; } public ReferenceSource getSource() { return ReferenceSource.UNKNOWN; } @Override public void add(Type type) { super.add(type); types.put(type.getName(), type); } public Type getCachedType(String typeName) { return types.get(typeName); } public void reset() { types.clear(); synchronized (this) { getResource().getContents().clear(); } } } static final ConcurrentHashMap<String, InvariantTypeResourceSet> invariantContextRS = new ConcurrentHashMap<String, InvariantTypeResourceSet>(); static final InvariantTypeResourceSet invariantRS = new InvariantTypeResourceSet( invariantContextRS); protected static boolean isProxy(Type type) { return type instanceof EObject && ((EObject) type).eIsProxy(); } private IValueTypeFactory factory = new ValueTypeFactoryImpl(this); public IValueTypeFactory getFactory() { return factory; } private boolean resolve = true; private Map<String, Member> elements = new HashMap<String, Member>(); public Member resolve(String name) { if (name == null) return null; Member element = elements.get(name); if (element != null) { return element; } element = TypeInfoModelLoader.getInstance().getMember(name); if (element != null) { elements.put(name, element); return element; } if (resolve) { for (IElementResolver resolver : TypeInfoManager .getElementResolvers()) { element = resolver.resolveElement(this, name); if (element != null) { elements.put(name, element); return element; } } } return null; } public IValue valueOf(Member member) { for (IMemberEvaluator evaluator : TypeInfoManager.getMemberEvaluators()) { final IValueCollection collection = evaluator.valueOf(this, member); if (collection != null) { if (collection instanceof IValueProvider) { IValue value = ((IValueProvider) collection).getValue(); if (member.getType() != null) { value.setDeclaredType(member.getType()); } if (value.getKind() == ReferenceKind.UNKNOWN) { if (member instanceof Property) { value.setKind(ReferenceKind.PROPERTY); } else { value.setKind(ReferenceKind.METHOD); } } return value; } else { break; } } } return ElementValue.createFor(member, this); } public Set<String> listGlobals(String prefix) { final Set<String> result = new HashSet<String>(); for (Member member : TypeInfoModelLoader.getInstance().listMembers( prefix)) { result.add(member.getName()); } for (IElementResolver resolver : TypeInfoManager.getElementResolvers()) { Set<String> globals = resolver.listGlobals(this, prefix); if (globals != null) { result.addAll(globals); } } return result; } public void setDoResolve(boolean resolve) { this.resolve = resolve; } private IModelBuilder[] modelBuilders = null; public IModelBuilder[] getModelBuilders() { if (modelBuilders == null) { modelBuilders = TypeInfoManager.getModelBuilders(this); } return modelBuilders; } }
true
true
private JSType2 doResolveTypeRef(JSType type) { if (type instanceof TypeRef) { final TypeRef r = (TypeRef) type; return JSTypeSet.ref(doResolveType(r.getTarget())); } else if (type instanceof ClassType) { final ClassType c = (ClassType) type; return JSTypeSet.classType(doResolveType(c.getTarget())); } else if (type instanceof ArrayType) { return JSTypeSet.arrayOf(doResolveTypeRef(((ArrayType) type) .getItemType())); } else if (type instanceof MapType) { final MapType mapType = (MapType) type; return JSTypeSet.mapOf(doResolveTypeRef(mapType.getKeyType()), doResolveTypeRef(mapType.getValueType())); } else if (type instanceof UnionType) { final List<JSType2> targets = new ArrayList<JSType2>(); for (JSType t : ((UnionType) type).getTargets()) { targets.add(doResolveTypeRef(t)); } return JSTypeSet.union(targets); } else if (type instanceof AnyType) { return JSTypeSet.any(); } else if (type instanceof FunctionType) { final FunctionType funcType = (FunctionType) type; final EList<Parameter> params = new BasicEList<Parameter>(); for (Parameter parameter : funcType.getParameters()) { params.add(JSTypeSet.parameter(parameter.getName(), doResolveTypeRef(parameter.getType()))); } return JSTypeSet.functionType(funcType.getParameters(), doResolveTypeRef(funcType.getReturnType())); } else if (type instanceof RecordType) { // TODO (alex) make a copy of Type? final Type target = ((RecordType) type).getTarget(); for (Member member : target.getMembers()) { if (member.getType() instanceof TypeRef) { final TypeRef ref = (TypeRef) member.getType(); ref.setTarget(doResolveType(ref.getTarget())); } } return JSTypeSet.record(target); } return (JSType2) type; }
private JSType2 doResolveTypeRef(JSType type) { if (type instanceof TypeRef) { final TypeRef r = (TypeRef) type; return JSTypeSet.ref(doResolveType(r.getTarget())); } else if (type instanceof ClassType) { final ClassType c = (ClassType) type; final Type target = c.getTarget(); return JSTypeSet.classType(target != null ? doResolveType(target) : null); } else if (type instanceof ArrayType) { return JSTypeSet.arrayOf(doResolveTypeRef(((ArrayType) type) .getItemType())); } else if (type instanceof MapType) { final MapType mapType = (MapType) type; return JSTypeSet.mapOf(doResolveTypeRef(mapType.getKeyType()), doResolveTypeRef(mapType.getValueType())); } else if (type instanceof UnionType) { final List<JSType2> targets = new ArrayList<JSType2>(); for (JSType t : ((UnionType) type).getTargets()) { targets.add(doResolveTypeRef(t)); } return JSTypeSet.union(targets); } else if (type instanceof AnyType) { return JSTypeSet.any(); } else if (type instanceof FunctionType) { final FunctionType funcType = (FunctionType) type; final EList<Parameter> params = new BasicEList<Parameter>(); for (Parameter parameter : funcType.getParameters()) { params.add(JSTypeSet.parameter(parameter.getName(), doResolveTypeRef(parameter.getType()))); } return JSTypeSet.functionType(funcType.getParameters(), doResolveTypeRef(funcType.getReturnType())); } else if (type instanceof RecordType) { // TODO (alex) make a copy of Type? final Type target = ((RecordType) type).getTarget(); for (Member member : target.getMembers()) { if (member.getType() instanceof TypeRef) { final TypeRef ref = (TypeRef) member.getType(); ref.setTarget(doResolveType(ref.getTarget())); } } return JSTypeSet.record(target); } return (JSType2) type; }
diff --git a/eol-globi-data-tool/src/test/java/org/eol/globi/data/taxon/TaxonNameNormalizerTest.java b/eol-globi-data-tool/src/test/java/org/eol/globi/data/taxon/TaxonNameNormalizerTest.java index 69125cd1..762d165f 100644 --- a/eol-globi-data-tool/src/test/java/org/eol/globi/data/taxon/TaxonNameNormalizerTest.java +++ b/eol-globi-data-tool/src/test/java/org/eol/globi/data/taxon/TaxonNameNormalizerTest.java @@ -1,99 +1,99 @@ package org.eol.globi.data.taxon; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class TaxonNameNormalizerTest { @Test public void cleanName() { TaxonNameNormalizer normalizer = new TaxonNameNormalizer(); assertThat(normalizer.normalize("Blbua blas "), is("Blbua blas")); assertThat(normalizer.normalize("Blbua blas "), is("Blbua blas")); assertThat(normalizer.normalize("Blbua blas (akjhaskdjhf)"), is("Blbua blas")); assertThat(normalizer.normalize(" Blbua blas (akjhaskdjhf)"), is("Blbua blas")); assertThat(normalizer.normalize("Aegathoa oculata¬†"), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata*"), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata?"), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata sp."), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata spp"), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata spp."), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata spp. Aegathoa oculata spp. Aegathoa oculata spp."), is("Aegathoa oculata")); assertThat(normalizer.normalize("Taraxacum leptaleum"), is("Taraxacum leptaleum")); assertThat(normalizer.normalize("NA"), is("NomenNescio")); assertThat(normalizer.normalize("NE"), is("NomenNescio")); assertThat(normalizer.normalize("'Loranthus'"), is("Loranthus")); assertThat(normalizer.normalize("Bacteriastrum spp. Bacteriastrum spp. Bacteriastrum spp. Bacteriastrum spp."), is("Bacteriastrum")); assertThat(normalizer.normalize("Acrididae spp. "), is("Acrididae")); assertThat(normalizer.normalize("<quotes>Chenopodiaceae<quotes>"), is("Chenopodiaceae")); assertThat(normalizer.normalize("Mycosphaerella filipendulae-denudatae"), is("Mycosphaerella filipendulae-denudatae")); assertThat(normalizer.normalize("Puccinia dioicae var. dioicae"), is("Puccinia dioicae var. dioicae")); assertThat(normalizer.normalize("Puccinia dioicae var dioicae"), is("Puccinia dioicae var. dioicae")); assertThat(normalizer.normalize("Puccinia dioicae variety dioicae"), is("Puccinia dioicae var. dioicae")); assertThat(normalizer.normalize("Puccinia dioicae varietas dioicae"), is("Puccinia dioicae var. dioicae")); assertThat(normalizer.normalize("Aegathoa oculata ssp. fred"), is("Aegathoa oculata ssp. fred")); assertThat(normalizer.normalize("Aegathoa oculata ssp fred"), is("Aegathoa oculata ssp. fred")); assertThat(normalizer.normalize("Aegathoa oculata subsp fred"), is("Aegathoa oculata ssp. fred")); assertThat(normalizer.normalize("Aegathoa oculata subsp. fred"), is("Aegathoa oculata ssp. fred")); assertThat(normalizer.normalize("Aegathoa oculata subspecies fred"), is("Aegathoa oculata ssp. fred")); //assertThat(normalizer.normalize("Armeria 'Bees Ruby'"), is("Armeria 'Bees Ruby'")); assertThat(normalizer.normalize("Rubus fruticosus agg."), is("Rubus fruticosus agg.")); assertThat(normalizer.normalize("Limonia (Dicranomyia) chorea"), is("Limonia chorea")); assertThat(normalizer.normalize("Archips podana/operana"), is("Archips")); assertThat(normalizer.normalize("Leptochela cf bermudensis"), is("Leptochela")); assertThat(normalizer.normalize("S enflata"), is("Sagitta enflata")); assertThat(normalizer.normalize("Aneugmenus fürstenbergensis"), is("Aneugmenus fuerstenbergensis")); assertThat(normalizer.normalize("Xanthorhoë"), is("Xanthorhoe")); // Malcolm Storey technique to distinguish duplicate genus names in taxonomies. assertThat(normalizer.normalize("Ammophila (Bot.)"), is("Ammophila (Bot.)")); assertThat(normalizer.normalize("Ammophila (Zool.)"), is("Ammophila (Zool.)")); assertThat(normalizer.normalize("Ammophila (zoo)"), is("Ammophila (zoo)")); assertThat(normalizer.normalize("Ammophila (bot)"), is("Ammophila (bot)")); assertThat(normalizer.normalize("Ammophila (bot.)"), is("Ammophila (bot.)")); assertThat(normalizer.normalize("Ammophila (Bot)"), is("Ammophila (Bot)")); assertThat(normalizer.normalize("Ammophila (blah)"), is("Ammophila")); assertThat(normalizer.normalize("Cal sapidus"), is("Callinectes sapidus")); - assertThat(normalizer.normalize("Bivalvia Genus A"), is("Bivalva")); + assertThat(normalizer.normalize("Bivalvia Genus A"), is("Bivalvia")); } /** * In scientific names of hybrids (e.g. Erysimum decumbens x perofskianum, http://eol.org/pages/5145889), * the \u00D7 or × (multiply) symbol should be used. However, most data sources simply use lower case "x", * and don't support the × symbol is their name matching methods. */ @Test public void replaceMultiplyOrXByLowerCaseX() { TaxonNameNormalizer normalizer = new TaxonNameNormalizer(); assertThat(normalizer.normalize("Genus species1 x species2"), is("Genus species1 x species2")); assertThat(normalizer.normalize("Genus species1 \u00D7 species2"), is("Genus species1 x species2")); assertThat(normalizer.normalize("Genus species1 × species2"), is("Genus species1 x species2")); assertThat(normalizer.normalize("Genus species1 ×hybridName"), is("Genus species1 xhybridName")); assertThat(normalizer.normalize("Genus species1 X species2"), is("Genus species1 x species2")); assertThat(normalizer.normalize("Genus species1 XhybridName"), is("Genus species1 xhybridName")); } @Test public void taxonNameTooShort() { TaxonNameNormalizer normalizer = new TaxonNameNormalizer(); assertThat(normalizer.normalize("G"), is("NomenNescio")); assertThat(normalizer.normalize("H"), is("NomenNescio")); assertThat(normalizer.normalize("HH"), is("HH")); } }
true
true
public void cleanName() { TaxonNameNormalizer normalizer = new TaxonNameNormalizer(); assertThat(normalizer.normalize("Blbua blas "), is("Blbua blas")); assertThat(normalizer.normalize("Blbua blas "), is("Blbua blas")); assertThat(normalizer.normalize("Blbua blas (akjhaskdjhf)"), is("Blbua blas")); assertThat(normalizer.normalize(" Blbua blas (akjhaskdjhf)"), is("Blbua blas")); assertThat(normalizer.normalize("Aegathoa oculata¬†"), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata*"), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata?"), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata sp."), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata spp"), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata spp."), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata spp. Aegathoa oculata spp. Aegathoa oculata spp."), is("Aegathoa oculata")); assertThat(normalizer.normalize("Taraxacum leptaleum"), is("Taraxacum leptaleum")); assertThat(normalizer.normalize("NA"), is("NomenNescio")); assertThat(normalizer.normalize("NE"), is("NomenNescio")); assertThat(normalizer.normalize("'Loranthus'"), is("Loranthus")); assertThat(normalizer.normalize("Bacteriastrum spp. Bacteriastrum spp. Bacteriastrum spp. Bacteriastrum spp."), is("Bacteriastrum")); assertThat(normalizer.normalize("Acrididae spp. "), is("Acrididae")); assertThat(normalizer.normalize("<quotes>Chenopodiaceae<quotes>"), is("Chenopodiaceae")); assertThat(normalizer.normalize("Mycosphaerella filipendulae-denudatae"), is("Mycosphaerella filipendulae-denudatae")); assertThat(normalizer.normalize("Puccinia dioicae var. dioicae"), is("Puccinia dioicae var. dioicae")); assertThat(normalizer.normalize("Puccinia dioicae var dioicae"), is("Puccinia dioicae var. dioicae")); assertThat(normalizer.normalize("Puccinia dioicae variety dioicae"), is("Puccinia dioicae var. dioicae")); assertThat(normalizer.normalize("Puccinia dioicae varietas dioicae"), is("Puccinia dioicae var. dioicae")); assertThat(normalizer.normalize("Aegathoa oculata ssp. fred"), is("Aegathoa oculata ssp. fred")); assertThat(normalizer.normalize("Aegathoa oculata ssp fred"), is("Aegathoa oculata ssp. fred")); assertThat(normalizer.normalize("Aegathoa oculata subsp fred"), is("Aegathoa oculata ssp. fred")); assertThat(normalizer.normalize("Aegathoa oculata subsp. fred"), is("Aegathoa oculata ssp. fred")); assertThat(normalizer.normalize("Aegathoa oculata subspecies fred"), is("Aegathoa oculata ssp. fred")); //assertThat(normalizer.normalize("Armeria 'Bees Ruby'"), is("Armeria 'Bees Ruby'")); assertThat(normalizer.normalize("Rubus fruticosus agg."), is("Rubus fruticosus agg.")); assertThat(normalizer.normalize("Limonia (Dicranomyia) chorea"), is("Limonia chorea")); assertThat(normalizer.normalize("Archips podana/operana"), is("Archips")); assertThat(normalizer.normalize("Leptochela cf bermudensis"), is("Leptochela")); assertThat(normalizer.normalize("S enflata"), is("Sagitta enflata")); assertThat(normalizer.normalize("Aneugmenus fürstenbergensis"), is("Aneugmenus fuerstenbergensis")); assertThat(normalizer.normalize("Xanthorhoë"), is("Xanthorhoe")); // Malcolm Storey technique to distinguish duplicate genus names in taxonomies. assertThat(normalizer.normalize("Ammophila (Bot.)"), is("Ammophila (Bot.)")); assertThat(normalizer.normalize("Ammophila (Zool.)"), is("Ammophila (Zool.)")); assertThat(normalizer.normalize("Ammophila (zoo)"), is("Ammophila (zoo)")); assertThat(normalizer.normalize("Ammophila (bot)"), is("Ammophila (bot)")); assertThat(normalizer.normalize("Ammophila (bot.)"), is("Ammophila (bot.)")); assertThat(normalizer.normalize("Ammophila (Bot)"), is("Ammophila (Bot)")); assertThat(normalizer.normalize("Ammophila (blah)"), is("Ammophila")); assertThat(normalizer.normalize("Cal sapidus"), is("Callinectes sapidus")); assertThat(normalizer.normalize("Bivalvia Genus A"), is("Bivalva")); }
public void cleanName() { TaxonNameNormalizer normalizer = new TaxonNameNormalizer(); assertThat(normalizer.normalize("Blbua blas "), is("Blbua blas")); assertThat(normalizer.normalize("Blbua blas "), is("Blbua blas")); assertThat(normalizer.normalize("Blbua blas (akjhaskdjhf)"), is("Blbua blas")); assertThat(normalizer.normalize(" Blbua blas (akjhaskdjhf)"), is("Blbua blas")); assertThat(normalizer.normalize("Aegathoa oculata¬†"), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata*"), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata?"), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata sp."), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata spp"), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata spp."), is("Aegathoa oculata")); assertThat(normalizer.normalize("Aegathoa oculata spp. Aegathoa oculata spp. Aegathoa oculata spp."), is("Aegathoa oculata")); assertThat(normalizer.normalize("Taraxacum leptaleum"), is("Taraxacum leptaleum")); assertThat(normalizer.normalize("NA"), is("NomenNescio")); assertThat(normalizer.normalize("NE"), is("NomenNescio")); assertThat(normalizer.normalize("'Loranthus'"), is("Loranthus")); assertThat(normalizer.normalize("Bacteriastrum spp. Bacteriastrum spp. Bacteriastrum spp. Bacteriastrum spp."), is("Bacteriastrum")); assertThat(normalizer.normalize("Acrididae spp. "), is("Acrididae")); assertThat(normalizer.normalize("<quotes>Chenopodiaceae<quotes>"), is("Chenopodiaceae")); assertThat(normalizer.normalize("Mycosphaerella filipendulae-denudatae"), is("Mycosphaerella filipendulae-denudatae")); assertThat(normalizer.normalize("Puccinia dioicae var. dioicae"), is("Puccinia dioicae var. dioicae")); assertThat(normalizer.normalize("Puccinia dioicae var dioicae"), is("Puccinia dioicae var. dioicae")); assertThat(normalizer.normalize("Puccinia dioicae variety dioicae"), is("Puccinia dioicae var. dioicae")); assertThat(normalizer.normalize("Puccinia dioicae varietas dioicae"), is("Puccinia dioicae var. dioicae")); assertThat(normalizer.normalize("Aegathoa oculata ssp. fred"), is("Aegathoa oculata ssp. fred")); assertThat(normalizer.normalize("Aegathoa oculata ssp fred"), is("Aegathoa oculata ssp. fred")); assertThat(normalizer.normalize("Aegathoa oculata subsp fred"), is("Aegathoa oculata ssp. fred")); assertThat(normalizer.normalize("Aegathoa oculata subsp. fred"), is("Aegathoa oculata ssp. fred")); assertThat(normalizer.normalize("Aegathoa oculata subspecies fred"), is("Aegathoa oculata ssp. fred")); //assertThat(normalizer.normalize("Armeria 'Bees Ruby'"), is("Armeria 'Bees Ruby'")); assertThat(normalizer.normalize("Rubus fruticosus agg."), is("Rubus fruticosus agg.")); assertThat(normalizer.normalize("Limonia (Dicranomyia) chorea"), is("Limonia chorea")); assertThat(normalizer.normalize("Archips podana/operana"), is("Archips")); assertThat(normalizer.normalize("Leptochela cf bermudensis"), is("Leptochela")); assertThat(normalizer.normalize("S enflata"), is("Sagitta enflata")); assertThat(normalizer.normalize("Aneugmenus fürstenbergensis"), is("Aneugmenus fuerstenbergensis")); assertThat(normalizer.normalize("Xanthorhoë"), is("Xanthorhoe")); // Malcolm Storey technique to distinguish duplicate genus names in taxonomies. assertThat(normalizer.normalize("Ammophila (Bot.)"), is("Ammophila (Bot.)")); assertThat(normalizer.normalize("Ammophila (Zool.)"), is("Ammophila (Zool.)")); assertThat(normalizer.normalize("Ammophila (zoo)"), is("Ammophila (zoo)")); assertThat(normalizer.normalize("Ammophila (bot)"), is("Ammophila (bot)")); assertThat(normalizer.normalize("Ammophila (bot.)"), is("Ammophila (bot.)")); assertThat(normalizer.normalize("Ammophila (Bot)"), is("Ammophila (Bot)")); assertThat(normalizer.normalize("Ammophila (blah)"), is("Ammophila")); assertThat(normalizer.normalize("Cal sapidus"), is("Callinectes sapidus")); assertThat(normalizer.normalize("Bivalvia Genus A"), is("Bivalvia")); }
diff --git a/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/repositories/AllRepositoryListPlexusResource.java b/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/repositories/AllRepositoryListPlexusResource.java index 42272dbc6..77a0a7701 100644 --- a/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/repositories/AllRepositoryListPlexusResource.java +++ b/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/repositories/AllRepositoryListPlexusResource.java @@ -1,79 +1,79 @@ /** * Sonatype Nexus (TM) Open Source Version. * Copyright (c) 2008 Sonatype, Inc. All rights reserved. * Includes the third-party code listed at http://nexus.sonatype.org/dev/attributions.html * This program is licensed to you under Version 3 only of the GNU General Public License 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 Version 3 for more details. * You should have received a copy of the GNU General Public License Version 3 along with this program. * If not, see http://www.gnu.org/licenses/. * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. * "Sonatype" and "Sonatype Nexus" are trademarks of Sonatype, Inc. */ package org.sonatype.nexus.rest.repositories; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.codehaus.enunciate.contract.jaxrs.ResourceMethodSignature; import org.codehaus.plexus.component.annotations.Component; import org.restlet.Context; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.resource.ResourceException; import org.restlet.resource.Variant; import org.sonatype.nexus.rest.model.RepositoryListResourceResponse; import org.sonatype.plexus.rest.resource.PathProtectionDescriptor; import org.sonatype.plexus.rest.resource.PlexusResource; /** * A resource list for Repository list. * * @author cstamas */ @Component( role = PlexusResource.class, hint = "AllRepositoryListPlexusResource" ) @Path( AllRepositoryListPlexusResource.RESOURCE_URI ) @Produces( { "application/xml", "application/json" } ) public class AllRepositoryListPlexusResource extends AbstractRepositoryPlexusResource { public static final String RESOURCE_URI = "/all_repositories"; public AllRepositoryListPlexusResource() { this.setModifiable( false ); } @Override public Object getPayloadInstance() { return null; } @Override public String getResourceUri() { return RESOURCE_URI; } @Override public PathProtectionDescriptor getResourceProtection() { return new PathProtectionDescriptor( getResourceUri(), "authcBasic,perms[nexus:repositories]" ); } /** * Retrieve the list of all repositories in nexus, regardless if user or nexus managed. */ @Override @GET @ResourceMethodSignature( output = RepositoryListResourceResponse.class ) public Object get( Context context, Request request, Response response, Variant variant ) throws ResourceException { - return listRepositories( request, true, false ); + return listRepositories( request, true, true ); } }
true
true
public Object get( Context context, Request request, Response response, Variant variant ) throws ResourceException { return listRepositories( request, true, false ); }
public Object get( Context context, Request request, Response response, Variant variant ) throws ResourceException { return listRepositories( request, true, true ); }
diff --git a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java index 5ff092261..1d377ac64 100644 --- a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java +++ b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java @@ -1,164 +1,165 @@ /******************************************************************************* * Copyright (c) 2000, 2002 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM - Initial API and implementation ******************************************************************************/ package org.eclipse.core.internal.resources; import org.eclipse.core.internal.localstore.CoreFileSystemLibrary; import org.eclipse.core.internal.utils.Policy; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; public class Folder extends Container implements IFolder { protected Folder(IPath path, Workspace container) { super(path, container); } protected void assertCreateRequirements(IPath location, int updateFlags) throws CoreException { checkDoesNotExist(); Container parent = (Container) getParent(); ResourceInfo info = parent.getResourceInfo(false, false); parent.checkAccessible(getFlags(info)); if (location == null) { String message = Policy.bind("localstore.locationUndefined", getFullPath().toString()); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.FAILED_WRITE_LOCAL, getFullPath(), message, null); } java.io.File localFile = location.toFile(); final boolean force = (updateFlags & IResource.FORCE) != 0; if (!force && localFile.exists()) { //return an appropriate error message for case variant collisions if (!CoreFileSystemLibrary.isCaseSensitive()) { String name = getLocalManager().getLocalName(localFile); if (name != null && !localFile.getName().equals(name)) { String msg = Policy.bind("resources.existsLocalDifferentCase", location.removeLastSegments(1).append(name).toOSString()); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.CASE_VARIANT_EXISTS, getFullPath(), msg, null); } } String msg = Policy.bind("resources.fileExists", localFile.getAbsolutePath()); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.FAILED_WRITE_LOCAL, getFullPath(), msg, null); } } /** * Changes this folder to be a file in the resource tree and returns * the newly created file. All related * properties are deleted. It is assumed that on disk the resource is * already a file so no action is taken to delete the disk contents. * <p> * <b>This method is for the exclusive use of the local resource manager</b> * * @see FileSystemResourceManager#reportChanges */ public IFile changeToFile() throws CoreException { getPropertyManager().deleteProperties(this, IResource.DEPTH_INFINITE); workspace.deleteResource(this); IFile result = workspace.getRoot().getFile(path); workspace.createResource(result, false); return result; } /* * @see IFolder */ public void create(int updateFlags, boolean local, IProgressMonitor monitor) throws CoreException { final boolean force = (updateFlags & IResource.FORCE) != 0; monitor = Policy.monitorFor(monitor); try { String message = Policy.bind("resources.creating", getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); checkValidPath(path, FOLDER); try { workspace.prepareOperation(); IPath location = getLocalManager().locationFor(this); assertCreateRequirements(location, updateFlags); workspace.beginOperation(true); java.io.File localFile = location.toFile(); if (force && !CoreFileSystemLibrary.isCaseSensitive() && localFile.exists()) { String name = getLocalManager().getLocalName(localFile); if (name == null || localFile.getName().equals(name)) { delete(true, null); } else { // The file system is not case sensitive and a case variant exists at this location String msg = Policy.bind("resources.existsLocalDifferentCase", location.removeLastSegments(1).append(name).toOSString()); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.CASE_VARIANT_EXISTS, getFullPath(), msg, null); } } internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.opWork)); + workspace.getAliasManager().updateAliases(this, getLocation(), IResource.DEPTH_ZERO, monitor); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } } /** * @see IFolder */ public void create(boolean force, boolean local, IProgressMonitor monitor) throws CoreException { // funnel all operations to central method create((force ? IResource.FORCE : IResource.NONE), local, monitor); } /** * Ensures that this folder exists in the workspace. This is similar in * concept to mkdirs but it does not work on projects. * If this folder is created, it will be marked as being local. */ public void ensureExists(IProgressMonitor monitor) throws CoreException { ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); if (exists(flags, true)) return; if (exists(flags, false)) { String message = Policy.bind("resources.folderOverFile", getFullPath().toString()); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.RESOURCE_WRONG_TYPE, getFullPath(), message, null); } Container parent = (Container) getParent(); if (parent.getType() == PROJECT) { info = parent.getResourceInfo(false, false); parent.checkExists(getFlags(info), true); } else ((Folder) parent).ensureExists(monitor); internalCreate(true, true, monitor); } /** * @see IResource#getType */ public int getType() { return FOLDER; } public void internalCreate(boolean force, boolean local, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { String message = Policy.bind("resources.creating", getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); workspace.createResource(this, false); if (local) { try { getLocalManager().write(this, force, Policy.subMonitorFor(monitor, Policy.totalWork * 75 / 100)); } catch (CoreException e) { // a problem happened creating the folder on disk, so delete from the workspace workspace.deleteResource(this); throw e; // rethrow } } setLocal(local, DEPTH_ZERO, Policy.subMonitorFor(monitor, Policy.totalWork * 25 / 100)); if (!local) getResourceInfo(true, true).setModificationStamp(IResource.NULL_STAMP); } finally { monitor.done(); } } }
true
true
public void create(int updateFlags, boolean local, IProgressMonitor monitor) throws CoreException { final boolean force = (updateFlags & IResource.FORCE) != 0; monitor = Policy.monitorFor(monitor); try { String message = Policy.bind("resources.creating", getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); checkValidPath(path, FOLDER); try { workspace.prepareOperation(); IPath location = getLocalManager().locationFor(this); assertCreateRequirements(location, updateFlags); workspace.beginOperation(true); java.io.File localFile = location.toFile(); if (force && !CoreFileSystemLibrary.isCaseSensitive() && localFile.exists()) { String name = getLocalManager().getLocalName(localFile); if (name == null || localFile.getName().equals(name)) { delete(true, null); } else { // The file system is not case sensitive and a case variant exists at this location String msg = Policy.bind("resources.existsLocalDifferentCase", location.removeLastSegments(1).append(name).toOSString()); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.CASE_VARIANT_EXISTS, getFullPath(), msg, null); } } internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.opWork)); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } }
public void create(int updateFlags, boolean local, IProgressMonitor monitor) throws CoreException { final boolean force = (updateFlags & IResource.FORCE) != 0; monitor = Policy.monitorFor(monitor); try { String message = Policy.bind("resources.creating", getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); checkValidPath(path, FOLDER); try { workspace.prepareOperation(); IPath location = getLocalManager().locationFor(this); assertCreateRequirements(location, updateFlags); workspace.beginOperation(true); java.io.File localFile = location.toFile(); if (force && !CoreFileSystemLibrary.isCaseSensitive() && localFile.exists()) { String name = getLocalManager().getLocalName(localFile); if (name == null || localFile.getName().equals(name)) { delete(true, null); } else { // The file system is not case sensitive and a case variant exists at this location String msg = Policy.bind("resources.existsLocalDifferentCase", location.removeLastSegments(1).append(name).toOSString()); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.CASE_VARIANT_EXISTS, getFullPath(), msg, null); } } internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.opWork)); workspace.getAliasManager().updateAliases(this, getLocation(), IResource.DEPTH_ZERO, monitor); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } }
diff --git a/src/BindTest.java b/src/BindTest.java index d263814..4727927 100644 --- a/src/BindTest.java +++ b/src/BindTest.java @@ -1,42 +1,39 @@ import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.io.IOException; import java.lang.Integer; import java.lang.ArrayIndexOutOfBoundsException; public class BindTest { public static void main(String[] args) { try{ Integer port = Integer.valueOf(args[0]); ServerSocket ss = null; /* workaround a macos|windows problem */ - String os = System.getProperty("os.name"); - if(os != null && os.equalsIgnoreCase("Windows")) - ss = new ServerSocket(port.intValue()); - else { - ss = new ServerSocket(); + String os = System.getProperty("os.name").toLowerCase(); + ss = new ServerSocket(); + if(os.startsWith("mac")) ss.setReuseAddress(false); - ss.bind(new InetSocketAddress("127.0.0.1:", port.intValue())); - if(!ss.isBound()) - System.exit(1); - } + ss.bind(new InetSocketAddress("127.0.0.1:", port.intValue())); + if(!ss.isBound()) + System.exit(1); ss.setSoTimeout(200); ss.accept(); }catch (SocketTimeoutException ste){ }catch (SocketException e){ System.exit(1); }catch (IOException io){ System.exit(2); }catch (ArrayIndexOutOfBoundsException aioobe){ System.err.println("Please give a port number as the first parameter!"); System.exit(-1); } System.exit(0); } }
false
true
public static void main(String[] args) { try{ Integer port = Integer.valueOf(args[0]); ServerSocket ss = null; /* workaround a macos|windows problem */ String os = System.getProperty("os.name"); if(os != null && os.equalsIgnoreCase("Windows")) ss = new ServerSocket(port.intValue()); else { ss = new ServerSocket(); ss.setReuseAddress(false); ss.bind(new InetSocketAddress("127.0.0.1:", port.intValue())); if(!ss.isBound()) System.exit(1); } ss.setSoTimeout(200); ss.accept(); }catch (SocketTimeoutException ste){ }catch (SocketException e){ System.exit(1); }catch (IOException io){ System.exit(2); }catch (ArrayIndexOutOfBoundsException aioobe){ System.err.println("Please give a port number as the first parameter!"); System.exit(-1); } System.exit(0); }
public static void main(String[] args) { try{ Integer port = Integer.valueOf(args[0]); ServerSocket ss = null; /* workaround a macos|windows problem */ String os = System.getProperty("os.name").toLowerCase(); ss = new ServerSocket(); if(os.startsWith("mac")) ss.setReuseAddress(false); ss.bind(new InetSocketAddress("127.0.0.1:", port.intValue())); if(!ss.isBound()) System.exit(1); ss.setSoTimeout(200); ss.accept(); }catch (SocketTimeoutException ste){ }catch (SocketException e){ System.exit(1); }catch (IOException io){ System.exit(2); }catch (ArrayIndexOutOfBoundsException aioobe){ System.err.println("Please give a port number as the first parameter!"); System.exit(-1); } System.exit(0); }
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/CallableBuilder.java b/src/com/redhat/ceylon/compiler/java/codegen/CallableBuilder.java index 10093e779..c045827ac 100644 --- a/src/com/redhat/ceylon/compiler/java/codegen/CallableBuilder.java +++ b/src/com/redhat/ceylon/compiler/java/codegen/CallableBuilder.java @@ -1,608 +1,612 @@ /* * 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.java.codegen; import static com.redhat.ceylon.compiler.java.codegen.AbstractTransformer.JT_CLASS_NEW; import static com.redhat.ceylon.compiler.java.codegen.AbstractTransformer.JT_EXTENDS; import static com.redhat.ceylon.compiler.java.codegen.AbstractTransformer.JT_NO_PRIMITIVES; import java.util.ArrayList; import com.redhat.ceylon.compiler.java.codegen.AbstractTransformer.BoxingStrategy; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.FunctionalParameter; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedReference; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; 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.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCNewClass; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; public class CallableBuilder { static interface DefaultValueMethodTransformation { public JCExpression makeDefaultValueMethod(AbstractTransformer gen, Parameter defaultedParam, Tree.Term forwardCallTo); } public static final DefaultValueMethodTransformation DEFAULTED_PARAM_METHOD = new DefaultValueMethodTransformation() { @Override public JCExpression makeDefaultValueMethod(AbstractTransformer gen, Parameter defaultedParam, Tree.Term forwardCallTo) { if (forwardCallTo != null) { if (forwardCallTo instanceof Tree.BaseMemberOrTypeExpression) { return gen.makeUnquotedIdent( Naming.getDefaultedParamMethodName((Declaration)defaultedParam.getScope(), defaultedParam)); } else if (forwardCallTo instanceof Tree.QualifiedMemberOrTypeExpression) { return gen.makeQualIdent( gen.expressionGen().transformPrimary(((Tree.QualifiedMemberOrTypeExpression)forwardCallTo).getPrimary(), null), Naming.getDefaultedParamMethodName((Declaration)defaultedParam.getScope(), defaultedParam)); } } return gen.makeUnquotedIdent(Naming.getDefaultedParamMethodName(null, defaultedParam)); } }; DefaultValueMethodTransformation defaultValueCall = DEFAULTED_PARAM_METHOD; private final AbstractTransformer gen; private final ProducedType typeModel; private final ParameterList paramLists; private boolean noDelegates; private int numParams; private int minimumParams; private boolean isVariadic; private boolean hasOptionalParameters; private java.util.List<ProducedType> parameterTypes; private CallableBuilder(CeylonTransformer gen, ProducedType typeModel, ParameterList paramLists) { this.gen = gen; this.typeModel = typeModel; this.paramLists = paramLists; this.numParams = paramLists.getParameters().size(); this.minimumParams = 0; for(Parameter p : paramLists.getParameters()){ if(p.isDefaulted() || p.isSequenced()) break; this.minimumParams++; } this.isVariadic = numParams > 0 && paramLists.getParameters().get(numParams-1).isSequenced(); this.hasOptionalParameters = minimumParams != numParams; } /** * Constructs an {@code AbstractCallable} suitable for wrapping a method reference. */ public static CallableBuilder methodReference(CeylonTransformer gen, Tree.Term expr, ParameterList parameterList) { CallableBuilder cb = new CallableBuilder(gen, expr.getTypeModel(), parameterList); cb.parameterTypes = cb.getParameterTypesFromCallableModel(); cb.forwardTo(expr); return cb; } /** * Used for "static" method or class references like * value x = Integer.plus; * value y = Foo.method; * value z = Outer.Inner; */ public static CallableBuilder unboundFunctionalMemberReference(CeylonTransformer gen, ProducedType typeModel, final Functional methodOrClass, ProducedReference producedReference) { final String instanceName = "$instance"; final ParameterList parameterList = methodOrClass.getParameterLists().get(0); final ProducedType type = gen.getReturnTypeOfCallable(typeModel); CallableBuilder inner = new CallableBuilder(gen, type, parameterList); inner.parameterTypes = inner.getParameterTypesFromCallableModel();//FromParameterModels(); class InstanceDefaultValueCall implements DefaultValueMethodTransformation { @Override public JCExpression makeDefaultValueMethod(AbstractTransformer gen, Parameter defaultedParam, Tree.Term forwardCallTo) { return gen.makeQualIdent(gen.naming.makeUnquotedIdent(instanceName), Naming.getDefaultedParamMethodName((Declaration)methodOrClass, defaultedParam)); } } inner.defaultValueCall = new InstanceDefaultValueCall(); CallBuilder callBuilder = CallBuilder.instance(gen); if (methodOrClass instanceof Method) { callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), (Method)methodOrClass, Naming.NA_MEMBER)); } else if (methodOrClass instanceof FunctionalParameter) { callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), (FunctionalParameter)methodOrClass, Naming.NA_MEMBER)); } else if (methodOrClass instanceof Class) { if (Strategy.generateInstantiator((Class)methodOrClass)) { callBuilder.invoke(gen.naming.makeInstantiatorMethodName(gen.naming.makeUnquotedIdent(instanceName), (Class)methodOrClass)); } else { callBuilder.instantiate(new ExpressionAndType(gen.naming.makeUnquotedIdent(instanceName), null), gen.makeJavaType(((Class)methodOrClass).getType(), JT_CLASS_NEW)); } } else { Assert.fail("Unhandled functional type " + methodOrClass.getClass().getSimpleName()); } ListBuffer<ExpressionAndType> reified = ListBuffer.lb(); DirectInvocation.addReifiedArguments(gen, producedReference, reified); for (ExpressionAndType reifiedArgument : reified) { callBuilder.argument(reifiedArgument.expression); } for (Parameter parameter : parameterList.getParameters()) { callBuilder.argument(gen.naming.makeQuotedIdent(parameter.getName())); } JCExpression innerInvocation = callBuilder.build(); - if (methodOrClass instanceof Method) { - innerInvocation = gen.expressionGen().applyErasureAndBoxing(innerInvocation, methodOrClass.getType(), !((Method)methodOrClass).getUnboxed(), BoxingStrategy.BOXED, methodOrClass.getType()); + // Need to worry about boxing for Method and FunctionalParameter + if (methodOrClass instanceof TypedDeclaration) { + innerInvocation = gen.expressionGen().applyErasureAndBoxing(innerInvocation, + methodOrClass.getType(), + !CodegenUtil.isUnBoxed((TypedDeclaration)methodOrClass), + BoxingStrategy.BOXED, methodOrClass.getType()); } inner.useBody(List.<JCStatement>of(gen.make().Return(innerInvocation))); ParameterList outerPl = new ParameterList(); ValueParameter instanceParameter = new ValueParameter(); instanceParameter.setName(instanceName); instanceParameter.setType(gen.getParameterTypeOfCallable(typeModel, 0)); instanceParameter.setUnboxed(false); outerPl.getParameters().add(instanceParameter); CallableBuilder outer = new CallableBuilder(gen, typeModel, outerPl); outer.parameterTypes = outer.getParameterTypesFromParameterModels(); outer.useBody(List.<JCStatement>of(gen.make().Return(inner.build()))); return outer; } /** * Used for "static" value references like * value x = Integer.plus; * value y = Foo.method; * value z = Outer.Inner; */ public static CallableBuilder unboundValueMemberReference(CeylonTransformer gen, ProducedType typeModel, final TypedDeclaration value) { final String instanceName = "$instance"; CallBuilder callBuilder = CallBuilder.instance(gen); callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), value, Naming.NA_GETTER | Naming.NA_MEMBER)); JCExpression innerInvocation = callBuilder.build(); innerInvocation = gen.expressionGen().applyErasureAndBoxing(innerInvocation, value.getType(), !value.getUnboxed(), BoxingStrategy.BOXED, value.getType()); ParameterList outerPl = new ParameterList(); ValueParameter instanceParameter = new ValueParameter(); instanceParameter.setName(instanceName); instanceParameter.setType(gen.getParameterTypeOfCallable(typeModel, 0)); instanceParameter.setUnboxed(false); outerPl.getParameters().add(instanceParameter); CallableBuilder outer = new CallableBuilder(gen, typeModel, outerPl); outer.parameterTypes = outer.getParameterTypesFromParameterModels(); outer.useBody(List.<JCStatement>of(gen.make().Return(innerInvocation))); return outer; } /** * Constructs an {@code AbstractCallable} suitable for an anonymous function. */ public static CallableBuilder anonymous( CeylonTransformer gen, Tree.Expression expr, ParameterList parameterList, Tree.ParameterList parameterListTree, ProducedType callableTypeModel, boolean noDelegates) { JCExpression transformedExpr = gen.expressionGen().transformExpression(expr, BoxingStrategy.BOXED, gen.getReturnTypeOfCallable(callableTypeModel)); final List<JCStatement> stmts = List.<JCStatement>of(gen.make().Return(transformedExpr)); return methodArgument(gen, callableTypeModel, parameterList, parameterListTree, stmts, noDelegates); } public static CallableBuilder methodArgument( CeylonTransformer gen, ProducedType callableTypeModel, ParameterList parameterList, Tree.ParameterList parameterListTree, List<JCStatement> stmts) { return methodArgument(gen, callableTypeModel, parameterList, parameterListTree, stmts, false); } public static CallableBuilder methodArgument( CeylonTransformer gen, ProducedType callableTypeModel, ParameterList parameterList, Tree.ParameterList parameterListTree, List<JCStatement> stmts, boolean noDelegates) { CallableBuilder cb = new CallableBuilder(gen, callableTypeModel, parameterList); cb.parameterTypes = cb.getParameterTypesFromParameterModels(); cb.parameterDefaultValueMethods(parameterListTree); cb.noDelegates = noDelegates; cb.useBody(stmts); return cb; } /** * Constructs an {@code AbstractCallable} suitable for use in a method * definition with a multiple parameter list. */ public static CallableBuilder mpl( CeylonTransformer gen, ProducedType typeModel, ParameterList parameterList, Tree.ParameterList parameterListTree, List<JCStatement> body) { CallableBuilder cb = new CallableBuilder(gen, typeModel, parameterList); if (body == null) { body = List.<JCStatement>nil(); } cb.parameterTypes = cb.getParameterTypesFromParameterModels(); cb.parameterDefaultValueMethods(parameterListTree); cb.useBody(body); return cb; } private ListBuffer<JCTree> parameterDefaultValueMethods; private ListBuffer<JCTree> callMethods = new ListBuffer<JCTree>(); public CallableBuilder forwardTo(Tree.Term forwardCallTo) { if (forwardCallTo == null) { throw new RuntimeException(); } // now generate a method for each supported minimum number of parameters below 4 // which delegates to the $call$typed method if required for(int i=minimumParams,max = Math.min(numParams,4);i<max;i++){ ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>(); makeDefaultedCall(i, stmts, forwardCallTo); makeForwardedInvocation(i, stmts, forwardCallTo); callMethods.append(makeCallMethod(stmts.toList(), i)); } // generate the $call method for the max number of parameters, // which delegates to the $call$typed method if required ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>(); makeDefaultedCall(numParams, stmts, forwardCallTo); makeForwardedInvocation(numParams, stmts, forwardCallTo); callMethods.append(makeCallMethod(stmts.toList(), numParams)); return this; } public CallableBuilder useBody(List<JCStatement> body) { if (!noDelegates) { // now generate a method for each supported minimum number of parameters below 4 // which delegates to the $call$typed method if required for(int i=minimumParams,max = Math.min(numParams,4);i<max;i++){ ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>(); makeDefaultedCall(i, stmts, null); makeCallTypedCallOrBody(i, stmts, body); callMethods.append(makeCallMethod(stmts.toList(), i)); } } // generate the $call method for the max number of parameters, // which delegates to the $call$typed method if required ListBuffer<JCStatement> stmts = new ListBuffer<JCStatement>(); makeDefaultedCall(numParams, stmts, null); makeCallTypedCallOrBody(numParams, stmts, body); callMethods.append(makeCallMethod(stmts.toList(), numParams)); // generate the $call$typed method if required if(hasOptionalParameters) callMethods.append(makeCallTypedMethod(body)); return this; } public CallableBuilder parameterDefaultValueMethods(Tree.ParameterList parameterListTree) { if (parameterDefaultValueMethods == null) { parameterDefaultValueMethods = ListBuffer.lb(); } for(Tree.Parameter p : parameterListTree.getParameters()){ if(p.getDefaultArgument() != null || p.getDeclarationModel().isSequenced()){ MethodDefinitionBuilder methodBuilder = gen.classGen().makeParamDefaultValueMethod(false, null, parameterListTree, p, null); this.parameterDefaultValueMethods.append(methodBuilder.build()); } } return this; } public JCNewClass build() { // Generate a subclass of Callable ListBuffer<JCTree> classBody = new ListBuffer<JCTree>(); if (parameterDefaultValueMethods != null) { classBody.appendList(parameterDefaultValueMethods); } classBody.appendList(callMethods); JCClassDecl classDef = gen.make().AnonymousClassDef(gen.make().Modifiers(0), classBody.toList()); int variadicIndex = isVariadic ? numParams - 1 : -1; JCNewClass instance = gen.make().NewClass(null, null, gen.makeJavaType(typeModel, JT_EXTENDS | JT_CLASS_NEW), List.<JCExpression>of(gen.makeReifiedTypeArgument(typeModel.getTypeArgumentList().get(0)), gen.makeReifiedTypeArgument(typeModel.getTypeArgumentList().get(1)), gen.make().Literal(typeModel.getProducedTypeName(true)), gen.make().TypeCast(gen.syms().shortType, gen.makeInteger(variadicIndex))), classDef); return instance; } private java.util.List<ProducedType> getParameterTypesFromCallableModel() { java.util.List<ProducedType> parameterTypes = new ArrayList<ProducedType>(numParams); for(int i=0;i<numParams;i++) { parameterTypes.add(gen.getParameterTypeOfCallable(typeModel, i)); } return parameterTypes; } private java.util.List<ProducedType> getParameterTypesFromParameterModels() { java.util.List<ProducedType> parameterTypes = new ArrayList<ProducedType>(numParams); // get them from our declaration for(Parameter p : paramLists.getParameters()){ ProducedType pt; if(p instanceof FunctionalParameter) pt = gen.getTypeForFunctionalParameter((FunctionalParameter) p); else pt = p.getType(); parameterTypes.add(pt); } return parameterTypes; } private JCExpression getTypedParameter(Parameter param, int argIndex, boolean varargs){ JCExpression argExpr; if (!varargs) { // The Callable has overridden one of the non-varargs call() // methods argExpr = gen.make().Ident( makeParamName(gen, argIndex)); } else { // The Callable has overridden the varargs call() method // so we need to index into the varargs array argExpr = gen.make().Indexed( gen.make().Ident(makeParamName(gen, 0)), gen.make().Literal(argIndex)); } // make sure we unbox it if required argExpr = gen.expressionGen().applyErasureAndBoxing(argExpr, parameterTypes.get(argIndex), // it came in as Object, but we need to pretend its type // is the parameter type because that's how unboxing determines how it has to unbox true, // it's completely erased true, // it came in boxed CodegenUtil.getBoxingStrategy(param), // see if we need to box parameterTypes.get(argIndex), // see what type we need ExpressionTransformer.EXPR_DOWN_CAST); // we're effectively downcasting it from Object return argExpr; } private void makeDefaultedCall(final int i, ListBuffer<JCStatement> stmts, Tree.Term forwardCallTo) { // collect every parameter int a = 0; for(Parameter param : paramLists.getParameters()){ // don't read default parameter values for forwarded calls if(forwardCallTo != null && i == a) break; stmts.append(makeArgumentVar(param, a, i, forwardCallTo)); a++; } } private void makeCallTypedCallOrBody(final int i, ListBuffer<JCStatement> stmts, List<JCStatement> body) { if(hasOptionalParameters){ // chain to n param typed method List<JCExpression> args = List.nil(); // pass along the parameters for(int a=paramLists.getParameters().size()-1;a>=0;a--){ Parameter param = paramLists.getParameters().get(a); args = args.prepend(gen.makeUnquotedIdent(getCallableTempVarName(param, null))); } JCMethodInvocation chain = gen.make().Apply(null, gen.makeUnquotedIdent(Naming.getCallableTypedMethodName()), args); stmts.append(gen.make().Return(chain)); }else{ // insert the method body directly stmts.appendList(body); } return; } /** * <p>Makes a variable declaration for variable which will be used as an * argument to a call. The variable is initialized to either the * corresponding parameter,</p> * <pre> * Foo foo = (Foo)arg0; * </pre> * <p>or the default value for the corresponding parameter</p> * <pre> * Bar bar = $$bar(**previous-args**); * </pre> */ private JCVariableDecl makeArgumentVar(final Parameter param, final int a, final int i, Tree.Term forwardCallTo) { // read the value JCExpression paramExpression = getTypedParameter(param, a, i>3); JCExpression varInitialExpression; if(param.isDefaulted() || param.isSequenced()){ if(i > 3){ // must check if it's defined JCExpression test = gen.make().Binary(JCTree.GT, gen.makeSelect(getParamName(0), "length"), gen.makeInteger(a)); JCExpression elseBranch = makeDefaultValueCall(param, a, forwardCallTo); varInitialExpression = gen.make().Conditional(test, paramExpression, elseBranch); }else if(a >= i){ // get its default value because we don't have it varInitialExpression = makeDefaultValueCall(param, a, forwardCallTo); }else{ // we must have it varInitialExpression = paramExpression; } }else{ varInitialExpression = paramExpression; } // store it in a local var int flags = 0; if(!CodegenUtil.isUnBoxed(param)){ flags |= AbstractTransformer.JT_NO_PRIMITIVES; } // Always go raw if we're forwarding, because we're building the call ourselves and we don't get a chance to apply erasure and // casting to parameter expressions when we pass them to the forwarded method. Ideally we could set it up correctly so that // the proper erasure is done when we read from the Callable.call Object param, but since we store it in a variable defined here, // we'd need to duplicate some of the erasure logic here to make or not the type raw, and that would be worse. // Besides, named parameter invocation does the same. // See https://github.com/ceylon/ceylon-compiler/issues/1005 if(forwardCallTo != null) flags |= AbstractTransformer.JT_RAW; JCVariableDecl var = gen.make().VarDef(gen.make().Modifiers(Flags.FINAL), gen.naming.makeUnquotedName(getCallableTempVarName(param, forwardCallTo)), gen.makeJavaType(parameterTypes.get(a), flags), varInitialExpression); return var; } private void makeForwardedInvocation(int i, ListBuffer<JCStatement> stmts, Tree.Term forwardCallTo) { final Tree.MemberOrTypeExpression primary; if (forwardCallTo instanceof Tree.MemberOrTypeExpression) { primary = (Tree.MemberOrTypeExpression)forwardCallTo; } else { throw new RuntimeException(forwardCallTo.getNodeType()); } TypeDeclaration primaryDeclaration = forwardCallTo.getTypeModel().getDeclaration(); CallableInvocation invocationBuilder = new CallableInvocation ( gen, primary, primaryDeclaration, primary.getTarget(), gen.getReturnTypeOfCallable(forwardCallTo.getTypeModel()), forwardCallTo, paramLists, i); boolean prevCallableInv = gen.expressionGen().withinSyntheticClassBody(true); JCExpression invocation; try { invocation = gen.expressionGen().transformInvocation(invocationBuilder); } finally { gen.expressionGen().withinSyntheticClassBody(prevCallableInv); } stmts.append(gen.make().Return(invocation)); } private String getCallableTempVarName(Parameter param, Tree.Term forwardCallTo) { // prefix them with $$ if we only forward, otherwise we need them to have the proper names return forwardCallTo != null ? Naming.getCallableTempVarName(param) : param.getName(); } private JCExpression makeDefaultValueCall(Parameter defaultedParam, int i, Tree.Term forwardCallTo){ // add the default value List<JCExpression> defaultMethodArgs = List.nil(); // pass all the previous values for(int a=i-1;a>=0;a--){ Parameter param = paramLists.getParameters().get(a); JCExpression previousValue = gen.makeUnquotedIdent(getCallableTempVarName(param, forwardCallTo)); defaultMethodArgs = defaultMethodArgs.prepend(previousValue); } // now call the default value method return gen.make().Apply(null, defaultValueCall.makeDefaultValueMethod(gen, defaultedParam, forwardCallTo), defaultMethodArgs); } private JCTree makeCallMethod(List<JCStatement> body, int numParams) { MethodDefinitionBuilder callMethod = MethodDefinitionBuilder.callable(gen); callMethod.isOverride(true); callMethod.modifiers(Flags.PUBLIC); ProducedType returnType = gen.getReturnTypeOfCallable(typeModel); callMethod.resultType(gen.makeJavaType(returnType, JT_NO_PRIMITIVES), null); // Now append formal parameters switch (numParams) { case 3: callMethod.parameter(makeCallableCallParam(0, numParams-3)); // fall through case 2: callMethod.parameter(makeCallableCallParam(0, numParams-2)); // fall through case 1: callMethod.parameter(makeCallableCallParam(0, numParams-1)); break; case 0: break; default: // use varargs callMethod.parameter(makeCallableCallParam(Flags.VARARGS, 0)); } // Return the call result, or null if a void method callMethod.body(body); return callMethod.build(); } private JCTree makeCallTypedMethod(List<JCStatement> body) { // make the method MethodDefinitionBuilder methodBuilder = MethodDefinitionBuilder.systemMethod(gen, Naming.getCallableTypedMethodName()); methodBuilder.noAnnotations(); methodBuilder.modifiers(Flags.PRIVATE); ProducedType returnType = gen.getReturnTypeOfCallable(typeModel); methodBuilder.resultType(gen.makeJavaType(returnType, JT_NO_PRIMITIVES), null); // add all parameters int i=0; for(Parameter param : paramLists.getParameters()){ ParameterDefinitionBuilder parameterBuilder = ParameterDefinitionBuilder.instance(gen, param.getName()); JCExpression paramType = gen.makeJavaType(parameterTypes.get(i)); parameterBuilder.type(paramType, null); methodBuilder.parameter(parameterBuilder); i++; } // Return the call result, or null if a void method methodBuilder.body(body); return methodBuilder.build(); } private static Name makeParamName(AbstractTransformer gen, int paramIndex) { return gen.names().fromString(getParamName(paramIndex)); } private static String getParamName(int paramIndex) { return "$param$"+paramIndex; } private ParameterDefinitionBuilder makeCallableCallParam(long flags, int ii) { JCExpression type = gen.makeIdent(gen.syms().objectType); if ((flags & Flags.VARARGS) != 0) { type = gen.make().TypeArray(type); } ParameterDefinitionBuilder pdb = ParameterDefinitionBuilder.instance(gen, getParamName(ii)); pdb.modifiers(Flags.FINAL | flags); pdb.type(type, null); return pdb; /* return gen.make().VarDef(gen.make().Modifiers(Flags.FINAL | Flags.PARAMETER | flags), makeParamName(gen, ii), type, null); */ } }
true
true
public static CallableBuilder unboundFunctionalMemberReference(CeylonTransformer gen, ProducedType typeModel, final Functional methodOrClass, ProducedReference producedReference) { final String instanceName = "$instance"; final ParameterList parameterList = methodOrClass.getParameterLists().get(0); final ProducedType type = gen.getReturnTypeOfCallable(typeModel); CallableBuilder inner = new CallableBuilder(gen, type, parameterList); inner.parameterTypes = inner.getParameterTypesFromCallableModel();//FromParameterModels(); class InstanceDefaultValueCall implements DefaultValueMethodTransformation { @Override public JCExpression makeDefaultValueMethod(AbstractTransformer gen, Parameter defaultedParam, Tree.Term forwardCallTo) { return gen.makeQualIdent(gen.naming.makeUnquotedIdent(instanceName), Naming.getDefaultedParamMethodName((Declaration)methodOrClass, defaultedParam)); } } inner.defaultValueCall = new InstanceDefaultValueCall(); CallBuilder callBuilder = CallBuilder.instance(gen); if (methodOrClass instanceof Method) { callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), (Method)methodOrClass, Naming.NA_MEMBER)); } else if (methodOrClass instanceof FunctionalParameter) { callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), (FunctionalParameter)methodOrClass, Naming.NA_MEMBER)); } else if (methodOrClass instanceof Class) { if (Strategy.generateInstantiator((Class)methodOrClass)) { callBuilder.invoke(gen.naming.makeInstantiatorMethodName(gen.naming.makeUnquotedIdent(instanceName), (Class)methodOrClass)); } else { callBuilder.instantiate(new ExpressionAndType(gen.naming.makeUnquotedIdent(instanceName), null), gen.makeJavaType(((Class)methodOrClass).getType(), JT_CLASS_NEW)); } } else { Assert.fail("Unhandled functional type " + methodOrClass.getClass().getSimpleName()); } ListBuffer<ExpressionAndType> reified = ListBuffer.lb(); DirectInvocation.addReifiedArguments(gen, producedReference, reified); for (ExpressionAndType reifiedArgument : reified) { callBuilder.argument(reifiedArgument.expression); } for (Parameter parameter : parameterList.getParameters()) { callBuilder.argument(gen.naming.makeQuotedIdent(parameter.getName())); } JCExpression innerInvocation = callBuilder.build(); if (methodOrClass instanceof Method) { innerInvocation = gen.expressionGen().applyErasureAndBoxing(innerInvocation, methodOrClass.getType(), !((Method)methodOrClass).getUnboxed(), BoxingStrategy.BOXED, methodOrClass.getType()); } inner.useBody(List.<JCStatement>of(gen.make().Return(innerInvocation))); ParameterList outerPl = new ParameterList(); ValueParameter instanceParameter = new ValueParameter(); instanceParameter.setName(instanceName); instanceParameter.setType(gen.getParameterTypeOfCallable(typeModel, 0)); instanceParameter.setUnboxed(false); outerPl.getParameters().add(instanceParameter); CallableBuilder outer = new CallableBuilder(gen, typeModel, outerPl); outer.parameterTypes = outer.getParameterTypesFromParameterModels(); outer.useBody(List.<JCStatement>of(gen.make().Return(inner.build()))); return outer; }
public static CallableBuilder unboundFunctionalMemberReference(CeylonTransformer gen, ProducedType typeModel, final Functional methodOrClass, ProducedReference producedReference) { final String instanceName = "$instance"; final ParameterList parameterList = methodOrClass.getParameterLists().get(0); final ProducedType type = gen.getReturnTypeOfCallable(typeModel); CallableBuilder inner = new CallableBuilder(gen, type, parameterList); inner.parameterTypes = inner.getParameterTypesFromCallableModel();//FromParameterModels(); class InstanceDefaultValueCall implements DefaultValueMethodTransformation { @Override public JCExpression makeDefaultValueMethod(AbstractTransformer gen, Parameter defaultedParam, Tree.Term forwardCallTo) { return gen.makeQualIdent(gen.naming.makeUnquotedIdent(instanceName), Naming.getDefaultedParamMethodName((Declaration)methodOrClass, defaultedParam)); } } inner.defaultValueCall = new InstanceDefaultValueCall(); CallBuilder callBuilder = CallBuilder.instance(gen); if (methodOrClass instanceof Method) { callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), (Method)methodOrClass, Naming.NA_MEMBER)); } else if (methodOrClass instanceof FunctionalParameter) { callBuilder.invoke(gen.naming.makeQualifiedName(gen.naming.makeUnquotedIdent(instanceName), (FunctionalParameter)methodOrClass, Naming.NA_MEMBER)); } else if (methodOrClass instanceof Class) { if (Strategy.generateInstantiator((Class)methodOrClass)) { callBuilder.invoke(gen.naming.makeInstantiatorMethodName(gen.naming.makeUnquotedIdent(instanceName), (Class)methodOrClass)); } else { callBuilder.instantiate(new ExpressionAndType(gen.naming.makeUnquotedIdent(instanceName), null), gen.makeJavaType(((Class)methodOrClass).getType(), JT_CLASS_NEW)); } } else { Assert.fail("Unhandled functional type " + methodOrClass.getClass().getSimpleName()); } ListBuffer<ExpressionAndType> reified = ListBuffer.lb(); DirectInvocation.addReifiedArguments(gen, producedReference, reified); for (ExpressionAndType reifiedArgument : reified) { callBuilder.argument(reifiedArgument.expression); } for (Parameter parameter : parameterList.getParameters()) { callBuilder.argument(gen.naming.makeQuotedIdent(parameter.getName())); } JCExpression innerInvocation = callBuilder.build(); // Need to worry about boxing for Method and FunctionalParameter if (methodOrClass instanceof TypedDeclaration) { innerInvocation = gen.expressionGen().applyErasureAndBoxing(innerInvocation, methodOrClass.getType(), !CodegenUtil.isUnBoxed((TypedDeclaration)methodOrClass), BoxingStrategy.BOXED, methodOrClass.getType()); } inner.useBody(List.<JCStatement>of(gen.make().Return(innerInvocation))); ParameterList outerPl = new ParameterList(); ValueParameter instanceParameter = new ValueParameter(); instanceParameter.setName(instanceName); instanceParameter.setType(gen.getParameterTypeOfCallable(typeModel, 0)); instanceParameter.setUnboxed(false); outerPl.getParameters().add(instanceParameter); CallableBuilder outer = new CallableBuilder(gen, typeModel, outerPl); outer.parameterTypes = outer.getParameterTypesFromParameterModels(); outer.useBody(List.<JCStatement>of(gen.make().Return(inner.build()))); return outer; }
diff --git a/src/main/java/net/pms/dlna/DLNAMediaDatabase.java b/src/main/java/net/pms/dlna/DLNAMediaDatabase.java index 0165a4929..f22dd48bd 100644 --- a/src/main/java/net/pms/dlna/DLNAMediaDatabase.java +++ b/src/main/java/net/pms/dlna/DLNAMediaDatabase.java @@ -1,763 +1,763 @@ /* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2008 A.Brochard * * 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; version 2 * of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.pms.dlna; import com.sun.jna.Platform; import java.awt.Component; import java.io.File; import java.sql.*; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import net.pms.Messages; import net.pms.PMS; import net.pms.configuration.FormatConfiguration; import net.pms.formats.v2.SubtitleType; import static org.apache.commons.lang.StringUtils.*; import org.h2.engine.Constants; import org.h2.jdbc.JdbcSQLException; import org.h2.jdbcx.JdbcConnectionPool; import org.h2.jdbcx.JdbcDataSource; import org.h2.store.fs.FileUtils; import org.h2.tools.DeleteDbFiles; import org.h2.tools.RunScript; import org.h2.tools.Script; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class provides methods for creating and maintaining the database where * media information is stored. Scanning media and interpreting the data is * intensive, so the database is used to cache scanned information to be reused * later. */ public class DLNAMediaDatabase implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(DLNAMediaDatabase.class); private String url; private String dbDir; private String dbName; public static final String NONAME = "###"; private Thread scanner; private JdbcConnectionPool cp; private int dbCount; // Database column sizes private final int SIZE_CODECV = 32; private final int SIZE_FRAMERATE = 32; private final int SIZE_ASPECT = 32; private final int SIZE_CONTAINER = 32; private final int SIZE_MODEL = 128; private final int SIZE_MUXINGMODE = 32; private final int SIZE_FRAMERATE_MODE = 16; private final int SIZE_LANG = 3; private final int SIZE_FLAVOR = 128; private final int SIZE_SAMPLEFREQ = 16; private final int SIZE_CODECA = 32; private final int SIZE_ALBUM = 255; private final int SIZE_ARTIST = 255; private final int SIZE_SONGNAME = 255; private final int SIZE_GENRE = 64; public DLNAMediaDatabase(String name) { String dir = "database"; dbName = name; File fileDir = new File(dir); boolean defaultLocation = fileDir.mkdir() || fileDir.exists(); if (defaultLocation) { // check if the database wasn't created during the installation run, with UAC activated. String to_delete = "to_delete"; File checkDir = new File(to_delete); if (checkDir.exists()) { defaultLocation = checkDir.delete(); } else { defaultLocation = checkDir.mkdir(); if (defaultLocation) { defaultLocation = checkDir.delete(); } } } if (Platform.isWindows() && !defaultLocation) { String profileDir = PMS.getConfiguration().getProfileDirectory(); url = String.format("jdbc:h2:%s\\%s/%s", profileDir, dir, dbName); fileDir = new File(profileDir, dir); } else { url = Constants.START_URL + dir + "/" + dbName; } dbDir = fileDir.getAbsolutePath(); LOGGER.debug("Using database URL: " + url); LOGGER.info("Using database located at: " + dbDir); try { Class.forName("org.h2.Driver"); } catch (ClassNotFoundException e) { LOGGER.error(null, e); } JdbcDataSource ds = new JdbcDataSource(); ds.setURL(url); ds.setUser("sa"); ds.setPassword(""); cp = JdbcConnectionPool.create(ds); } private Connection getConnection() throws SQLException { return cp.getConnection(); } public void init(boolean force) { dbCount = -1; String version = null; Connection conn = null; ResultSet rs = null; Statement stmt = null; - // Check whether the database is not severely damaged, corrupted or wrong version - boolean force_delete = false; try { conn = getConnection(); - } catch (SQLException se) { // Connection can't be established, so delete the database - force_delete = true; - } finally { - close(conn); - if (FileUtils.exists(dbDir + File.separator + dbName + ".data.db") || force_delete) { + } catch (SQLException se) { + if (FileUtils.exists(dbDir + File.separator + dbName + ".data.db") || (se.getErrorCode() == 90048)) { // Cache is corrupt or wrong version, so delete it FileUtils.deleteRecursive(dbDir, true); - if (!FileUtils.exists(dbDir)) { + if (!FileUtils.exists(dbDir)){ LOGGER.debug("The cache has been deleted because it was corrupt or had the wrong version"); } else { if (!java.awt.GraphicsEnvironment.isHeadless()) { JOptionPane.showMessageDialog( (JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())), String.format(Messages.getString("DLNAMediaDatabase.5"), dbDir), Messages.getString("Dialog.Error"), - JOptionPane.ERROR_MESSAGE - ); - } + JOptionPane.ERROR_MESSAGE); + } LOGGER.debug("Damaged cache can't be deleted. Stop the program and delete the folder \"" + dbDir + "\" manually"); + PMS.getConfiguration().setUseCache(false); + return; } + } else { + LOGGER.debug("Cache connection error: " + se.getMessage()); + PMS.getConfiguration().setUseCache(false); + return; } } try { conn = getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT count(*) FROM FILES"); if (rs.next()) { dbCount = rs.getInt(1); } rs.close(); stmt.close(); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT VALUE FROM METADATA WHERE KEY = 'VERSION'"); if (rs.next()) { version = rs.getString(1); } } catch (SQLException se) { if (se.getErrorCode() != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in following step LOGGER.error(null, se); } } finally { close(rs); close(stmt); close(conn); } boolean force_reinit = !PMS.getVersion().equals(version); // here we can force a deletion for a specific version if (force || dbCount == -1 || force_reinit) { LOGGER.debug("Database will be (re)initialized"); try { conn = getConnection(); executeUpdate(conn, "DROP TABLE FILES"); executeUpdate(conn, "DROP TABLE METADATA"); executeUpdate(conn, "DROP TABLE REGEXP_RULES"); executeUpdate(conn, "DROP TABLE AUDIOTRACKS"); executeUpdate(conn, "DROP TABLE SUBTRACKS"); } catch (SQLException se) { if (se.getErrorCode() != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in following step LOGGER.error(null, se); } } try { StringBuilder sb = new StringBuilder(); sb.append("CREATE TABLE FILES ("); sb.append(" ID INT AUTO_INCREMENT"); sb.append(", FILENAME VARCHAR2(1024) NOT NULL"); sb.append(", MODIFIED TIMESTAMP NOT NULL"); sb.append(", TYPE INT"); sb.append(", DURATION DOUBLE"); sb.append(", BITRATE INT"); sb.append(", WIDTH INT"); sb.append(", HEIGHT INT"); sb.append(", SIZE NUMERIC"); sb.append(", CODECV VARCHAR2(").append(SIZE_CODECV).append(")"); sb.append(", FRAMERATE VARCHAR2(").append(SIZE_FRAMERATE).append(")"); sb.append(", ASPECT VARCHAR2(").append(SIZE_ASPECT).append(")"); sb.append(", BITSPERPIXEL INT"); sb.append(", THUMB BINARY"); sb.append(", CONTAINER VARCHAR2(").append(SIZE_CONTAINER).append(")"); sb.append(", MODEL VARCHAR2(").append(SIZE_MODEL).append(")"); sb.append(", EXPOSURE INT"); sb.append(", ORIENTATION INT"); sb.append(", ISO INT"); sb.append(", MUXINGMODE VARCHAR2(").append(SIZE_MUXINGMODE).append(")"); sb.append(", FRAMERATEMODE VARCHAR2(").append(SIZE_FRAMERATE_MODE).append(")"); sb.append(", constraint PK1 primary key (FILENAME, MODIFIED, ID))"); executeUpdate(conn, sb.toString()); sb = new StringBuilder(); sb.append("CREATE TABLE AUDIOTRACKS ("); sb.append(" FILEID INT NOT NULL"); sb.append(", ID INT NOT NULL"); sb.append(", LANG VARCHAR2(").append(SIZE_LANG).append(")"); sb.append(", FLAVOR VARCHAR2(").append(SIZE_FLAVOR).append(")"); sb.append(", NRAUDIOCHANNELS NUMERIC"); sb.append(", SAMPLEFREQ VARCHAR2(").append(SIZE_SAMPLEFREQ).append(")"); sb.append(", CODECA VARCHAR2(").append(SIZE_CODECA).append(")"); sb.append(", BITSPERSAMPLE INT"); sb.append(", ALBUM VARCHAR2(").append(SIZE_ALBUM).append(")"); sb.append(", ARTIST VARCHAR2(").append(SIZE_ARTIST).append(")"); sb.append(", SONGNAME VARCHAR2(").append(SIZE_SONGNAME).append(")"); sb.append(", GENRE VARCHAR2(").append(SIZE_GENRE).append(")"); sb.append(", YEAR INT"); sb.append(", TRACK INT"); sb.append(", DELAY INT"); sb.append(", MUXINGMODE VARCHAR2(").append(SIZE_MUXINGMODE).append(")"); sb.append(", BITRATE INT"); sb.append(", constraint PKAUDIO primary key (FILEID, ID))"); executeUpdate(conn, sb.toString()); sb = new StringBuilder(); sb.append("CREATE TABLE SUBTRACKS ("); sb.append(" FILEID INT NOT NULL"); sb.append(", ID INT NOT NULL"); sb.append(", LANG VARCHAR2(").append(SIZE_LANG).append(")"); sb.append(", FLAVOR VARCHAR2(").append(SIZE_FLAVOR).append(")"); sb.append(", TYPE INT"); sb.append(", constraint PKSUB primary key (FILEID, ID))"); executeUpdate(conn, sb.toString()); executeUpdate(conn, "CREATE TABLE METADATA (KEY VARCHAR2(255) NOT NULL, VALUE VARCHAR2(255) NOT NULL)"); executeUpdate(conn, "INSERT INTO METADATA VALUES ('VERSION', '" + PMS.getVersion() + "')"); executeUpdate(conn, "CREATE INDEX IDXARTIST on AUDIOTRACKS (ARTIST asc);"); executeUpdate(conn, "CREATE INDEX IDXALBUM on AUDIOTRACKS (ALBUM asc);"); executeUpdate(conn, "CREATE INDEX IDXGENRE on AUDIOTRACKS (GENRE asc);"); executeUpdate(conn, "CREATE INDEX IDXYEAR on AUDIOTRACKS (YEAR asc);"); executeUpdate(conn, "CREATE TABLE REGEXP_RULES ( ID VARCHAR2(255) PRIMARY KEY, RULE VARCHAR2(255), ORDR NUMERIC);"); executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '###', '(?i)^\\W.+', 0 );"); executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '0-9', '(?i)^\\d.+', 1 );"); // Retrieve the alphabet property value and split it String[] chars = Messages.getString("DLNAMediaDatabase.1").split(","); for (int i = 0; i < chars.length; i++) { // Create regexp rules for characters with a sort order based on the property value executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '" + chars[i] + "', '(?i)^" + chars[i] + ".+', " + (i + 2) + " );"); } LOGGER.debug("Database initialized"); } catch (SQLException se) { LOGGER.info("Error in table creation: " + se.getMessage()); } finally { close(conn); } } else { LOGGER.debug("Database file count: " + dbCount); LOGGER.debug("Database version: " + version); } } private void executeUpdate(Connection conn, String sql) throws SQLException { if (conn != null) { Statement stmt = conn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } } public boolean isDataExists(String name, long modified) { boolean found = false; Connection conn = null; ResultSet rs = null; PreparedStatement stmt = null; try { conn = getConnection(); stmt = conn.prepareStatement("SELECT * FROM FILES WHERE FILENAME = ? AND MODIFIED = ?"); stmt.setString(1, name); stmt.setTimestamp(2, new Timestamp(modified)); rs = stmt.executeQuery(); while (rs.next()) { found = true; } } catch (SQLException se) { LOGGER.error(null, se); return false; } finally { close(rs); close(stmt); close(conn); } return found; } public ArrayList<DLNAMediaInfo> getData(String name, long modified) { ArrayList<DLNAMediaInfo> list = new ArrayList<DLNAMediaInfo>(); Connection conn = null; ResultSet rs = null; PreparedStatement stmt = null; try { conn = getConnection(); stmt = conn.prepareStatement("SELECT * FROM FILES WHERE FILENAME = ? AND MODIFIED = ?"); stmt.setString(1, name); stmt.setTimestamp(2, new Timestamp(modified)); rs = stmt.executeQuery(); while (rs.next()) { DLNAMediaInfo media = new DLNAMediaInfo(); int id = rs.getInt("ID"); media.setDuration(toDouble(rs, "DURATION")); media.setBitrate(rs.getInt("BITRATE")); media.setWidth(rs.getInt("WIDTH")); media.setHeight(rs.getInt("HEIGHT")); media.setSize(rs.getLong("SIZE")); media.setCodecV(rs.getString("CODECV")); media.setFrameRate(rs.getString("FRAMERATE")); media.setAspect(rs.getString("ASPECT")); media.setBitsPerPixel(rs.getInt("BITSPERPIXEL")); media.setThumb(rs.getBytes("THUMB")); media.setContainer(rs.getString("CONTAINER")); media.setModel(rs.getString("MODEL")); if (media.getModel() != null && !FormatConfiguration.JPG.equals(media.getContainer())) { media.setExtrasAsString(media.getModel()); } media.setExposure(rs.getInt("EXPOSURE")); media.setOrientation(rs.getInt("ORIENTATION")); media.setIso(rs.getInt("ISO")); media.setMuxingMode(rs.getString("MUXINGMODE")); media.setFrameRateMode(rs.getString("FRAMERATEMODE")); media.setMediaparsed(true); PreparedStatement audios = conn.prepareStatement("SELECT * FROM AUDIOTRACKS WHERE FILEID = ?"); audios.setInt(1, id); ResultSet subrs = audios.executeQuery(); while (subrs.next()) { DLNAMediaAudio audio = new DLNAMediaAudio(); audio.setId(subrs.getInt("ID")); audio.setLang(subrs.getString("LANG")); audio.setFlavor(subrs.getString("FLAVOR")); audio.getAudioProperties().setNumberOfChannels(subrs.getInt("NRAUDIOCHANNELS")); audio.setSampleFrequency(subrs.getString("SAMPLEFREQ")); audio.setCodecA(subrs.getString("CODECA")); audio.setBitsperSample(subrs.getInt("BITSPERSAMPLE")); audio.setAlbum(subrs.getString("ALBUM")); audio.setArtist(subrs.getString("ARTIST")); audio.setSongname(subrs.getString("SONGNAME")); audio.setGenre(subrs.getString("GENRE")); audio.setYear(subrs.getInt("YEAR")); audio.setTrack(subrs.getInt("TRACK")); audio.getAudioProperties().setAudioDelay(subrs.getInt("DELAY")); audio.setMuxingModeAudio(subrs.getString("MUXINGMODE")); audio.setBitRate(subrs.getInt("BITRATE")); media.getAudioTracksList().add(audio); } subrs.close(); audios.close(); PreparedStatement subs = conn.prepareStatement("SELECT * FROM SUBTRACKS WHERE FILEID = ?"); subs.setInt(1, id); subrs = subs.executeQuery(); while (subrs.next()) { DLNAMediaSubtitle sub = new DLNAMediaSubtitle(); sub.setId(subrs.getInt("ID")); sub.setLang(subrs.getString("LANG")); sub.setFlavor(subrs.getString("FLAVOR")); sub.setType(SubtitleType.valueOfStableIndex(subrs.getInt("TYPE"))); media.getSubtitleTracksList().add(sub); } subrs.close(); subs.close(); list.add(media); } } catch (SQLException se) { LOGGER.error(null, se); return null; } finally { close(rs); close(stmt); close(conn); } return list; } private Double toDouble(ResultSet rs, String column) throws SQLException { Object obj = rs.getObject(column); if (obj instanceof Double) { return (Double) obj; } return null; } public synchronized void insertData(String name, long modified, int type, DLNAMediaInfo media) { Connection conn = null; PreparedStatement ps = null; try { conn = getConnection(); ps = conn.prepareStatement("INSERT INTO FILES(FILENAME, MODIFIED, TYPE, DURATION, BITRATE, WIDTH, HEIGHT, SIZE, CODECV, FRAMERATE, ASPECT, BITSPERPIXEL, THUMB, CONTAINER, MODEL, EXPOSURE, ORIENTATION, ISO, MUXINGMODE, FRAMERATEMODE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, name); ps.setTimestamp(2, new Timestamp(modified)); ps.setInt(3, type); if (media != null) { if (media.getDuration() != null) { ps.setDouble(4, media.getDurationInSeconds()); } else { ps.setNull(4, Types.DOUBLE); } // TODO: Stop trying to parse the bitrate of images int databaseBitrate = media.getBitrate(); if (databaseBitrate == 0) { LOGGER.debug("Could not parse the bitrate from: " + name); } ps.setInt(5, databaseBitrate); ps.setInt(6, media.getWidth()); ps.setInt(7, media.getHeight()); ps.setLong(8, media.getSize()); ps.setString(9, left(media.getCodecV(), SIZE_CODECV)); ps.setString(10, left(media.getFrameRate(), SIZE_FRAMERATE)); ps.setString(11, left(media.getAspect(), SIZE_ASPECT)); ps.setInt(12, media.getBitsPerPixel()); ps.setBytes(13, media.getThumb()); ps.setString(14, left(media.getContainer(), SIZE_CONTAINER)); if (media.getExtras() != null) { ps.setString(15, left(media.getExtrasAsString(), SIZE_MODEL)); } else { ps.setString(15, left(media.getModel(), SIZE_MODEL)); } ps.setInt(16, media.getExposure()); ps.setInt(17, media.getOrientation()); ps.setInt(18, media.getIso()); ps.setString(19, left(media.getMuxingModeAudio(), SIZE_MUXINGMODE)); ps.setString(20, left(media.getFrameRateMode(), SIZE_FRAMERATE_MODE)); } else { ps.setString(4, null); ps.setInt(5, 0); ps.setInt(6, 0); ps.setInt(7, 0); ps.setLong(8, 0); ps.setString(9, null); ps.setString(10, null); ps.setString(11, null); ps.setInt(12, 0); ps.setBytes(13, null); ps.setString(14, null); ps.setString(15, null); ps.setInt(16, 0); ps.setInt(17, 0); ps.setInt(18, 0); ps.setString(19, null); ps.setString(20, null); } ps.executeUpdate(); ResultSet rs = ps.getGeneratedKeys(); int id = -1; while (rs.next()) { id = rs.getInt(1); } rs.close(); if (media != null && id > -1) { PreparedStatement insert = null; if (media.getAudioTracksList().size() > 0) { insert = conn.prepareStatement("INSERT INTO AUDIOTRACKS VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); } for (DLNAMediaAudio audio : media.getAudioTracksList()) { insert.clearParameters(); insert.setInt(1, id); insert.setInt(2, audio.getId()); insert.setString(3, left(audio.getLang(), SIZE_LANG)); insert.setString(4, left(audio.getFlavor(), SIZE_FLAVOR)); insert.setInt(5, audio.getAudioProperties().getNumberOfChannels()); insert.setString(6, left(audio.getSampleFrequency(), SIZE_SAMPLEFREQ)); insert.setString(7, left(audio.getCodecA(), SIZE_CODECA)); insert.setInt(8, audio.getBitsperSample()); insert.setString(9, left(trimToEmpty(audio.getAlbum()), SIZE_ALBUM)); insert.setString(10, left(trimToEmpty(audio.getArtist()), SIZE_ARTIST)); insert.setString(11, left(trimToEmpty(audio.getSongname()), SIZE_SONGNAME)); insert.setString(12, left(trimToEmpty(audio.getGenre()), SIZE_GENRE)); insert.setInt(13, audio.getYear()); insert.setInt(14, audio.getTrack()); insert.setInt(15, audio.getAudioProperties().getAudioDelay()); insert.setString(16, left(trimToEmpty(audio.getMuxingModeAudio()), SIZE_MUXINGMODE)); insert.setInt(17, audio.getBitRate()); try { insert.executeUpdate(); } catch (JdbcSQLException e) { if (e.getErrorCode() == 23505) { LOGGER.debug("A duplicate key error occurred while trying to store the following file's audio information in the database: " + name); } else { LOGGER.debug("An error occurred while trying to store the following file's audio information in the database: " + name); } LOGGER.debug("The error given by jdbc was: " + e); } } if (media.getSubtitleTracksList().size() > 0) { insert = conn.prepareStatement("INSERT INTO SUBTRACKS VALUES (?, ?, ?, ?, ?)"); } for (DLNAMediaSubtitle sub : media.getSubtitleTracksList()) { if (sub.getExternalFile() == null) { // no save of external subtitles insert.clearParameters(); insert.setInt(1, id); insert.setInt(2, sub.getId()); insert.setString(3, left(sub.getLang(), SIZE_LANG)); insert.setString(4, left(sub.getFlavor(), SIZE_FLAVOR)); insert.setInt(5, sub.getType().getStableIndex()); try { insert.executeUpdate(); } catch (JdbcSQLException e) { if (e.getErrorCode() == 23505) { LOGGER.debug("A duplicate key error occurred while trying to store the following file's subtitle information in the database: " + name); } else { LOGGER.debug("An error occurred while trying to store the following file's subtitle information in the database: " + name); } LOGGER.debug("The error given by jdbc was: " + e); } } } close(insert); } } catch (SQLException se) { if (se.getErrorCode() == 23001) { LOGGER.debug("Duplicate key while inserting this entry: " + name + " into the database: " + se.getMessage()); } else { LOGGER.error(null, se); } } finally { close(ps); close(conn); } } public synchronized void updateThumbnail(String name, long modified, int type, DLNAMediaInfo media) { Connection conn = null; PreparedStatement ps = null; try { conn = getConnection(); ps = conn.prepareStatement("UPDATE FILES SET THUMB = ? WHERE FILENAME = ? AND MODIFIED = ?"); ps.setString(2, name); ps.setTimestamp(3, new Timestamp(modified)); if (media != null) { ps.setBytes(1, media.getThumb()); } else { ps.setNull(1, Types.BINARY); } ps.executeUpdate(); } catch (SQLException se) { if (se.getErrorCode() == 23001) { LOGGER.debug("Duplicate key while inserting this entry: " + name + " into the database: " + se.getMessage()); } else { LOGGER.error(null, se); } } finally { close(ps); close(conn); } } public ArrayList<String> getStrings(String sql) { ArrayList<String> list = new ArrayList<String>(); Connection conn = null; ResultSet rs = null; PreparedStatement ps = null; try { conn = getConnection(); ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { String str = rs.getString(1); if (isBlank(str)) { if (!list.contains(NONAME)) { list.add(NONAME); } } else if (!list.contains(str)) { list.add(str); } } } catch (SQLException se) { LOGGER.error(null, se); return null; } finally { close(rs); close(ps); close(conn); } return list; } public void cleanup() { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = getConnection(); ps = conn.prepareStatement("SELECT COUNT(*) FROM FILES"); rs = ps.executeQuery(); dbCount = 0; if (rs.next()) { dbCount = rs.getInt(1); } rs.close(); ps.close(); PMS.get().getFrame().setStatusLine(Messages.getString("DLNAMediaDatabase.2") + " 0%"); int i = 0; int oldpercent = 0; if (dbCount > 0) { ps = conn.prepareStatement("SELECT FILENAME, MODIFIED, ID FROM FILES", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); rs = ps.executeQuery(); while (rs.next()) { String filename = rs.getString("FILENAME"); long modified = rs.getTimestamp("MODIFIED").getTime(); File file = new File(filename); if (!file.exists() || file.lastModified() != modified) { rs.deleteRow(); } i++; int newpercent = i * 100 / dbCount; if (newpercent > oldpercent) { PMS.get().getFrame().setStatusLine(Messages.getString("DLNAMediaDatabase.2") + newpercent + "%"); oldpercent = newpercent; } } } } catch (SQLException se) { LOGGER.error(null, se); } finally { close(rs); close(ps); close(conn); } } public ArrayList<File> getFiles(String sql) { ArrayList<File> list = new ArrayList<File>(); Connection conn = null; ResultSet rs = null; PreparedStatement ps = null; try { conn = getConnection(); ps = conn.prepareStatement(sql.toLowerCase().startsWith("select") ? sql : ("SELECT FILENAME, MODIFIED FROM FILES WHERE " + sql)); rs = ps.executeQuery(); while (rs.next()) { String filename = rs.getString("FILENAME"); long modified = rs.getTimestamp("MODIFIED").getTime(); File file = new File(filename); if (file.exists() && file.lastModified() == modified) { list.add(file); } } } catch (SQLException se) { LOGGER.error(null, se); return null; } finally { close(rs); close(ps); close(conn); } return list; } private void close(ResultSet rs) { try { if (rs != null) { rs.close(); } } catch (SQLException e) { LOGGER.error("error during closing:" + e.getMessage(), e); } } private void close(Statement ps) { try { if (ps != null) { ps.close(); } } catch (SQLException e) { LOGGER.error("error during closing:" + e.getMessage(), e); } } private void close(Connection conn) { try { if (conn != null) { conn.close(); } } catch (SQLException e) { LOGGER.error("error during closing:" + e.getMessage(), e); } } public synchronized boolean isScanLibraryRunning() { return scanner != null && scanner.isAlive(); } public synchronized void scanLibrary() { if (scanner == null) { scanner = new Thread(this, "Library Scanner"); scanner.start(); } else if (scanner.isAlive()) { LOGGER.info("Scanner is already running !"); } else { scanner = new Thread(this, "Library Scanner"); scanner.start(); } } public synchronized void stopScanLibrary() { if (scanner != null && scanner.isAlive()) { PMS.get().getRootFolder(null).stopScan(); } } @Override public void run() { PMS.get().getRootFolder(null).scan(); } public void compact() { LOGGER.info("Compacting database..."); PMS.get().getFrame().setStatusLine(Messages.getString("DLNAMediaDatabase.3")); String filename = "database/backup.sql"; try { Script.execute(url, "sa", "", filename); DeleteDbFiles.execute(dbDir, dbName, true); RunScript.execute(url, "sa", "", filename, null, false); } catch (SQLException se) { LOGGER.error("Error in compacting database: ", se); } finally { File testsql = new File(filename); if (testsql.exists() && !testsql.delete()) { testsql.deleteOnExit(); } } PMS.get().getFrame().setStatusLine(null); } }
false
true
public void init(boolean force) { dbCount = -1; String version = null; Connection conn = null; ResultSet rs = null; Statement stmt = null; // Check whether the database is not severely damaged, corrupted or wrong version boolean force_delete = false; try { conn = getConnection(); } catch (SQLException se) { // Connection can't be established, so delete the database force_delete = true; } finally { close(conn); if (FileUtils.exists(dbDir + File.separator + dbName + ".data.db") || force_delete) { FileUtils.deleteRecursive(dbDir, true); if (!FileUtils.exists(dbDir)) { LOGGER.debug("The cache has been deleted because it was corrupt or had the wrong version"); } else { if (!java.awt.GraphicsEnvironment.isHeadless()) { JOptionPane.showMessageDialog( (JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())), String.format(Messages.getString("DLNAMediaDatabase.5"), dbDir), Messages.getString("Dialog.Error"), JOptionPane.ERROR_MESSAGE ); } LOGGER.debug("Damaged cache can't be deleted. Stop the program and delete the folder \"" + dbDir + "\" manually"); } } } try { conn = getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT count(*) FROM FILES"); if (rs.next()) { dbCount = rs.getInt(1); } rs.close(); stmt.close(); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT VALUE FROM METADATA WHERE KEY = 'VERSION'"); if (rs.next()) { version = rs.getString(1); } } catch (SQLException se) { if (se.getErrorCode() != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in following step LOGGER.error(null, se); } } finally { close(rs); close(stmt); close(conn); } boolean force_reinit = !PMS.getVersion().equals(version); // here we can force a deletion for a specific version if (force || dbCount == -1 || force_reinit) { LOGGER.debug("Database will be (re)initialized"); try { conn = getConnection(); executeUpdate(conn, "DROP TABLE FILES"); executeUpdate(conn, "DROP TABLE METADATA"); executeUpdate(conn, "DROP TABLE REGEXP_RULES"); executeUpdate(conn, "DROP TABLE AUDIOTRACKS"); executeUpdate(conn, "DROP TABLE SUBTRACKS"); } catch (SQLException se) { if (se.getErrorCode() != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in following step LOGGER.error(null, se); } } try { StringBuilder sb = new StringBuilder(); sb.append("CREATE TABLE FILES ("); sb.append(" ID INT AUTO_INCREMENT"); sb.append(", FILENAME VARCHAR2(1024) NOT NULL"); sb.append(", MODIFIED TIMESTAMP NOT NULL"); sb.append(", TYPE INT"); sb.append(", DURATION DOUBLE"); sb.append(", BITRATE INT"); sb.append(", WIDTH INT"); sb.append(", HEIGHT INT"); sb.append(", SIZE NUMERIC"); sb.append(", CODECV VARCHAR2(").append(SIZE_CODECV).append(")"); sb.append(", FRAMERATE VARCHAR2(").append(SIZE_FRAMERATE).append(")"); sb.append(", ASPECT VARCHAR2(").append(SIZE_ASPECT).append(")"); sb.append(", BITSPERPIXEL INT"); sb.append(", THUMB BINARY"); sb.append(", CONTAINER VARCHAR2(").append(SIZE_CONTAINER).append(")"); sb.append(", MODEL VARCHAR2(").append(SIZE_MODEL).append(")"); sb.append(", EXPOSURE INT"); sb.append(", ORIENTATION INT"); sb.append(", ISO INT"); sb.append(", MUXINGMODE VARCHAR2(").append(SIZE_MUXINGMODE).append(")"); sb.append(", FRAMERATEMODE VARCHAR2(").append(SIZE_FRAMERATE_MODE).append(")"); sb.append(", constraint PK1 primary key (FILENAME, MODIFIED, ID))"); executeUpdate(conn, sb.toString()); sb = new StringBuilder(); sb.append("CREATE TABLE AUDIOTRACKS ("); sb.append(" FILEID INT NOT NULL"); sb.append(", ID INT NOT NULL"); sb.append(", LANG VARCHAR2(").append(SIZE_LANG).append(")"); sb.append(", FLAVOR VARCHAR2(").append(SIZE_FLAVOR).append(")"); sb.append(", NRAUDIOCHANNELS NUMERIC"); sb.append(", SAMPLEFREQ VARCHAR2(").append(SIZE_SAMPLEFREQ).append(")"); sb.append(", CODECA VARCHAR2(").append(SIZE_CODECA).append(")"); sb.append(", BITSPERSAMPLE INT"); sb.append(", ALBUM VARCHAR2(").append(SIZE_ALBUM).append(")"); sb.append(", ARTIST VARCHAR2(").append(SIZE_ARTIST).append(")"); sb.append(", SONGNAME VARCHAR2(").append(SIZE_SONGNAME).append(")"); sb.append(", GENRE VARCHAR2(").append(SIZE_GENRE).append(")"); sb.append(", YEAR INT"); sb.append(", TRACK INT"); sb.append(", DELAY INT"); sb.append(", MUXINGMODE VARCHAR2(").append(SIZE_MUXINGMODE).append(")"); sb.append(", BITRATE INT"); sb.append(", constraint PKAUDIO primary key (FILEID, ID))"); executeUpdate(conn, sb.toString()); sb = new StringBuilder(); sb.append("CREATE TABLE SUBTRACKS ("); sb.append(" FILEID INT NOT NULL"); sb.append(", ID INT NOT NULL"); sb.append(", LANG VARCHAR2(").append(SIZE_LANG).append(")"); sb.append(", FLAVOR VARCHAR2(").append(SIZE_FLAVOR).append(")"); sb.append(", TYPE INT"); sb.append(", constraint PKSUB primary key (FILEID, ID))"); executeUpdate(conn, sb.toString()); executeUpdate(conn, "CREATE TABLE METADATA (KEY VARCHAR2(255) NOT NULL, VALUE VARCHAR2(255) NOT NULL)"); executeUpdate(conn, "INSERT INTO METADATA VALUES ('VERSION', '" + PMS.getVersion() + "')"); executeUpdate(conn, "CREATE INDEX IDXARTIST on AUDIOTRACKS (ARTIST asc);"); executeUpdate(conn, "CREATE INDEX IDXALBUM on AUDIOTRACKS (ALBUM asc);"); executeUpdate(conn, "CREATE INDEX IDXGENRE on AUDIOTRACKS (GENRE asc);"); executeUpdate(conn, "CREATE INDEX IDXYEAR on AUDIOTRACKS (YEAR asc);"); executeUpdate(conn, "CREATE TABLE REGEXP_RULES ( ID VARCHAR2(255) PRIMARY KEY, RULE VARCHAR2(255), ORDR NUMERIC);"); executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '###', '(?i)^\\W.+', 0 );"); executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '0-9', '(?i)^\\d.+', 1 );"); // Retrieve the alphabet property value and split it String[] chars = Messages.getString("DLNAMediaDatabase.1").split(","); for (int i = 0; i < chars.length; i++) { // Create regexp rules for characters with a sort order based on the property value executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '" + chars[i] + "', '(?i)^" + chars[i] + ".+', " + (i + 2) + " );"); } LOGGER.debug("Database initialized"); } catch (SQLException se) { LOGGER.info("Error in table creation: " + se.getMessage()); } finally { close(conn); } } else { LOGGER.debug("Database file count: " + dbCount); LOGGER.debug("Database version: " + version); } }
public void init(boolean force) { dbCount = -1; String version = null; Connection conn = null; ResultSet rs = null; Statement stmt = null; try { conn = getConnection(); } catch (SQLException se) { if (FileUtils.exists(dbDir + File.separator + dbName + ".data.db") || (se.getErrorCode() == 90048)) { // Cache is corrupt or wrong version, so delete it FileUtils.deleteRecursive(dbDir, true); if (!FileUtils.exists(dbDir)){ LOGGER.debug("The cache has been deleted because it was corrupt or had the wrong version"); } else { if (!java.awt.GraphicsEnvironment.isHeadless()) { JOptionPane.showMessageDialog( (JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())), String.format(Messages.getString("DLNAMediaDatabase.5"), dbDir), Messages.getString("Dialog.Error"), JOptionPane.ERROR_MESSAGE); } LOGGER.debug("Damaged cache can't be deleted. Stop the program and delete the folder \"" + dbDir + "\" manually"); PMS.getConfiguration().setUseCache(false); return; } } else { LOGGER.debug("Cache connection error: " + se.getMessage()); PMS.getConfiguration().setUseCache(false); return; } } try { conn = getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT count(*) FROM FILES"); if (rs.next()) { dbCount = rs.getInt(1); } rs.close(); stmt.close(); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT VALUE FROM METADATA WHERE KEY = 'VERSION'"); if (rs.next()) { version = rs.getString(1); } } catch (SQLException se) { if (se.getErrorCode() != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in following step LOGGER.error(null, se); } } finally { close(rs); close(stmt); close(conn); } boolean force_reinit = !PMS.getVersion().equals(version); // here we can force a deletion for a specific version if (force || dbCount == -1 || force_reinit) { LOGGER.debug("Database will be (re)initialized"); try { conn = getConnection(); executeUpdate(conn, "DROP TABLE FILES"); executeUpdate(conn, "DROP TABLE METADATA"); executeUpdate(conn, "DROP TABLE REGEXP_RULES"); executeUpdate(conn, "DROP TABLE AUDIOTRACKS"); executeUpdate(conn, "DROP TABLE SUBTRACKS"); } catch (SQLException se) { if (se.getErrorCode() != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in following step LOGGER.error(null, se); } } try { StringBuilder sb = new StringBuilder(); sb.append("CREATE TABLE FILES ("); sb.append(" ID INT AUTO_INCREMENT"); sb.append(", FILENAME VARCHAR2(1024) NOT NULL"); sb.append(", MODIFIED TIMESTAMP NOT NULL"); sb.append(", TYPE INT"); sb.append(", DURATION DOUBLE"); sb.append(", BITRATE INT"); sb.append(", WIDTH INT"); sb.append(", HEIGHT INT"); sb.append(", SIZE NUMERIC"); sb.append(", CODECV VARCHAR2(").append(SIZE_CODECV).append(")"); sb.append(", FRAMERATE VARCHAR2(").append(SIZE_FRAMERATE).append(")"); sb.append(", ASPECT VARCHAR2(").append(SIZE_ASPECT).append(")"); sb.append(", BITSPERPIXEL INT"); sb.append(", THUMB BINARY"); sb.append(", CONTAINER VARCHAR2(").append(SIZE_CONTAINER).append(")"); sb.append(", MODEL VARCHAR2(").append(SIZE_MODEL).append(")"); sb.append(", EXPOSURE INT"); sb.append(", ORIENTATION INT"); sb.append(", ISO INT"); sb.append(", MUXINGMODE VARCHAR2(").append(SIZE_MUXINGMODE).append(")"); sb.append(", FRAMERATEMODE VARCHAR2(").append(SIZE_FRAMERATE_MODE).append(")"); sb.append(", constraint PK1 primary key (FILENAME, MODIFIED, ID))"); executeUpdate(conn, sb.toString()); sb = new StringBuilder(); sb.append("CREATE TABLE AUDIOTRACKS ("); sb.append(" FILEID INT NOT NULL"); sb.append(", ID INT NOT NULL"); sb.append(", LANG VARCHAR2(").append(SIZE_LANG).append(")"); sb.append(", FLAVOR VARCHAR2(").append(SIZE_FLAVOR).append(")"); sb.append(", NRAUDIOCHANNELS NUMERIC"); sb.append(", SAMPLEFREQ VARCHAR2(").append(SIZE_SAMPLEFREQ).append(")"); sb.append(", CODECA VARCHAR2(").append(SIZE_CODECA).append(")"); sb.append(", BITSPERSAMPLE INT"); sb.append(", ALBUM VARCHAR2(").append(SIZE_ALBUM).append(")"); sb.append(", ARTIST VARCHAR2(").append(SIZE_ARTIST).append(")"); sb.append(", SONGNAME VARCHAR2(").append(SIZE_SONGNAME).append(")"); sb.append(", GENRE VARCHAR2(").append(SIZE_GENRE).append(")"); sb.append(", YEAR INT"); sb.append(", TRACK INT"); sb.append(", DELAY INT"); sb.append(", MUXINGMODE VARCHAR2(").append(SIZE_MUXINGMODE).append(")"); sb.append(", BITRATE INT"); sb.append(", constraint PKAUDIO primary key (FILEID, ID))"); executeUpdate(conn, sb.toString()); sb = new StringBuilder(); sb.append("CREATE TABLE SUBTRACKS ("); sb.append(" FILEID INT NOT NULL"); sb.append(", ID INT NOT NULL"); sb.append(", LANG VARCHAR2(").append(SIZE_LANG).append(")"); sb.append(", FLAVOR VARCHAR2(").append(SIZE_FLAVOR).append(")"); sb.append(", TYPE INT"); sb.append(", constraint PKSUB primary key (FILEID, ID))"); executeUpdate(conn, sb.toString()); executeUpdate(conn, "CREATE TABLE METADATA (KEY VARCHAR2(255) NOT NULL, VALUE VARCHAR2(255) NOT NULL)"); executeUpdate(conn, "INSERT INTO METADATA VALUES ('VERSION', '" + PMS.getVersion() + "')"); executeUpdate(conn, "CREATE INDEX IDXARTIST on AUDIOTRACKS (ARTIST asc);"); executeUpdate(conn, "CREATE INDEX IDXALBUM on AUDIOTRACKS (ALBUM asc);"); executeUpdate(conn, "CREATE INDEX IDXGENRE on AUDIOTRACKS (GENRE asc);"); executeUpdate(conn, "CREATE INDEX IDXYEAR on AUDIOTRACKS (YEAR asc);"); executeUpdate(conn, "CREATE TABLE REGEXP_RULES ( ID VARCHAR2(255) PRIMARY KEY, RULE VARCHAR2(255), ORDR NUMERIC);"); executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '###', '(?i)^\\W.+', 0 );"); executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '0-9', '(?i)^\\d.+', 1 );"); // Retrieve the alphabet property value and split it String[] chars = Messages.getString("DLNAMediaDatabase.1").split(","); for (int i = 0; i < chars.length; i++) { // Create regexp rules for characters with a sort order based on the property value executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '" + chars[i] + "', '(?i)^" + chars[i] + ".+', " + (i + 2) + " );"); } LOGGER.debug("Database initialized"); } catch (SQLException se) { LOGGER.info("Error in table creation: " + se.getMessage()); } finally { close(conn); } } else { LOGGER.debug("Database file count: " + dbCount); LOGGER.debug("Database version: " + version); } }
diff --git a/src/com/jgaap/distances/KendallCorrelationDistance.java b/src/com/jgaap/distances/KendallCorrelationDistance.java index 1a6833e..556d660 100644 --- a/src/com/jgaap/distances/KendallCorrelationDistance.java +++ b/src/com/jgaap/distances/KendallCorrelationDistance.java @@ -1,192 +1,193 @@ // Copyright (c) 2009, 2011 by Patrick Juola. All rights reserved. All unauthorized use prohibited. /** **/ package com.jgaap.distances; import java.util.*; import com.jgaap.generics.DistanceFunction; import com.jgaap.generics.EventSet; import com.jgaap.generics.EventHistogram; import com.jgaap.generics.Event; import com.jgaap.generics.Pair; /** * KendallCorrelationDistance : sequence-based distance for NN * algorithm suggested by (Wilson & Martinez 1997, JAIR). General theory: * Kendell's rank correlation measures how similar frequency rankings are * between two rank orderings; +1 is perfect agreement, -1 is perfect * disagreement. We subtract from 1 to get a distance measure. * * @author Juola * @version 5.0 */ public class KendallCorrelationDistance extends DistanceFunction { @Override public String displayName(){ return "Kendall Correlation Distance"; } @Override public String tooltipText(){ return "Kendall Correlation Distance Nearest Neighbor Classifier"; } @Override public boolean showInGUI(){ return true; } /** * Returns KC distance between event sets es1 and es2 * * @param es1 * The first EventSet * @param es2 * The second EventSet * @return the KC distance between them */ @Override public double distance(EventSet es1, EventSet es2) { EventHistogram h1 = new EventHistogram(); EventHistogram h2 = new EventHistogram(); Set<Event> s = new HashSet<Event>(); List<Pair<Event,Double>> l1 = new ArrayList<Pair<Event,Double>>(); List<Pair<Event,Double>> l2 = new ArrayList<Pair<Event,Double>>(); HashMap<Event,Integer> hm1 = new HashMap<Event,Integer>(); HashMap<Event,Integer> hm2 = new HashMap<Event,Integer>(); double oldfreq = Double.POSITIVE_INFINITY; double correlation = 0.0; /* make two histograms */ /* also make set for union of two histograms */ for (int i = 0; i < es1.size(); i++) { h1.add(es1.eventAt(i)); s.add(es1.eventAt(i)); } for (int i = 0; i < es2.size(); i++) { h2.add(es2.eventAt(i)); s.add(es2.eventAt(i)); } //System.out.println(h1.toString()); //System.out.println(h2.toString()); /* make lists of the histograms */ for (Event e: h1) { l1.add(new Pair<Event, Double>(e,h1.getRelativeFrequency(e),2) ); } for (Event e: h2) { l2.add(new Pair<Event, Double>(e,h2.getRelativeFrequency(e),2) ); } /* sort the list so the most frequent items are at the top */ /* NOTE : THIS MAY BE USEFUL ELSEWHERE : SAVE THIS CODE */ Collections.sort(l1); Collections.reverse(l1); Collections.sort(l2); Collections.reverse(l2); /* DEBUGGING STUFF for (Pair <Event,Double> p : l1) { System.out.println("L1: " + p.toString()); } for (Pair <Event,Double> p : l1) { System.out.println("L2: " + p.toString()); } */ /* Convert lists into a hashmap of event:rank pairs */ int rank = 0; int count = 0; for (Pair<Event,Double> p : l1) { Event e = (Event) (p.getFirst()); double f = (Double) (p.getSecond()); count++; if (f != oldfreq) { rank = count; oldfreq = f; } hm1.put(e,rank); } /* reset and do second list */ rank = 0; count = 0; for (Pair<Event,Double> p : l2) { Event e = (Event) (p.getFirst()); double f = (Double) (p.getSecond()); count++; if (f != oldfreq) { rank = count; oldfreq = f; } hm2.put(e,rank); } /* More debugging stuff System.out.println(hm1.toString()); System.out.println(hm2.toString()); System.out.println(s.toString()); */ Integer x1, x2, y1, y2; for (Event e1 : s) { for (Event e2: s) { if (e1.equals(e2)) continue; /* get ranks of events e1 and e2 in both x and y distributions */ x1 = hm1.get(e1); /* if not present, rank is size + 1 */ if (x1 == null) x1 = hm1.size()+1; x2 = hm2.get(e1); if (x2 == null) x2 = hm2.size()+1; y1 = hm1.get(e2); /* if not present, rank is size + 1 */ - if (y1 == null) x1 = hm1.size()+1; + //broke because if (y1 == null) x1 = hm1.size()+1; x1 should be y1 + if (y1 == null) y1 = hm1.size()+1; y2 = hm2.get(e2); if (y2 == null) y2 = hm2.size()+1; /* more debugging stuff System.out.println(e1.toString() + " is ("+x1+","+x2+")"); System.out.println(e2.toString() + " is ("+y1+","+y2+")"); System.out.println(sgn(x1.compareTo(y1)) + " " + sgn(x2.compareTo(y2)) ); System.out.println(""); */ correlation += (sgn(x1.compareTo(y1)) * sgn(x2.compareTo(y2))); - //System.out.println(correlation); + System.out.println(correlation); } } //System.out.println(correlation); correlation /= (hm1.size() * (hm2.size()-1)); //System.out.println(correlation); //System.out.println("---"); return 1.0 - correlation; } private int sgn(Integer i) { if (i<0) return -1; else if (i==0) return 0; else /* i > 0 */ return 1; } }
false
true
public double distance(EventSet es1, EventSet es2) { EventHistogram h1 = new EventHistogram(); EventHistogram h2 = new EventHistogram(); Set<Event> s = new HashSet<Event>(); List<Pair<Event,Double>> l1 = new ArrayList<Pair<Event,Double>>(); List<Pair<Event,Double>> l2 = new ArrayList<Pair<Event,Double>>(); HashMap<Event,Integer> hm1 = new HashMap<Event,Integer>(); HashMap<Event,Integer> hm2 = new HashMap<Event,Integer>(); double oldfreq = Double.POSITIVE_INFINITY; double correlation = 0.0; /* make two histograms */ /* also make set for union of two histograms */ for (int i = 0; i < es1.size(); i++) { h1.add(es1.eventAt(i)); s.add(es1.eventAt(i)); } for (int i = 0; i < es2.size(); i++) { h2.add(es2.eventAt(i)); s.add(es2.eventAt(i)); } //System.out.println(h1.toString()); //System.out.println(h2.toString()); /* make lists of the histograms */ for (Event e: h1) { l1.add(new Pair<Event, Double>(e,h1.getRelativeFrequency(e),2) ); } for (Event e: h2) { l2.add(new Pair<Event, Double>(e,h2.getRelativeFrequency(e),2) ); } /* sort the list so the most frequent items are at the top */ /* NOTE : THIS MAY BE USEFUL ELSEWHERE : SAVE THIS CODE */ Collections.sort(l1); Collections.reverse(l1); Collections.sort(l2); Collections.reverse(l2); /* DEBUGGING STUFF for (Pair <Event,Double> p : l1) { System.out.println("L1: " + p.toString()); } for (Pair <Event,Double> p : l1) { System.out.println("L2: " + p.toString()); } */ /* Convert lists into a hashmap of event:rank pairs */ int rank = 0; int count = 0; for (Pair<Event,Double> p : l1) { Event e = (Event) (p.getFirst()); double f = (Double) (p.getSecond()); count++; if (f != oldfreq) { rank = count; oldfreq = f; } hm1.put(e,rank); } /* reset and do second list */ rank = 0; count = 0; for (Pair<Event,Double> p : l2) { Event e = (Event) (p.getFirst()); double f = (Double) (p.getSecond()); count++; if (f != oldfreq) { rank = count; oldfreq = f; } hm2.put(e,rank); } /* More debugging stuff System.out.println(hm1.toString()); System.out.println(hm2.toString()); System.out.println(s.toString()); */ Integer x1, x2, y1, y2; for (Event e1 : s) { for (Event e2: s) { if (e1.equals(e2)) continue; /* get ranks of events e1 and e2 in both x and y distributions */ x1 = hm1.get(e1); /* if not present, rank is size + 1 */ if (x1 == null) x1 = hm1.size()+1; x2 = hm2.get(e1); if (x2 == null) x2 = hm2.size()+1; y1 = hm1.get(e2); /* if not present, rank is size + 1 */ if (y1 == null) x1 = hm1.size()+1; y2 = hm2.get(e2); if (y2 == null) y2 = hm2.size()+1; /* more debugging stuff System.out.println(e1.toString() + " is ("+x1+","+x2+")"); System.out.println(e2.toString() + " is ("+y1+","+y2+")"); System.out.println(sgn(x1.compareTo(y1)) + " " + sgn(x2.compareTo(y2)) ); System.out.println(""); */ correlation += (sgn(x1.compareTo(y1)) * sgn(x2.compareTo(y2))); //System.out.println(correlation); } } //System.out.println(correlation); correlation /= (hm1.size() * (hm2.size()-1)); //System.out.println(correlation); //System.out.println("---"); return 1.0 - correlation; }
public double distance(EventSet es1, EventSet es2) { EventHistogram h1 = new EventHistogram(); EventHistogram h2 = new EventHistogram(); Set<Event> s = new HashSet<Event>(); List<Pair<Event,Double>> l1 = new ArrayList<Pair<Event,Double>>(); List<Pair<Event,Double>> l2 = new ArrayList<Pair<Event,Double>>(); HashMap<Event,Integer> hm1 = new HashMap<Event,Integer>(); HashMap<Event,Integer> hm2 = new HashMap<Event,Integer>(); double oldfreq = Double.POSITIVE_INFINITY; double correlation = 0.0; /* make two histograms */ /* also make set for union of two histograms */ for (int i = 0; i < es1.size(); i++) { h1.add(es1.eventAt(i)); s.add(es1.eventAt(i)); } for (int i = 0; i < es2.size(); i++) { h2.add(es2.eventAt(i)); s.add(es2.eventAt(i)); } //System.out.println(h1.toString()); //System.out.println(h2.toString()); /* make lists of the histograms */ for (Event e: h1) { l1.add(new Pair<Event, Double>(e,h1.getRelativeFrequency(e),2) ); } for (Event e: h2) { l2.add(new Pair<Event, Double>(e,h2.getRelativeFrequency(e),2) ); } /* sort the list so the most frequent items are at the top */ /* NOTE : THIS MAY BE USEFUL ELSEWHERE : SAVE THIS CODE */ Collections.sort(l1); Collections.reverse(l1); Collections.sort(l2); Collections.reverse(l2); /* DEBUGGING STUFF for (Pair <Event,Double> p : l1) { System.out.println("L1: " + p.toString()); } for (Pair <Event,Double> p : l1) { System.out.println("L2: " + p.toString()); } */ /* Convert lists into a hashmap of event:rank pairs */ int rank = 0; int count = 0; for (Pair<Event,Double> p : l1) { Event e = (Event) (p.getFirst()); double f = (Double) (p.getSecond()); count++; if (f != oldfreq) { rank = count; oldfreq = f; } hm1.put(e,rank); } /* reset and do second list */ rank = 0; count = 0; for (Pair<Event,Double> p : l2) { Event e = (Event) (p.getFirst()); double f = (Double) (p.getSecond()); count++; if (f != oldfreq) { rank = count; oldfreq = f; } hm2.put(e,rank); } /* More debugging stuff System.out.println(hm1.toString()); System.out.println(hm2.toString()); System.out.println(s.toString()); */ Integer x1, x2, y1, y2; for (Event e1 : s) { for (Event e2: s) { if (e1.equals(e2)) continue; /* get ranks of events e1 and e2 in both x and y distributions */ x1 = hm1.get(e1); /* if not present, rank is size + 1 */ if (x1 == null) x1 = hm1.size()+1; x2 = hm2.get(e1); if (x2 == null) x2 = hm2.size()+1; y1 = hm1.get(e2); /* if not present, rank is size + 1 */ //broke because if (y1 == null) x1 = hm1.size()+1; x1 should be y1 if (y1 == null) y1 = hm1.size()+1; y2 = hm2.get(e2); if (y2 == null) y2 = hm2.size()+1; /* more debugging stuff System.out.println(e1.toString() + " is ("+x1+","+x2+")"); System.out.println(e2.toString() + " is ("+y1+","+y2+")"); System.out.println(sgn(x1.compareTo(y1)) + " " + sgn(x2.compareTo(y2)) ); System.out.println(""); */ correlation += (sgn(x1.compareTo(y1)) * sgn(x2.compareTo(y2))); System.out.println(correlation); } } //System.out.println(correlation); correlation /= (hm1.size() * (hm2.size()-1)); //System.out.println(correlation); //System.out.println("---"); return 1.0 - correlation; }
diff --git a/modules/xml/src/main/java/org/mule/ibeans/module/xml/transformers/JAXBMarshallerTransformer.java b/modules/xml/src/main/java/org/mule/ibeans/module/xml/transformers/JAXBMarshallerTransformer.java index 8e14528..8a24eff 100644 --- a/modules/xml/src/main/java/org/mule/ibeans/module/xml/transformers/JAXBMarshallerTransformer.java +++ b/modules/xml/src/main/java/org/mule/ibeans/module/xml/transformers/JAXBMarshallerTransformer.java @@ -1,128 +1,130 @@ /* * $Id$ * -------------------------------------------------------------------------------------- * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com * * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.ibeans.module.xml.transformers; import org.mule.api.MuleEvent; import org.mule.api.lifecycle.InitialisationException; import org.mule.api.transformer.TransformerException; import org.mule.api.transport.OutputHandler; import org.mule.config.i18n.CoreMessages; import org.mule.transformer.AbstractTransformer; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringWriter; import java.io.Writer; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; /** * TODO */ public class JAXBMarshallerTransformer extends AbstractTransformer { protected JAXBContext jaxbContext; public JAXBMarshallerTransformer() { setReturnClass(InputStream.class); registerSourceType(Object.class); } public JAXBMarshallerTransformer(JAXBContext jaxbContext, Class returnType) { this(); this.jaxbContext = jaxbContext; setReturnClass(returnType); } @Override public void initialise() throws InitialisationException { super.initialise(); if (jaxbContext == null) { throw new InitialisationException(CoreMessages.objectIsNull("jaxbContext"), this); } } protected Object doTransform(Object src, String encoding) throws TransformerException { try { final Marshaller m = jaxbContext.createMarshaller(); if (getReturnClass().equals(String.class)) { Writer w = new StringWriter(); m.marshal(src, w); return w.toString(); } else if (getReturnClass().isAssignableFrom(Writer.class)) { Writer w = new StringWriter(); m.marshal(src, w); return w; } else if (Document.class.isAssignableFrom(getReturnClass())) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc = factory.newDocumentBuilder().newDocument(); m.marshal(src, doc); return doc; } else if (OutputStream.class.isAssignableFrom(getReturnClass())) { ByteArrayOutputStream out = new ByteArrayOutputStream(); m.marshal(src, out); return out; } else if (OutputHandler.class.equals(getReturnClass())) { return new OutputHandler() { public void write(MuleEvent event, OutputStream out) throws IOException { try { m.marshal(event.getMessage().getPayload(), out); } catch (JAXBException e) { - throw new IOException("failed to mashal objec tto XML", e); + IOException iox = new IOException("failed to mashal objec tto XML"); + iox.initCause(e); + throw iox; } } }; } } catch (Exception e) { throw new TransformerException(this, e); } return null; } public JAXBContext getJAXBContext() { return jaxbContext; } public void setJAXBContext(JAXBContext context) { this.jaxbContext = context; } }
true
true
protected Object doTransform(Object src, String encoding) throws TransformerException { try { final Marshaller m = jaxbContext.createMarshaller(); if (getReturnClass().equals(String.class)) { Writer w = new StringWriter(); m.marshal(src, w); return w.toString(); } else if (getReturnClass().isAssignableFrom(Writer.class)) { Writer w = new StringWriter(); m.marshal(src, w); return w; } else if (Document.class.isAssignableFrom(getReturnClass())) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc = factory.newDocumentBuilder().newDocument(); m.marshal(src, doc); return doc; } else if (OutputStream.class.isAssignableFrom(getReturnClass())) { ByteArrayOutputStream out = new ByteArrayOutputStream(); m.marshal(src, out); return out; } else if (OutputHandler.class.equals(getReturnClass())) { return new OutputHandler() { public void write(MuleEvent event, OutputStream out) throws IOException { try { m.marshal(event.getMessage().getPayload(), out); } catch (JAXBException e) { throw new IOException("failed to mashal objec tto XML", e); } } }; } } catch (Exception e) { throw new TransformerException(this, e); } return null; }
protected Object doTransform(Object src, String encoding) throws TransformerException { try { final Marshaller m = jaxbContext.createMarshaller(); if (getReturnClass().equals(String.class)) { Writer w = new StringWriter(); m.marshal(src, w); return w.toString(); } else if (getReturnClass().isAssignableFrom(Writer.class)) { Writer w = new StringWriter(); m.marshal(src, w); return w; } else if (Document.class.isAssignableFrom(getReturnClass())) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc = factory.newDocumentBuilder().newDocument(); m.marshal(src, doc); return doc; } else if (OutputStream.class.isAssignableFrom(getReturnClass())) { ByteArrayOutputStream out = new ByteArrayOutputStream(); m.marshal(src, out); return out; } else if (OutputHandler.class.equals(getReturnClass())) { return new OutputHandler() { public void write(MuleEvent event, OutputStream out) throws IOException { try { m.marshal(event.getMessage().getPayload(), out); } catch (JAXBException e) { IOException iox = new IOException("failed to mashal objec tto XML"); iox.initCause(e); throw iox; } } }; } } catch (Exception e) { throw new TransformerException(this, e); } return null; }
diff --git a/java/modules/core/src/main/java/org/apache/synapse/config/xml/endpoints/SALoadbalanceEndpointSerializer.java b/java/modules/core/src/main/java/org/apache/synapse/config/xml/endpoints/SALoadbalanceEndpointSerializer.java index 8f92084e5..f8f559fa3 100644 --- a/java/modules/core/src/main/java/org/apache/synapse/config/xml/endpoints/SALoadbalanceEndpointSerializer.java +++ b/java/modules/core/src/main/java/org/apache/synapse/config/xml/endpoints/SALoadbalanceEndpointSerializer.java @@ -1,109 +1,109 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.synapse.config.xml.endpoints; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMAbstractFactory; import org.apache.synapse.endpoints.Endpoint; import org.apache.synapse.endpoints.SALoadbalanceEndpoint; import org.apache.synapse.endpoints.dispatch.Dispatcher; import org.apache.synapse.endpoints.dispatch.SoapSessionDispatcher; import org.apache.synapse.endpoints.dispatch.SimpleClientSessionDispatcher; import org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher; import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm; import org.apache.synapse.endpoints.algorithms.RoundRobin; import org.apache.synapse.SynapseException; import org.apache.synapse.Constants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.List; public class SALoadbalanceEndpointSerializer implements EndpointSerializer { private static final Log log = LogFactory.getLog(SALoadbalanceEndpointSerializer.class); private OMFactory fac = null; public OMElement serializeEndpoint(Endpoint endpoint) { if (!(endpoint instanceof SALoadbalanceEndpoint)) { handleException("Invalid endpoint type for serializing. " + "Expected: SALoadbalanceEndpoint Found: " + endpoint.getClass().getName()); } SALoadbalanceEndpoint loadbalanceEndpoint = (SALoadbalanceEndpoint) endpoint; fac = OMAbstractFactory.getOMFactory(); OMElement endpointElement = fac.createOMElement("endpoint", Constants.SYNAPSE_OMNAMESPACE); String name = loadbalanceEndpoint.getName(); if (name != null) { endpointElement.addAttribute("name", name, null); } Dispatcher dispatcher = loadbalanceEndpoint.getDispatcher(); if (dispatcher instanceof SoapSessionDispatcher) { OMElement sessionElement = fac.createOMElement("session", Constants.SYNAPSE_OMNAMESPACE); sessionElement.addAttribute("type", "soap", null); endpointElement.addChild(sessionElement); } else if (dispatcher instanceof HttpSessionDispatcher) { OMElement sessionElement = fac.createOMElement("session", Constants.SYNAPSE_OMNAMESPACE); sessionElement.addAttribute("type", "http", null); endpointElement.addChild(sessionElement); } else if (dispatcher instanceof SimpleClientSessionDispatcher) { OMElement sessionElement = fac.createOMElement("session", Constants.SYNAPSE_OMNAMESPACE); - sessionElement.addAttribute("type", "clientSession", null); + sessionElement.addAttribute("type", "simpleClientSession", null); endpointElement.addChild(sessionElement); } OMElement loadbalanceElement = fac.createOMElement("loadbalance", Constants.SYNAPSE_OMNAMESPACE); endpointElement.addChild(loadbalanceElement); LoadbalanceAlgorithm algorithm = loadbalanceEndpoint.getAlgorithm(); String algorithmName = "roundRobin"; if (algorithm instanceof RoundRobin) { algorithmName = "roundRobin"; } loadbalanceElement.addAttribute("algorithm", algorithmName, null); List endpoints = loadbalanceEndpoint.getEndpoints(); for (int i = 0; i < endpoints.size(); i++) { Endpoint childEndpoint = (Endpoint) endpoints.get(i); EndpointSerializer serializer = EndpointAbstractSerializer. getEndpointSerializer(childEndpoint); OMElement aeElement = serializer.serializeEndpoint(childEndpoint); loadbalanceElement.addChild(aeElement); } return endpointElement; } private void handleException(String msg) { log.error(msg); throw new SynapseException(msg); } }
true
true
public OMElement serializeEndpoint(Endpoint endpoint) { if (!(endpoint instanceof SALoadbalanceEndpoint)) { handleException("Invalid endpoint type for serializing. " + "Expected: SALoadbalanceEndpoint Found: " + endpoint.getClass().getName()); } SALoadbalanceEndpoint loadbalanceEndpoint = (SALoadbalanceEndpoint) endpoint; fac = OMAbstractFactory.getOMFactory(); OMElement endpointElement = fac.createOMElement("endpoint", Constants.SYNAPSE_OMNAMESPACE); String name = loadbalanceEndpoint.getName(); if (name != null) { endpointElement.addAttribute("name", name, null); } Dispatcher dispatcher = loadbalanceEndpoint.getDispatcher(); if (dispatcher instanceof SoapSessionDispatcher) { OMElement sessionElement = fac.createOMElement("session", Constants.SYNAPSE_OMNAMESPACE); sessionElement.addAttribute("type", "soap", null); endpointElement.addChild(sessionElement); } else if (dispatcher instanceof HttpSessionDispatcher) { OMElement sessionElement = fac.createOMElement("session", Constants.SYNAPSE_OMNAMESPACE); sessionElement.addAttribute("type", "http", null); endpointElement.addChild(sessionElement); } else if (dispatcher instanceof SimpleClientSessionDispatcher) { OMElement sessionElement = fac.createOMElement("session", Constants.SYNAPSE_OMNAMESPACE); sessionElement.addAttribute("type", "clientSession", null); endpointElement.addChild(sessionElement); } OMElement loadbalanceElement = fac.createOMElement("loadbalance", Constants.SYNAPSE_OMNAMESPACE); endpointElement.addChild(loadbalanceElement); LoadbalanceAlgorithm algorithm = loadbalanceEndpoint.getAlgorithm(); String algorithmName = "roundRobin"; if (algorithm instanceof RoundRobin) { algorithmName = "roundRobin"; } loadbalanceElement.addAttribute("algorithm", algorithmName, null); List endpoints = loadbalanceEndpoint.getEndpoints(); for (int i = 0; i < endpoints.size(); i++) { Endpoint childEndpoint = (Endpoint) endpoints.get(i); EndpointSerializer serializer = EndpointAbstractSerializer. getEndpointSerializer(childEndpoint); OMElement aeElement = serializer.serializeEndpoint(childEndpoint); loadbalanceElement.addChild(aeElement); } return endpointElement; }
public OMElement serializeEndpoint(Endpoint endpoint) { if (!(endpoint instanceof SALoadbalanceEndpoint)) { handleException("Invalid endpoint type for serializing. " + "Expected: SALoadbalanceEndpoint Found: " + endpoint.getClass().getName()); } SALoadbalanceEndpoint loadbalanceEndpoint = (SALoadbalanceEndpoint) endpoint; fac = OMAbstractFactory.getOMFactory(); OMElement endpointElement = fac.createOMElement("endpoint", Constants.SYNAPSE_OMNAMESPACE); String name = loadbalanceEndpoint.getName(); if (name != null) { endpointElement.addAttribute("name", name, null); } Dispatcher dispatcher = loadbalanceEndpoint.getDispatcher(); if (dispatcher instanceof SoapSessionDispatcher) { OMElement sessionElement = fac.createOMElement("session", Constants.SYNAPSE_OMNAMESPACE); sessionElement.addAttribute("type", "soap", null); endpointElement.addChild(sessionElement); } else if (dispatcher instanceof HttpSessionDispatcher) { OMElement sessionElement = fac.createOMElement("session", Constants.SYNAPSE_OMNAMESPACE); sessionElement.addAttribute("type", "http", null); endpointElement.addChild(sessionElement); } else if (dispatcher instanceof SimpleClientSessionDispatcher) { OMElement sessionElement = fac.createOMElement("session", Constants.SYNAPSE_OMNAMESPACE); sessionElement.addAttribute("type", "simpleClientSession", null); endpointElement.addChild(sessionElement); } OMElement loadbalanceElement = fac.createOMElement("loadbalance", Constants.SYNAPSE_OMNAMESPACE); endpointElement.addChild(loadbalanceElement); LoadbalanceAlgorithm algorithm = loadbalanceEndpoint.getAlgorithm(); String algorithmName = "roundRobin"; if (algorithm instanceof RoundRobin) { algorithmName = "roundRobin"; } loadbalanceElement.addAttribute("algorithm", algorithmName, null); List endpoints = loadbalanceEndpoint.getEndpoints(); for (int i = 0; i < endpoints.size(); i++) { Endpoint childEndpoint = (Endpoint) endpoints.get(i); EndpointSerializer serializer = EndpointAbstractSerializer. getEndpointSerializer(childEndpoint); OMElement aeElement = serializer.serializeEndpoint(childEndpoint); loadbalanceElement.addChild(aeElement); } return endpointElement; }
diff --git a/aura/src/test/java/org/auraframework/perfTest/RerenderMarksUITest.java b/aura/src/test/java/org/auraframework/perfTest/RerenderMarksUITest.java index b0dbf152dd..fa03e6160c 100644 --- a/aura/src/test/java/org/auraframework/perfTest/RerenderMarksUITest.java +++ b/aura/src/test/java/org/auraframework/perfTest/RerenderMarksUITest.java @@ -1,103 +1,103 @@ /* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.perfTest; import java.util.Map; import org.auraframework.system.AuraContext.Mode; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * * Automation to verify Jiffy marks for rerender cycle. */ public class RerenderMarksUITest extends PerfMetricsTestCase { public RerenderMarksUITest(String name){ super(name); } /** * Simple scenario where a top level attribute change initiates a rerender cycle. * Subsequent rerender of the same component should also be logged in Jiffy. * @throws Exception */ public void testRerenderMarksHaveComponentName() throws Exception{ Map<String, String> logStats = Maps.newHashMap(); open("/performanceTest/ui_button.cmp", Mode.CADENCE); clearStats(); WebElement button = getDriver().findElement(By.cssSelector("button[class~='uiButton']")); button.click(); waitForElementTextPresent(getDriver().findElement(By.cssSelector("button[class~='uiButton']")), "clicked"); logStats.putAll(getJiffyStats(Lists.newArrayList("Rerendering-2: ['markup://ui:button']"))); assertFalse("Did not find Jiffy marks with component information for Rerender cycle.", logStats.isEmpty()); logStats.clear(); button.click(); logStats.putAll(getJiffyStats(Lists.newArrayList("Rerendering-3: ['markup://ui:button']"))); assertFalse("Did not mark multiple Rerender of same component.", logStats.isEmpty()); } /** * Scenario where * 1. Top level attribute change causes a rerender * 2. Attribute value change causes multiple component rerender * 3. Server action where no component rerender is caused. * @throws Exception * * Re-enable after bug W-1935316 is fixed */ - public void _testRerenderMarksHaveAllComponentNames() throws Exception{ + public void testRerenderMarksHaveAllComponentNames() throws Exception{ Map<String, String> logStats = Maps.newHashMap(); open("/performanceTest/perfApp.app", Mode.CADENCE); clearStats(); //Mark an attribute as dirty at the root component WebElement button = getDriver().findElement(By.cssSelector("button[class~='bkgColor']")); button.click(); waitForElementPresent(getDriver().findElement(By.cssSelector("tr[class~='grey']"))); logStats.putAll(getJiffyStats(Lists.newArrayList("Rerendering-3: ['markup://performanceTest:perfApp']"))); assertFalse("Rerender of root component not marked in Jiffy.", logStats.isEmpty()); logStats.clear(); //Make a value change to cause multiple component rerender, the jiffy mark should have qualified names of the components WebElement innerButton = getDriver().findElement(By.cssSelector("button[class~='changeIteratonIndex']")); innerButton.click(); logStats.putAll(getJiffyStats(Lists.newArrayList("Rerendering-4: ['markup://performanceTest:perfApp','markup://aura:iteration','markup://aura:iteration','markup://aura:iteration']"))); assertFalse("Multiple component Rerender should be marked with all componentNames.", logStats.isEmpty()); logStats.clear(); //An action that does not result in a component rerender innerButton = getDriver().findElement(By.cssSelector("button[class~='simpleServerAction']")); innerButton.click(); waitForCondition("return $A.getRoot()._simpleServerActionComplete"); logStats.putAll(getJiffyStats(Lists.newArrayList("Rerendering-5: []"))); assertFalse("Server action that causes no components to rerender should be logged but with no component names.", logStats.isEmpty()); //Server action should cause no rerender and hence rerender mark should be 0 assertEquals("0", logStats.get("Rerendering-5: []")); logStats.clear(); } }
true
true
public void _testRerenderMarksHaveAllComponentNames() throws Exception{ Map<String, String> logStats = Maps.newHashMap(); open("/performanceTest/perfApp.app", Mode.CADENCE); clearStats(); //Mark an attribute as dirty at the root component WebElement button = getDriver().findElement(By.cssSelector("button[class~='bkgColor']")); button.click(); waitForElementPresent(getDriver().findElement(By.cssSelector("tr[class~='grey']"))); logStats.putAll(getJiffyStats(Lists.newArrayList("Rerendering-3: ['markup://performanceTest:perfApp']"))); assertFalse("Rerender of root component not marked in Jiffy.", logStats.isEmpty()); logStats.clear(); //Make a value change to cause multiple component rerender, the jiffy mark should have qualified names of the components WebElement innerButton = getDriver().findElement(By.cssSelector("button[class~='changeIteratonIndex']")); innerButton.click(); logStats.putAll(getJiffyStats(Lists.newArrayList("Rerendering-4: ['markup://performanceTest:perfApp','markup://aura:iteration','markup://aura:iteration','markup://aura:iteration']"))); assertFalse("Multiple component Rerender should be marked with all componentNames.", logStats.isEmpty()); logStats.clear(); //An action that does not result in a component rerender innerButton = getDriver().findElement(By.cssSelector("button[class~='simpleServerAction']")); innerButton.click(); waitForCondition("return $A.getRoot()._simpleServerActionComplete"); logStats.putAll(getJiffyStats(Lists.newArrayList("Rerendering-5: []"))); assertFalse("Server action that causes no components to rerender should be logged but with no component names.", logStats.isEmpty()); //Server action should cause no rerender and hence rerender mark should be 0 assertEquals("0", logStats.get("Rerendering-5: []")); logStats.clear(); }
public void testRerenderMarksHaveAllComponentNames() throws Exception{ Map<String, String> logStats = Maps.newHashMap(); open("/performanceTest/perfApp.app", Mode.CADENCE); clearStats(); //Mark an attribute as dirty at the root component WebElement button = getDriver().findElement(By.cssSelector("button[class~='bkgColor']")); button.click(); waitForElementPresent(getDriver().findElement(By.cssSelector("tr[class~='grey']"))); logStats.putAll(getJiffyStats(Lists.newArrayList("Rerendering-3: ['markup://performanceTest:perfApp']"))); assertFalse("Rerender of root component not marked in Jiffy.", logStats.isEmpty()); logStats.clear(); //Make a value change to cause multiple component rerender, the jiffy mark should have qualified names of the components WebElement innerButton = getDriver().findElement(By.cssSelector("button[class~='changeIteratonIndex']")); innerButton.click(); logStats.putAll(getJiffyStats(Lists.newArrayList("Rerendering-4: ['markup://performanceTest:perfApp','markup://aura:iteration','markup://aura:iteration','markup://aura:iteration']"))); assertFalse("Multiple component Rerender should be marked with all componentNames.", logStats.isEmpty()); logStats.clear(); //An action that does not result in a component rerender innerButton = getDriver().findElement(By.cssSelector("button[class~='simpleServerAction']")); innerButton.click(); waitForCondition("return $A.getRoot()._simpleServerActionComplete"); logStats.putAll(getJiffyStats(Lists.newArrayList("Rerendering-5: []"))); assertFalse("Server action that causes no components to rerender should be logged but with no component names.", logStats.isEmpty()); //Server action should cause no rerender and hence rerender mark should be 0 assertEquals("0", logStats.get("Rerendering-5: []")); logStats.clear(); }
diff --git a/src/main/java/org/mapdb/BTreeMap.java b/src/main/java/org/mapdb/BTreeMap.java index 23043a2b..bf0391ad 100644 --- a/src/main/java/org/mapdb/BTreeMap.java +++ b/src/main/java/org/mapdb/BTreeMap.java @@ -1,2739 +1,2737 @@ /* * Copyright (c) 2012 Jan Kotek * * 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. */ /* * NOTE: some code (and javadoc) used in this class * comes from Apache Harmony with following copyright: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package org.mapdb; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentNavigableMap; /** * A scalable concurrent {@link ConcurrentNavigableMap} implementation. * The map is sorted according to the {@linkplain Comparable natural * ordering} of its keys, or by a {@link Comparator} provided at map * creation time. * * Insertion, removal, * update, and access operations safely execute concurrently by * multiple threads. Iterators are <i>weakly consistent</i>, returning * elements reflecting the state of the map at some point at or since * the creation of the iterator. They do <em>not</em> throw {@link * ConcurrentModificationException}, and may proceed concurrently with * other operations. Ascending key ordered views and their iterators * are faster than descending ones. * * It is possible to obtain <i>consistent</i> iterator by using <code>snapshot()</code> * method. * * All <tt>Map.Entry</tt> pairs returned by methods in this class * and its views represent snapshots of mappings at the time they were * produced. They do <em>not</em> support the <tt>Entry.setValue</tt> * method. (Note however that it is possible to change mappings in the * associated map using <tt>put</tt>, <tt>putIfAbsent</tt>, or * <tt>replace</tt>, depending on exactly which effect you need.) * * This collection has optional size counter. If this is enabled Map size is * kept in {@link Atomic.Long} variable. Keeping counter brings considerable * overhead on inserts and removals. * If the size counter is not enabled the <tt>size</tt> method is <em>not</em> a constant-time operation. * Determining the current number of elements requires a traversal of the elements. * * Additionally, the bulk operations <tt>putAll</tt>, <tt>equals</tt>, and * <tt>clear</tt> are <em>not</em> guaranteed to be performed * atomically. For example, an iterator operating concurrently with a * <tt>putAll</tt> operation might view only some of the added * elements. NOTE: there is an optional * * This class and its views and iterators implement all of the * <em>optional</em> methods of the {@link Map} and {@link Iterator} * interfaces. Like most other concurrent collections, this class does * <em>not</em> permit the use of <tt>null</tt> keys or values because some * null return values cannot be reliably distinguished from the absence of * elements. * * Theoretical design of BTreeMap is based on <a href="http://www.cs.cornell.edu/courses/cs4411/2009sp/blink.pdf">paper</a> * from Philip L. Lehman and S. Bing Yao. More practical aspects of BTreeMap implementation are based on <a href="http://www.doc.ic.ac.uk/~td202/">notes</a> * and <a href="http://www.doc.ic.ac.uk/~td202/btree/">demo application</a> from Thomas Dinsdale-Young. * B-Linked-Tree used here does not require locking for read. Updates and inserts locks only one, two or three nodes. * This B-Linked-Tree structure does not support removal well, entry deletion does not collapse tree nodes. Massive * deletion causes empty nodes and performance lost. There is workaround in form of compaction process, but it is not * implemented yet. * * @author Jan Kotek * @author some parts by Doug Lea and JSR-166 group */ @SuppressWarnings({ "unchecked", "rawtypes" }) //TODO better tests for BTreeMap without values (set) public class BTreeMap<K,V> extends AbstractMap<K,V> implements ConcurrentNavigableMap<K,V>, Bind.MapWithModificationListener<K,V>{ protected static final int B_TREE_NODE_LEAF_LR = 180; protected static final int B_TREE_NODE_LEAF_L = 181; protected static final int B_TREE_NODE_LEAF_R = 182; protected static final int B_TREE_NODE_LEAF_C = 183; protected static final int B_TREE_NODE_DIR_LR = 184; protected static final int B_TREE_NODE_DIR_L = 185; protected static final int B_TREE_NODE_DIR_R = 186; protected static final int B_TREE_NODE_DIR_C = 187; /** recid under which reference to rootRecid is stored */ protected final long rootRecidRef; /** Serializer used to convert keys from/into binary form. * TODO delta packing on BTree keys*/ protected final BTreeKeySerializer keySerializer; /** Serializer used to convert keys from/into binary form*/ protected final Serializer<V> valueSerializer; /** keys are sorted by this*/ protected final Comparator comparator; /** holds node level locks*/ protected final LongConcurrentHashMap<Thread> nodeLocks = new LongConcurrentHashMap<Thread>(); /** maximal node size allowed in this BTree*/ protected final int maxNodeSize; /** DB Engine in which entries are persisted */ protected final Engine engine; /** is this a Map or Set? if false, entries do not have values, only keys are allowed*/ protected final boolean hasValues; /** store values as part of BTree nodes */ protected final boolean valsOutsideNodes; private final KeySet keySet; private final EntrySet entrySet = new EntrySet(this); private final Values values = new Values(this); private final ConcurrentNavigableMap<K,V> descendingMap = new DescendingMap(this, null,true, null, false); protected final Atomic.Long counter; /** hack used for DB Catalog*/ protected static SortedMap<String, Object> preinitCatalog(DB db) { Long rootRef = db.getEngine().get(Engine.CATALOG_RECID, Serializer.LONG); if(rootRef==null){ if(db.getEngine().isReadOnly()) return Collections.unmodifiableSortedMap(new TreeMap<String, Object>()); NodeSerializer rootSerializer = new NodeSerializer(false,BTreeKeySerializer.STRING, db.getDefaultSerializer(),Utils.COMPARABLE_COMPARATOR); BNode root = new LeafNode(new Object[]{null, null}, new Object[]{}, 0); rootRef = db.getEngine().put(root, rootSerializer); db.getEngine().update(Engine.CATALOG_RECID,rootRef, Serializer.LONG); } return new BTreeMap<String, Object>(db.engine,Engine.CATALOG_RECID,32,false,0, BTreeKeySerializer.STRING, db.getDefaultSerializer(), (Comparator)Utils.COMPARABLE_COMPARATOR); } /** if <code>valsOutsideNodes</code> is true, this class is used instead of values. * It contains reference to actual value. It also supports assertions from preventing it to leak outside of Map*/ protected static final class ValRef{ /** reference to actual value */ final long recid; public ValRef(long recid) { this.recid = recid; } @Override public boolean equals(Object obj) { throw new InternalError(); } @Override public int hashCode() { throw new InternalError(); } @Override public String toString() { return "BTreeMap-ValRer["+recid+"]"; } } /** common interface for BTree node */ protected interface BNode{ boolean isLeaf(); Object[] keys(); Object[] vals(); Object highKey(); long[] child(); long next(); } protected final static class DirNode implements BNode{ final Object[] keys; final long[] child; DirNode(Object[] keys, long[] child) { this.keys = keys; this.child = child; } DirNode(Object[] keys, List<Long> child) { this.keys = keys; this.child = new long[child.size()]; for(int i=0;i<child.size();i++){ this.child[i] = child.get(i); } } @Override public boolean isLeaf() { return false;} @Override public Object[] keys() { return keys;} @Override public Object[] vals() { return null;} @Override public Object highKey() {return keys[keys.length-1];} @Override public long[] child() { return child;} @Override public long next() {return child[child.length-1];} @Override public String toString(){ return "Dir(K"+Arrays.toString(keys)+", C"+Arrays.toString(child)+")"; } } protected final static class LeafNode implements BNode{ final Object[] keys; final Object[] vals; final long next; LeafNode(Object[] keys, Object[] vals, long next) { this.keys = keys; this.vals = vals; this.next = next; assert(vals==null||keys.length == vals.length+2); } @Override public boolean isLeaf() { return true;} @Override public Object[] keys() { return keys;} @Override public Object[] vals() { return vals;} @Override public Object highKey() {return keys[keys.length-1];} @Override public long[] child() { return null;} @Override public long next() {return next;} @Override public String toString(){ return "Leaf(K"+Arrays.toString(keys)+", V"+Arrays.toString(vals)+", L="+next+")"; } } protected final Serializer<BNode> nodeSerializer; protected static class NodeSerializer implements Serializer<BNode>{ protected final boolean hasValues; protected final boolean valsOutsideNodes; protected final BTreeKeySerializer keySerializer; protected final Serializer valueSerializer; protected final Comparator comparator; public NodeSerializer(boolean valsOutsideNodes, BTreeKeySerializer keySerializer, Serializer valueSerializer, Comparator comparator) { assert(keySerializer!=null); assert(comparator!=null); this.hasValues = valueSerializer!=null; this.valsOutsideNodes = valsOutsideNodes; this.keySerializer = keySerializer; this.valueSerializer = valueSerializer; this.comparator = comparator; } @Override public void serialize(DataOutput out, BNode value) throws IOException { final boolean isLeaf = value.isLeaf(); //first byte encodes if is leaf (first bite) and length (last seven bites) if(value.keys().length>255) throw new InternalError(); if(!isLeaf && value.child().length!= value.keys().length) throw new InternalError(); if(isLeaf && hasValues && value.vals().length!= value.keys().length-2) throw new InternalError(); //check node integrity in paranoid mode if(CC.PARANOID){ int len = value.keys().length; for(int i=value.keys()[0]==null?2:1; i<(value.keys()[len-1]==null?len-1:len); i++){ int comp = comparator.compare(value.keys()[i-1], value.keys()[i]); int limit = i==len-1 ? 1:0 ; if(comp>=limit){ throw new AssertionError("BTreeNode format error, wrong key order at #"+i+"\n"+value); } } } final boolean left = value.keys()[0] == null; final boolean right = value.keys()[value.keys().length-1] == null; final int header; if(isLeaf){ if(right){ if(left) header = B_TREE_NODE_LEAF_LR; else header = B_TREE_NODE_LEAF_R; }else{ if(left) header = B_TREE_NODE_LEAF_L; else header = B_TREE_NODE_LEAF_C; } }else{ if(right){ if(left) header = B_TREE_NODE_DIR_LR; else header = B_TREE_NODE_DIR_R; }else{ if(left) header = B_TREE_NODE_DIR_L; else header = B_TREE_NODE_DIR_C; } } out.write(header); out.write(value.keys().length); //longs go first, so it is possible to reconstruct tree without serializer if(isLeaf){ Utils.packLong(out, ((LeafNode) value).next); }else{ for(long child : ((DirNode)value).child) Utils.packLong(out, child); } keySerializer.serialize(out,left?1:0, right?value.keys().length-1:value.keys().length, value.keys()); if(isLeaf && hasValues){ for(Object val:value.vals()){ assert(val!=null); if(valsOutsideNodes){ long recid = ((ValRef)val).recid; Utils.packLong(out, recid); }else{ valueSerializer.serialize(out, val); } } } } @Override public BNode deserialize(DataInput in, int available) throws IOException { final int header = in.readUnsignedByte(); final int size = in.readUnsignedByte(); //first bite indicates leaf final boolean isLeaf = header == B_TREE_NODE_LEAF_C || header == B_TREE_NODE_LEAF_L || header == B_TREE_NODE_LEAF_LR || header == B_TREE_NODE_LEAF_R; final int start = (header==B_TREE_NODE_LEAF_L || header == B_TREE_NODE_LEAF_LR || header==B_TREE_NODE_DIR_L || header == B_TREE_NODE_DIR_LR) ? 1:0; final int end = (header==B_TREE_NODE_LEAF_R || header == B_TREE_NODE_LEAF_LR || header==B_TREE_NODE_DIR_R || header == B_TREE_NODE_DIR_LR) ? size-1:size; if(isLeaf){ long next = Utils.unpackLong(in); Object[] keys = keySerializer.deserialize(in, start,end,size); if(keys.length!=size) throw new InternalError(); Object[] vals = null; if(hasValues){ vals = new Object[size-2]; for(int i=0;i<size-2;i++){ if(valsOutsideNodes){ long recid = Utils.unpackLong(in); vals[i] = recid==0? null: new ValRef(recid); }else{ vals[i] = valueSerializer.deserialize(in, -1); } } } return new LeafNode(keys, vals, next); }else{ long[] child = new long[size]; for(int i=0;i<size;i++) child[i] = Utils.unpackLong(in); Object[] keys = keySerializer.deserialize(in, start,end,size); if(keys.length!=size) throw new InternalError(); return new DirNode(keys, child); } } }; /** Constructor used to create new BTreeMap. * * @param engine used for persistence * @param rootRecidRef reference to root recid * @param maxNodeSize maximal BTree Node size. Node will split if number of entries is higher * @param valsOutsideNodes Store Values outside of BTree Nodes in separate record? * @param counterRecid recid under which `Atomic.Long` is stored, or `0` for no counter * @param keySerializer Serializer used for keys. May be null for default value. TODO delta packing * @param valueSerializer Serializer used for values. May be null for default value * @param comparator Comparator to sort keys in this BTree, may be null. */ public BTreeMap(Engine engine, long rootRecidRef, int maxNodeSize, boolean valsOutsideNodes, long counterRecid, BTreeKeySerializer<K> keySerializer, Serializer<V> valueSerializer, Comparator<K> comparator) { if(maxNodeSize%2!=0) throw new IllegalArgumentException("maxNodeSize must be dividable by 2"); if(maxNodeSize<6) throw new IllegalArgumentException("maxNodeSize too low"); if(maxNodeSize>126) throw new IllegalArgumentException("maxNodeSize too high"); if(rootRecidRef<=0||counterRecid<0) throw new IllegalArgumentException(); if(keySerializer==null) throw new NullPointerException(); if(comparator==null) throw new NullPointerException(); SerializerBase.assertSerializable(keySerializer); SerializerBase.assertSerializable(valueSerializer); SerializerBase.assertSerializable(comparator); this.rootRecidRef = rootRecidRef; this.hasValues = valueSerializer!=null; this.valsOutsideNodes = valsOutsideNodes; this.engine = engine; this.maxNodeSize = maxNodeSize; this.comparator = comparator; //TODO when delta packing implemented, add assertion for COMPARABLE_COMPARATOR this.keySerializer = keySerializer; this.valueSerializer = valueSerializer; this.nodeSerializer = new NodeSerializer(valsOutsideNodes,keySerializer,valueSerializer,comparator); this.keySet = new KeySet(this, hasValues); if(counterRecid!=0){ this.counter = new Atomic.Long(engine,counterRecid); Bind.size(this,counter); }else{ this.counter = null; } } /** creates empty root node and returns recid of its reference*/ static protected long createRootRef(Engine engine, BTreeKeySerializer keySer, Serializer valueSer, Comparator comparator){ final LeafNode emptyRoot = new LeafNode(new Object[]{null, null}, new Object[]{}, 0); //empty root is serializer simpler way, so we can use dummy values long rootRecidVal = engine.put(emptyRoot, new NodeSerializer(false,keySer, valueSer, comparator)); return engine.put(rootRecidVal,Serializer.LONG); } /** * Find the first children node with a key equal or greater than the given key. * If all items are smaller it returns `keys.length` */ protected final int findChildren(final Object key, final Object[] keys) { int left = 0; if(keys[0] == null) left++; int right = keys[keys.length-1] == null ? keys.length-1 : keys.length; int middle; // binary search while (true) { middle = (left + right) / 2; if(keys[middle]==null) return middle; //null is positive infinitive if (comparator.compare(keys[middle], key) < 0) { left = middle + 1; } else { right = middle; } if (left >= right) { return right; } } } @Override public V get(Object key){ if(key==null) throw new NullPointerException(); K v = (K) key; final long rootRecid = engine.get(rootRecidRef, Serializer.LONG); long current = rootRecid; BNode A = engine.get(current, nodeSerializer); //dive until leaf while(!A.isLeaf()){ current = nextDir((DirNode) A, v); A = engine.get(current, nodeSerializer); } //now at leaf level LeafNode leaf = (LeafNode) A; int pos = findChildren(v, leaf.keys); while(pos == leaf.keys.length){ //follow next link on leaf until necessary leaf = (LeafNode) engine.get(leaf.next, nodeSerializer); pos = findChildren(v, leaf.keys); } if(pos==leaf.keys.length-1){ return null; //last key is always deleted } //finish search if(leaf.keys[pos]!=null && 0==comparator.compare(v,leaf.keys[pos])){ Object ret = (hasValues? leaf.vals[pos-1] : Utils.EMPTY_STRING); return valExpand(ret); }else return null; } protected V valExpand(Object ret) { if(valsOutsideNodes && ret!=null) { long recid = ((ValRef)ret).recid; ret = engine.get(recid, valueSerializer); } return (V) ret; } protected long nextDir(DirNode d, Object key) { int pos = findChildren(key, d.keys) - 1; if(pos<0) pos = 0; return d.child[pos]; } @Override public V put(K key, V value){ if(key==null||value==null) throw new NullPointerException(); return put2(key,value, false); } protected V put2(K v, V value2, final boolean putOnlyIfAbsent){ if(v == null) throw new IllegalArgumentException("null key"); if(value2 == null) throw new IllegalArgumentException("null value"); Utils.checkMapValueIsNotCollecion(value2); V value = value2; if(valsOutsideNodes){ long recid = engine.put(value2, valueSerializer); value = (V) new ValRef(recid); } int stackPos = -1; long[] stackVals = new long[4]; final long rootRecid = engine.get(rootRecidRef, Serializer.LONG); long current = rootRecid; BNode A = engine.get(current, nodeSerializer); while(!A.isLeaf()){ long t = current; current = nextDir((DirNode) A, v); if(current == A.child()[A.child().length-1]){ //is link, do nothing }else{ //stack push t stackPos++; if(stackVals.length == stackPos) //grow if needed stackVals = Arrays.copyOf(stackVals, stackVals.length*2); stackVals[stackPos] = t; } A = engine.get(current, nodeSerializer); } int level = 1; long p=0; try{ while(true){ boolean found; do{ Utils.lock(nodeLocks, current); found = true; A = engine.get(current, nodeSerializer); int pos = findChildren(v, A.keys()); if(pos<A.keys().length-1 && v!=null && A.keys()[pos]!=null && 0==comparator.compare(v,A.keys()[pos])){ Object oldVal = (hasValues? A.vals()[pos-1] : Utils.EMPTY_STRING); if(putOnlyIfAbsent){ //is not absent, so quit Utils.unlock(nodeLocks, current); if(CC.PARANOID) Utils.assertNoLocks(nodeLocks); - V ret = valExpand(oldVal); - notify(v,ret, value2); - return ret; + return valExpand(oldVal); } //insert new Object[] vals = null; if(hasValues){ vals = Arrays.copyOf(A.vals(), A.vals().length); vals[pos-1] = value; } A = new LeafNode(Arrays.copyOf(A.keys(), A.keys().length), vals, ((LeafNode)A).next); engine.update(current, A, nodeSerializer); //already in here Utils.unlock(nodeLocks, current); if(CC.PARANOID) Utils.assertNoLocks(nodeLocks); V ret = valExpand(oldVal); notify(v,ret, value2); return ret; } if(A.highKey() != null && comparator.compare(v, A.highKey())>0){ //follow link until necessary Utils.unlock(nodeLocks, current); found = false; int pos2 = findChildren(v, A.keys()); while(A!=null && pos2 == A.keys().length){ //TODO lock? long next = A.next(); if(next==0) break; current = next; A = engine.get(current, nodeSerializer); pos2 = findChildren(v, A.keys()); } } }while(!found); // can be new item inserted into A without splitting it? if(A.keys().length - (A.isLeaf()?2:1)<maxNodeSize){ int pos = findChildren(v, A.keys()); Object[] keys = Utils.arrayPut(A.keys(), pos, v); if(A.isLeaf()){ Object[] vals = hasValues? Utils.arrayPut(A.vals(), pos-1, value): null; LeafNode n = new LeafNode(keys, vals, ((LeafNode)A).next); engine.update(current, n, nodeSerializer); }else{ if(p==0) throw new InternalError(); long[] child = Utils.arrayLongPut(A.child(), pos, p); DirNode d = new DirNode(keys, child); engine.update(current, d, nodeSerializer); } Utils.unlock(nodeLocks, current); if(CC.PARANOID) Utils.assertNoLocks(nodeLocks); notify(v, null, value2); return null; }else{ //node is not safe, it requires splitting final boolean isRoot = (current == rootRecid); final int pos = findChildren(v, A.keys()); final Object[] keys = Utils.arrayPut(A.keys(), pos, v); final Object[] vals = (A.isLeaf() && hasValues)? Utils.arrayPut(A.vals(), pos-1, value) : null; final long[] child = A.isLeaf()? null : Utils.arrayLongPut(A.child(), pos, p); final int splitPos = keys.length/2; BNode B; if(A.isLeaf()){ Object[] vals2 = null; if(hasValues){ vals2 = Arrays.copyOfRange(vals, splitPos, vals.length); } B = new LeafNode( Arrays.copyOfRange(keys, splitPos, keys.length), vals2, ((LeafNode)A).next); }else{ B = new DirNode(Arrays.copyOfRange(keys, splitPos, keys.length), Arrays.copyOfRange(child, splitPos, keys.length)); } long q = engine.put(B, nodeSerializer); if(A.isLeaf()){ // splitPos+1 is there so A gets new high value (key) Object[] keys2 = Arrays.copyOf(keys, splitPos+2); keys2[keys2.length-1] = keys2[keys2.length-2]; Object[] vals2 = null; if(hasValues){ vals2 = Arrays.copyOf(vals, splitPos); } //TODO check high/low keys overlap A = new LeafNode(keys2, vals2, q); }else{ long[] child2 = Arrays.copyOf(child, splitPos+1); child2[splitPos] = q; A = new DirNode(Arrays.copyOf(keys, splitPos+1), child2); } engine.update(current, A, nodeSerializer); if(!isRoot){ Utils.unlock(nodeLocks, current); p = q; v = (K) A.highKey(); level = level+1; if(stackPos!=-1){ //if stack is not empty current = stackVals[stackPos--]; }else{ current = -1; //TODO pointer to left most node at level level throw new InternalError(); } }else{ BNode R = new DirNode( new Object[]{A.keys()[0], A.highKey(), B.highKey()}, new long[]{current,q, 0}); long newRootRecid = engine.put(R, nodeSerializer); //TODO tree root locking engine.update(rootRecidRef, newRootRecid, Serializer.LONG); //TODO update tree levels Utils.unlock(nodeLocks, current); if(CC.PARANOID) Utils.assertNoLocks(nodeLocks); notify(v, null, value2); return null; } } } }catch(RuntimeException e){ Utils.unlockAll(nodeLocks); throw e; }catch(Exception e){ Utils.unlockAll(nodeLocks); throw new RuntimeException(e); } } protected static class BTreeIterator{ final BTreeMap m; LeafNode currentLeaf; Object lastReturnedKey; int currentPos; final Object hi; final boolean hiInclusive; /** unbounded iterator*/ BTreeIterator(BTreeMap m){ this.m = m; hi=null; hiInclusive=false; pointToStart(); } /** bounder iterator, args may be null for partially bounded*/ BTreeIterator(BTreeMap m, Object lo, boolean loInclusive, Object hi, boolean hiInclusive){ this.m = m; if(lo==null){ pointToStart(); }else{ Fun.Tuple2<Integer, LeafNode> l = m.findLargerNode(lo, loInclusive); currentPos = l!=null? l.a : -1; currentLeaf = l!=null ? l.b : null; } this.hi = hi; this.hiInclusive = hiInclusive; if(hi!=null && currentLeaf!=null){ //check in bounds Object key = currentLeaf.keys[currentPos]; int c = m.comparator.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)){ //out of high bound currentLeaf=null; currentPos=-1; } } } private void pointToStart() { //find left-most leaf final long rootRecid = m.engine.get(m.rootRecidRef, Serializer.LONG); BNode node = (BNode) m.engine.get(rootRecid, m.nodeSerializer); while(!node.isLeaf()){ node = (BNode) m.engine.get(node.child()[0], m.nodeSerializer); } currentLeaf = (LeafNode) node; currentPos = 1; while(currentLeaf.keys.length==2){ //follow link until leaf is not empty if(currentLeaf.next == 0){ currentLeaf = null; return; } currentLeaf = (LeafNode) m.engine.get(currentLeaf.next, m.nodeSerializer); } } public boolean hasNext(){ return currentLeaf!=null; } public void remove(){ if(lastReturnedKey==null) throw new IllegalStateException(); m.remove(lastReturnedKey); lastReturnedKey = null; } protected void advance(){ if(currentLeaf==null) return; lastReturnedKey = currentLeaf.keys[currentPos]; currentPos++; if(currentPos == currentLeaf.keys.length-1){ //move to next leaf if(currentLeaf.next==0){ currentLeaf = null; currentPos=-1; return; } currentPos = 1; currentLeaf = (LeafNode) m.engine.get(currentLeaf.next, m.nodeSerializer); while(currentLeaf.keys.length==2){ if(currentLeaf.next ==0){ currentLeaf = null; currentPos=-1; return; } currentLeaf = (LeafNode) m.engine.get(currentLeaf.next, m.nodeSerializer); } } if(hi!=null && currentLeaf!=null){ //check in bounds Object key = currentLeaf.keys[currentPos]; int c = m.comparator.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)){ //out of high bound currentLeaf=null; currentPos=-1; } } } } @Override public V remove(Object key) { return remove2(key, null); } private V remove2(Object key, Object value) { final long rootRecid = engine.get(rootRecidRef, Serializer.LONG); long current = rootRecid; BNode A = engine.get(current, nodeSerializer); while(!A.isLeaf()){ current = nextDir((DirNode) A, key); A = engine.get(current, nodeSerializer); } try{ while(true){ Utils.lock(nodeLocks, current); A = engine.get(current, nodeSerializer); int pos = findChildren(key, A.keys()); if(pos<A.keys().length&& key!=null && A.keys()[pos]!=null && 0==comparator.compare(key,A.keys()[pos])){ //check for last node which was already deleted if(pos == A.keys().length-1 && value == null){ Utils.unlock(nodeLocks, current); return null; } //delete from node Object oldVal = hasValues? A.vals()[pos-1] : Utils.EMPTY_STRING; oldVal = valExpand(oldVal); if(value!=null && !value.equals(oldVal)){ Utils.unlock(nodeLocks, current); return null; } Object[] keys2 = new Object[A.keys().length-1]; System.arraycopy(A.keys(),0,keys2, 0, pos); System.arraycopy(A.keys(), pos+1, keys2, pos, keys2.length-pos); Object[] vals2 = null; if(hasValues){ vals2 = new Object[A.vals().length-1]; System.arraycopy(A.vals(),0,vals2, 0, pos-1); System.arraycopy(A.vals(), pos, vals2, pos-1, vals2.length-(pos-1)); } A = new LeafNode(keys2, vals2, ((LeafNode)A).next); engine.update(current, A, nodeSerializer); Utils.unlock(nodeLocks, current); notify((K)key, (V)oldVal, null); return (V) oldVal; }else{ Utils.unlock(nodeLocks, current); //follow link until necessary if(A.highKey() != null && comparator.compare(key, A.highKey())>0){ int pos2 = findChildren(key, A.keys()); while(pos2 == A.keys().length){ //TODO lock? current = ((LeafNode)A).next; A = engine.get(current, nodeSerializer); } }else{ return null; } } } }catch(RuntimeException e){ Utils.unlockAll(nodeLocks); throw e; }catch(Exception e){ Utils.unlockAll(nodeLocks); throw new RuntimeException(e); } } @Override public void clear() { Iterator iter = keyIterator(); while(iter.hasNext()){ iter.next(); iter.remove(); } } static class BTreeKeyIterator<K> extends BTreeIterator implements Iterator<K>{ BTreeKeyIterator(BTreeMap m) { super(m); } BTreeKeyIterator(BTreeMap m, Object lo, boolean loInclusive, Object hi, boolean hiInclusive) { super(m, lo, loInclusive, hi, hiInclusive); } @Override public K next() { if(currentLeaf == null) throw new NoSuchElementException(); K ret = (K) currentLeaf.keys[currentPos]; advance(); return ret; } } static class BTreeValueIterator<V> extends BTreeIterator implements Iterator<V>{ BTreeValueIterator(BTreeMap m) { super(m); } BTreeValueIterator(BTreeMap m, Object lo, boolean loInclusive, Object hi, boolean hiInclusive) { super(m, lo, loInclusive, hi, hiInclusive); } @Override public V next() { if(currentLeaf == null) throw new NoSuchElementException(); Object ret = currentLeaf.vals[currentPos-1]; advance(); return (V) m.valExpand(ret); } } static class BTreeEntryIterator<K,V> extends BTreeIterator implements Iterator<Entry<K, V>>{ BTreeEntryIterator(BTreeMap m) { super(m); } BTreeEntryIterator(BTreeMap m, Object lo, boolean loInclusive, Object hi, boolean hiInclusive) { super(m, lo, loInclusive, hi, hiInclusive); } @Override public Entry<K, V> next() { if(currentLeaf == null) throw new NoSuchElementException(); K ret = (K) currentLeaf.keys[currentPos]; Object val = currentLeaf.vals[currentPos-1]; advance(); return m.makeEntry(ret, m.valExpand(val)); } } protected Entry<K, V> makeEntry(Object key, Object value) { if(value instanceof ValRef) throw new InternalError(); return new SimpleImmutableEntry<K, V>((K)key, (V)value); } @Override public boolean isEmpty() { return !keyIterator().hasNext(); } @Override public int size() { long size = sizeLong(); if(size>Integer.MAX_VALUE) return Integer.MAX_VALUE; return (int) size; } @Override public long sizeLong() { if(counter!=null) return counter.get(); long size = 0; BTreeIterator iter = new BTreeIterator(this); while(iter.hasNext()){ iter.advance(); size++; } return size; } @Override public V putIfAbsent(K key, V value) { if(key == null || value == null) throw new NullPointerException(); return put2(key, value, true); } @Override public boolean remove(Object key, Object value) { if(key == null) throw new NullPointerException(); if(value == null) return false; return remove2(key, value)!=null; } @Override public boolean replace(K key, V oldValue, V newValue) { if(key == null || oldValue == null || newValue == null ) throw new NullPointerException(); long rootRecid = engine.get(rootRecidRef, Serializer.LONG); long current = rootRecid; BNode node = engine.get(current, nodeSerializer); //dive until leaf is found while(!node.isLeaf()){ current = nextDir((DirNode) node, key); node = engine.get(current, nodeSerializer); } Utils.lock(nodeLocks, current); LeafNode leaf = (LeafNode) engine.get(current, nodeSerializer); int pos = findChildren(key, node.keys()); try{ while(pos==leaf.keys.length){ //follow leaf link until necessary Utils.lock(nodeLocks, leaf.next); Utils.unlock(nodeLocks, current); current = leaf.next; leaf = (LeafNode) engine.get(current, nodeSerializer); pos = findChildren(key, node.keys()); } boolean ret = false; if( key!=null && leaf.keys()[pos]!=null && 0==comparator.compare(key,leaf.keys[pos])){ Object val = leaf.vals[pos-1]; val = valExpand(val); if(oldValue.equals(val)){ //TODO use comparator here? Object[] vals = Arrays.copyOf(leaf.vals, leaf.vals.length); notify(key, oldValue, newValue); if(valsOutsideNodes){ long recid = engine.put(newValue, valueSerializer); newValue = (V) new ValRef(recid); } vals[pos-1] = newValue; leaf = new LeafNode(Arrays.copyOf(leaf.keys, leaf.keys.length), vals, leaf.next); engine.update(current, leaf, nodeSerializer); ret = true; } } Utils.unlock(nodeLocks, current); return ret; }catch(RuntimeException e){ Utils.unlockAll(nodeLocks); throw e; }catch(Exception e){ Utils.unlockAll(nodeLocks); throw new RuntimeException(e); } } @Override public V replace(K key, V value) { if(key == null || value == null) throw new NullPointerException(); final long rootRecid = engine.get(rootRecidRef,Serializer.LONG); long current = rootRecid; BNode node = engine.get(current, nodeSerializer); //dive until leaf is found while(!node.isLeaf()){ current = nextDir((DirNode) node, key); node = engine.get(current, nodeSerializer); } Utils.lock(nodeLocks, current); LeafNode leaf = (LeafNode) engine.get(current, nodeSerializer); try{ int pos = findChildren(key, node.keys()); while(pos==leaf.keys.length){ //follow leaf link until necessary Utils.lock(nodeLocks, leaf.next); Utils.unlock(nodeLocks, current); current = leaf.next; leaf = (LeafNode) engine.get(current, nodeSerializer); pos = findChildren(key, node.keys()); } Object ret = null; if( key!=null && leaf.keys()[pos]!=null && 0==comparator.compare(key,leaf.keys[pos])){ Object[] vals = Arrays.copyOf(leaf.vals, leaf.vals.length); Object oldVal = vals[pos-1]; ret = valExpand(oldVal); notify(key, (V)ret, value); if(valsOutsideNodes && value!=null){ long recid = engine.put(value, valueSerializer); value = (V) new ValRef(recid); } vals[pos-1] = value; leaf = new LeafNode(Arrays.copyOf(leaf.keys, leaf.keys.length), vals, leaf.next); engine.update(current, leaf, nodeSerializer); } Utils.unlock(nodeLocks, current); return (V)ret; }catch(RuntimeException e){ Utils.unlockAll(nodeLocks); throw e; }catch(Exception e){ Utils.unlockAll(nodeLocks); throw new RuntimeException(e); } } @Override public Comparator<? super K> comparator() { return comparator; } @Override public Map.Entry<K,V> firstEntry() { final long rootRecid = engine.get(rootRecidRef, Serializer.LONG); BNode n = engine.get(rootRecid, nodeSerializer); while(!n.isLeaf()){ n = engine.get(n.child()[0], nodeSerializer); } LeafNode l = (LeafNode) n; //follow link until necessary while(l.keys.length==2){ if(l.next==0) return null; l = (LeafNode) engine.get(l.next, nodeSerializer); } return makeEntry(l.keys[1], hasValues?valExpand(l.vals[0]):Utils.EMPTY_STRING); } @Override public Entry<K, V> pollFirstEntry() { while(true){ Entry<K, V> e = firstEntry(); if(e==null || remove(e.getKey(),e.getValue())){ return e; } } } @Override public Entry<K, V> pollLastEntry() { while(true){ Entry<K, V> e = lastEntry(); if(e==null || remove(e.getKey(),e.getValue())){ return e; } } } protected Entry<K,V> findSmaller(K key,boolean inclusive){ if(key==null) throw new NullPointerException(); final long rootRecid = engine.get(rootRecidRef, Serializer.LONG); BNode n = engine.get(rootRecid, nodeSerializer); Entry<K,V> k = findSmallerRecur(n, key, inclusive); if(k==null || (k.getValue()==null)) return null; return k; } private Entry<K, V> findSmallerRecur(BNode n, K key, boolean inclusive) { final boolean leaf = n.isLeaf(); final int start = leaf ? n.keys().length-2 : n.keys().length-1; final int end = leaf?1:0; final int res = inclusive? 1 : 0; for(int i=start;i>=end; i--){ final Object key2 = n.keys()[i]; int comp = (key2==null)? -1 : comparator.compare(key2, key); if(comp<res){ if(leaf){ return key2==null ? null : makeEntry(key2, hasValues?valExpand(n.vals()[i-1]):Utils.EMPTY_STRING); }else{ final long recid = n.child()[i]; if(recid==0) continue; BNode n2 = engine.get(recid, nodeSerializer); Entry<K,V> ret = findSmallerRecur(n2, key, inclusive); if(ret!=null) return ret; } } } return null; } @Override public Map.Entry<K,V> lastEntry() { final long rootRecid = engine.get(rootRecidRef, Serializer.LONG); BNode n = engine.get(rootRecid, nodeSerializer); Entry e = lastEntryRecur(n); if(e!=null && e.getValue()==null) return null; return e; } private Map.Entry<K,V> lastEntryRecur(BNode n){ if(n.isLeaf()){ //follow next node if available if(n.next()!=0){ BNode n2 = engine.get(n.next(), nodeSerializer); return lastEntryRecur(n2); } //iterate over keys to find last non null key for(int i=n.keys().length-1; i>0;i--){ Object k = n.keys()[i]; if(k!=null) { return makeEntry(k, hasValues?valExpand(n.vals()[i-1]):Utils.EMPTY_STRING); } } }else{ //dir node, dive deeper for(int i=n.child().length-1; i>=0;i--){ long childRecid = n.child()[i]; if(childRecid==0) continue; BNode n2 = engine.get(childRecid, nodeSerializer); Entry<K,V> ret = lastEntryRecur(n2); if(ret!=null) return ret; } } return null; } @Override public Map.Entry<K,V> lowerEntry(K key) { if(key==null) throw new NullPointerException(); return findSmaller(key, false); } @Override public K lowerKey(K key) { Entry<K,V> n = lowerEntry(key); return (n == null)? null : n.getKey(); } @Override public Map.Entry<K,V> floorEntry(K key) { if(key==null) throw new NullPointerException(); return findSmaller(key, true); } @Override public K floorKey(K key) { Entry<K,V> n = floorEntry(key); return (n == null)? null : n.getKey(); } @Override public Map.Entry<K,V> ceilingEntry(K key) { if(key==null) throw new NullPointerException(); return findLarger(key, true); } protected Entry<K, V> findLarger(K key, boolean inclusive) { if(key==null) return null; K v = (K) key; final long rootRecid = engine.get(rootRecidRef, Serializer.LONG); long current = rootRecid; BNode A = engine.get(current, nodeSerializer); //dive until leaf while(!A.isLeaf()){ current = nextDir((DirNode) A, v); A = engine.get(current, nodeSerializer); } //now at leaf level LeafNode leaf = (LeafNode) A; //follow link until first matching node is found final int comp = inclusive?1:0; while(true){ for(int i=1;i<leaf.keys.length-1;i++){ if(leaf.keys[i]==null) continue; if(comparator.compare(key, leaf.keys[i])<comp){ return makeEntry(leaf.keys[i], hasValues?valExpand(leaf.vals[i-1]):Utils.EMPTY_STRING); } } if(leaf.next==0) return null; //reached end leaf = (LeafNode) engine.get(leaf.next, nodeSerializer); } } protected Fun.Tuple2<Integer,LeafNode> findLargerNode(K key, boolean inclusive) { if(key==null) return null; K v = (K) key; final long rootRecid = engine.get(rootRecidRef, Serializer.LONG); long current = rootRecid; BNode A = engine.get(current, nodeSerializer); //dive until leaf while(!A.isLeaf()){ current = nextDir((DirNode) A, v); A = engine.get(current, nodeSerializer); } //now at leaf level LeafNode leaf = (LeafNode) A; //follow link until first matching node is found final int comp = inclusive?1:0; while(true){ for(int i=1;i<leaf.keys.length-1;i++){ if(leaf.keys[i]==null) continue; if(comparator.compare(key, leaf.keys[i])<comp){ return Fun.t2(i, leaf); } } if(leaf.next==0) return null; //reached end leaf = (LeafNode) engine.get(leaf.next, nodeSerializer); } } @Override public K ceilingKey(K key) { if(key==null) throw new NullPointerException(); Entry<K,V> n = ceilingEntry(key); return (n == null)? null : n.getKey(); } @Override public Map.Entry<K,V> higherEntry(K key) { if(key==null) throw new NullPointerException(); return findLarger(key, false); } @Override public K higherKey(K key) { if(key==null) throw new NullPointerException(); Entry<K,V> n = higherEntry(key); return (n == null)? null : n.getKey(); } @Override public boolean containsKey(Object key) { if(key==null) throw new NullPointerException(); return get(key)!=null; } @Override public boolean containsValue(Object value){ if(value ==null) throw new NullPointerException(); Iterator<V> valueIter = valueIterator(); while(valueIter.hasNext()){ if(value.equals(valueIter.next())) return true; } return false; } @Override public K firstKey() { Entry<K,V> e = firstEntry(); if(e==null) throw new NoSuchElementException(); return e.getKey(); } @Override public K lastKey() { Entry<K,V> e = lastEntry(); if(e==null) throw new NoSuchElementException(); return e.getKey(); } @Override public ConcurrentNavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (fromKey == null || toKey == null) throw new NullPointerException(); return new SubMap<K,V> ( this, fromKey, fromInclusive, toKey, toInclusive); } @Override public ConcurrentNavigableMap<K,V> headMap(K toKey, boolean inclusive) { if (toKey == null) throw new NullPointerException(); return new SubMap<K,V> (this, null, false, toKey, inclusive); } @Override public ConcurrentNavigableMap<K,V> tailMap(K fromKey, boolean inclusive) { if (fromKey == null) throw new NullPointerException(); return new SubMap<K,V> (this, fromKey, inclusive, null, false); } @Override public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public ConcurrentNavigableMap<K,V> headMap(K toKey) { return headMap(toKey, false); } @Override public ConcurrentNavigableMap<K,V> tailMap(K fromKey) { return tailMap(fromKey, true); } Iterator<K> keyIterator() { return new BTreeKeyIterator(this); } Iterator<V> valueIterator() { return new BTreeValueIterator(this); } Iterator<Map.Entry<K,V>> entryIterator() { return new BTreeEntryIterator(this); } /* ---------------- View methods -------------- */ @Override public NavigableSet<K> keySet() { return keySet; } @Override public NavigableSet<K> navigableKeySet() { return keySet; } @Override public Collection<V> values() { return values; } @Override public Set<Map.Entry<K,V>> entrySet() { return entrySet; } @Override public ConcurrentNavigableMap<K,V> descendingMap() { return descendingMap; } @Override public NavigableSet<K> descendingKeySet() { return descendingMap.keySet(); } static final <E> List<E> toList(Collection<E> c) { // Using size() here would be a pessimization. List<E> list = new ArrayList<E>(); for (E e : c){ list.add(e); } return list; } static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> { protected final ConcurrentNavigableMap<E,Object> m; private final boolean hasValues; KeySet(ConcurrentNavigableMap<E,Object> map, boolean hasValues) { m = map; this.hasValues = hasValues; } @Override public int size() { return m.size(); } @Override public boolean isEmpty() { return m.isEmpty(); } @Override public boolean contains(Object o) { return m.containsKey(o); } @Override public boolean remove(Object o) { return m.remove(o) != null; } @Override public void clear() { m.clear(); } @Override public E lower(E e) { return m.lowerKey(e); } @Override public E floor(E e) { return m.floorKey(e); } @Override public E ceiling(E e) { return m.ceilingKey(e); } @Override public E higher(E e) { return m.higherKey(e); } @Override public Comparator<? super E> comparator() { return m.comparator(); } @Override public E first() { return m.firstKey(); } @Override public E last() { return m.lastKey(); } @Override public E pollFirst() { Map.Entry<E,Object> e = m.pollFirstEntry(); return e == null? null : e.getKey(); } @Override public E pollLast() { Map.Entry<E,Object> e = m.pollLastEntry(); return e == null? null : e.getKey(); } @Override public Iterator<E> iterator() { if (m instanceof BTreeMap) return ((BTreeMap<E,Object>)m).keyIterator(); else if(m instanceof SubMap) return ((BTreeMap.SubMap<E,Object>)m).keyIterator(); else return ((BTreeMap.DescendingMap<E,Object>)m).keyIterator(); } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Collection<?> c = (Collection<?>) o; try { return containsAll(c) && c.containsAll(this); } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } } @Override public Object[] toArray() { return toList(this).toArray(); } @Override public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } @Override public Iterator<E> descendingIterator() { return descendingSet().iterator(); } @Override public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new KeySet<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive),hasValues); } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { return new KeySet<E>(m.headMap(toElement, inclusive),hasValues); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return new KeySet<E>(m.tailMap(fromElement, inclusive),hasValues); } @Override public NavigableSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } @Override public NavigableSet<E> headSet(E toElement) { return headSet(toElement, false); } @Override public NavigableSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } @Override public NavigableSet<E> descendingSet() { return new KeySet(m.descendingMap(),hasValues); } @Override public boolean add(E k) { if(hasValues) throw new UnsupportedOperationException(); else return m.put(k, Utils.EMPTY_STRING) == null; } } static final class Values<E> extends AbstractCollection<E> { private final ConcurrentNavigableMap<Object, E> m; Values(ConcurrentNavigableMap<Object, E> map) { m = map; } @Override public Iterator<E> iterator() { if (m instanceof BTreeMap) return ((BTreeMap<Object,E>)m).valueIterator(); else return ((SubMap<Object,E>)m).valueIterator(); } @Override public boolean isEmpty() { return m.isEmpty(); } @Override public int size() { return m.size(); } @Override public boolean contains(Object o) { return m.containsValue(o); } @Override public void clear() { m.clear(); } @Override public Object[] toArray() { return toList(this).toArray(); } @Override public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } } static final class EntrySet<K1,V1> extends AbstractSet<Map.Entry<K1,V1>> { private final ConcurrentNavigableMap<K1, V1> m; EntrySet(ConcurrentNavigableMap<K1, V1> map) { m = map; } @Override public Iterator<Map.Entry<K1,V1>> iterator() { if (m instanceof BTreeMap) return ((BTreeMap<K1,V1>)m).entryIterator(); else if(m instanceof SubMap) return ((SubMap<K1,V1>)m).entryIterator(); else return ((DescendingMap<K1,V1>)m).entryIterator(); } @Override public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<K1,V1> e = (Map.Entry<K1,V1>)o; K1 key = e.getKey(); if(key == null) return false; V1 v = m.get(key); return v != null && v.equals(e.getValue()); } @Override public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<K1,V1> e = (Map.Entry<K1,V1>)o; K1 key = e.getKey(); if(key == null) return false; return m.remove(key, e.getValue()); } @Override public boolean isEmpty() { return m.isEmpty(); } @Override public int size() { return m.size(); } @Override public void clear() { m.clear(); } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Collection<?> c = (Collection<?>) o; try { return containsAll(c) && c.containsAll(this); } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } } @Override public Object[] toArray() { return toList(this).toArray(); } @Override public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } } static protected class SubMap<K,V> extends AbstractMap<K,V> implements ConcurrentNavigableMap<K,V> { protected final BTreeMap<K,V> m; protected final K lo; protected final boolean loInclusive; protected final K hi; protected final boolean hiInclusive; public SubMap(BTreeMap<K,V> m, K lo, boolean loInclusive, K hi, boolean hiInclusive) { this.m = m; this.lo = lo; this.loInclusive = loInclusive; this.hi = hi; this.hiInclusive = hiInclusive; if(lo!=null && hi!=null && m.comparator.compare(lo, hi)>0){ throw new IllegalArgumentException(); } } /* ---------------- Map API methods -------------- */ @Override public boolean containsKey(Object key) { if (key == null) throw new NullPointerException(); K k = (K)key; return inBounds(k) && m.containsKey(k); } @Override public V get(Object key) { if (key == null) throw new NullPointerException(); K k = (K)key; return ((!inBounds(k)) ? null : m.get(k)); } @Override public V put(K key, V value) { checkKeyBounds(key); return m.put(key, value); } @Override public V remove(Object key) { K k = (K)key; return (!inBounds(k))? null : m.remove(k); } @Override public int size() { Iterator<K> i = keyIterator(); int counter = 0; while(i.hasNext()){ counter++; i.next(); } return counter; } @Override public boolean isEmpty() { return !keyIterator().hasNext(); } @Override public boolean containsValue(Object value) { if(value==null) throw new NullPointerException(); Iterator<V> i = valueIterator(); while(i.hasNext()){ if(value.equals(i.next())) return true; } return false; } @Override public void clear() { Iterator<K> i = keyIterator(); while(i.hasNext()){ i.next(); i.remove(); } } /* ---------------- ConcurrentMap API methods -------------- */ @Override public V putIfAbsent(K key, V value) { checkKeyBounds(key); return m.putIfAbsent(key, value); } @Override public boolean remove(Object key, Object value) { K k = (K)key; return inBounds(k) && m.remove(k, value); } @Override public boolean replace(K key, V oldValue, V newValue) { checkKeyBounds(key); return m.replace(key, oldValue, newValue); } @Override public V replace(K key, V value) { checkKeyBounds(key); return m.replace(key, value); } /* ---------------- SortedMap API methods -------------- */ @Override public Comparator<? super K> comparator() { return m.comparator(); } /* ---------------- Relational methods -------------- */ @Override public Map.Entry<K,V> lowerEntry(K key) { if(key==null)throw new NullPointerException(); if(tooLow(key))return null; if(tooHigh(key)) return lastEntry(); Entry<K,V> r = m.lowerEntry(key); return r!=null && !tooLow(r.getKey()) ? r :null; } @Override public K lowerKey(K key) { Entry<K,V> n = lowerEntry(key); return (n == null)? null : n.getKey(); } @Override public Map.Entry<K,V> floorEntry(K key) { if(key==null) throw new NullPointerException(); if(tooLow(key)) return null; if(tooHigh(key)){ return lastEntry(); } Entry<K,V> ret = m.floorEntry(key); if(ret!=null && tooLow(ret.getKey())) return null; return ret; } @Override public K floorKey(K key) { Entry<K,V> n = floorEntry(key); return (n == null)? null : n.getKey(); } @Override public Map.Entry<K,V> ceilingEntry(K key) { if(key==null) throw new NullPointerException(); if(tooHigh(key)) return null; if(tooLow(key)){ return firstEntry(); } Entry<K,V> ret = m.ceilingEntry(key); if(ret!=null && tooHigh(ret.getKey())) return null; return ret; } @Override public K ceilingKey(K key) { Entry<K,V> k = ceilingEntry(key); return k!=null? k.getKey():null; } @Override public Entry<K, V> higherEntry(K key) { Entry<K,V> r = m.higherEntry(key); return r!=null && inBounds(r.getKey()) ? r : null; } @Override public K higherKey(K key) { Entry<K,V> k = higherEntry(key); return k!=null? k.getKey():null; } @Override public K firstKey() { Entry<K,V> e = firstEntry(); if(e==null) throw new NoSuchElementException(); return e.getKey(); } @Override public K lastKey() { Entry<K,V> e = lastEntry(); if(e==null) throw new NoSuchElementException(); return e.getKey(); } @Override public Map.Entry<K,V> firstEntry() { Entry<K,V> k = lo==null ? m.firstEntry(): m.findLarger(lo, loInclusive); return k!=null && inBounds(k.getKey())? k : null; } @Override public Map.Entry<K,V> lastEntry() { Entry<K,V> k = hi==null ? m.lastEntry(): m.findSmaller(hi, hiInclusive); return k!=null && inBounds(k.getKey())? k : null; } @Override public Entry<K, V> pollFirstEntry() { while(true){ Entry<K, V> e = firstEntry(); if(e==null || remove(e.getKey(),e.getValue())){ return e; } } } @Override public Entry<K, V> pollLastEntry() { while(true){ Entry<K, V> e = lastEntry(); if(e==null || remove(e.getKey(),e.getValue())){ return e; } } } /** * Utility to create submaps, where given bounds override * unbounded(null) ones and/or are checked against bounded ones. */ private SubMap<K,V> newSubMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { // if(fromKey!=null && toKey!=null){ // int comp = m.comparator.compare(fromKey, toKey); // if((fromInclusive||!toInclusive) && comp==0) // throw new IllegalArgumentException(); // } if (lo != null) { if (fromKey == null) { fromKey = lo; fromInclusive = loInclusive; } else { int c = m.comparator.compare(fromKey, lo); if (c < 0 || (c == 0 && !loInclusive && fromInclusive)) throw new IllegalArgumentException("key out of range"); } } if (hi != null) { if (toKey == null) { toKey = hi; toInclusive = hiInclusive; } else { int c = m.comparator.compare(toKey, hi); if (c > 0 || (c == 0 && !hiInclusive && toInclusive)) throw new IllegalArgumentException("key out of range"); } } return new SubMap<K,V>(m, fromKey, fromInclusive, toKey, toInclusive); } @Override public SubMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (fromKey == null || toKey == null) throw new NullPointerException(); return newSubMap(fromKey, fromInclusive, toKey, toInclusive); } @Override public SubMap<K,V> headMap(K toKey, boolean inclusive) { if (toKey == null) throw new NullPointerException(); return newSubMap(null, false, toKey, inclusive); } @Override public SubMap<K,V> tailMap(K fromKey, boolean inclusive) { if (fromKey == null) throw new NullPointerException(); return newSubMap(fromKey, inclusive, null, false); } @Override public SubMap<K,V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public SubMap<K,V> headMap(K toKey) { return headMap(toKey, false); } @Override public SubMap<K,V> tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public ConcurrentNavigableMap<K,V> descendingMap() { return new DescendingMap(m, lo,loInclusive, hi,hiInclusive); } @Override public NavigableSet<K> navigableKeySet() { return new KeySet<K>((ConcurrentNavigableMap<K,Object>) this,m.hasValues); } /* ---------------- Utilities -------------- */ private boolean tooLow(K key) { if (lo != null) { int c = m.comparator.compare(key, lo); if (c < 0 || (c == 0 && !loInclusive)) return true; } return false; } private boolean tooHigh(K key) { if (hi != null) { int c = m.comparator.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)) return true; } return false; } private boolean inBounds(K key) { return !tooLow(key) && !tooHigh(key); } private void checkKeyBounds(K key) throws IllegalArgumentException { if (key == null) throw new NullPointerException(); if (!inBounds(key)) throw new IllegalArgumentException("key out of range"); } @Override public NavigableSet<K> keySet() { return new KeySet<K>((ConcurrentNavigableMap<K,Object>) this, m.hasValues); } @Override public NavigableSet<K> descendingKeySet() { return new DescendingMap<K,V>(m,lo,loInclusive, hi, hiInclusive).keySet(); } @Override public Set<Entry<K, V>> entrySet() { return new EntrySet<K, V>(this); } Iterator<K> keyIterator() { return new BTreeKeyIterator(m,lo,loInclusive,hi,hiInclusive); } Iterator<V> valueIterator() { return new BTreeValueIterator(m,lo,loInclusive,hi,hiInclusive); } Iterator<Map.Entry<K,V>> entryIterator() { return new BTreeEntryIterator(m,lo,loInclusive,hi,hiInclusive); } } static protected class DescendingMap<K,V> extends AbstractMap<K,V> implements ConcurrentNavigableMap<K,V> { protected final BTreeMap<K,V> m; protected final K lo; protected final boolean loInclusive; protected final K hi; protected final boolean hiInclusive; public DescendingMap(BTreeMap<K,V> m, K lo, boolean loInclusive, K hi, boolean hiInclusive) { this.m = m; this.lo = lo; this.loInclusive = loInclusive; this.hi = hi; this.hiInclusive = hiInclusive; if(lo!=null && hi!=null && m.comparator.compare(lo, hi)>0){ throw new IllegalArgumentException(); } } /* ---------------- Map API methods -------------- */ @Override public boolean containsKey(Object key) { if (key == null) throw new NullPointerException(); K k = (K)key; return inBounds(k) && m.containsKey(k); } @Override public V get(Object key) { if (key == null) throw new NullPointerException(); K k = (K)key; return ((!inBounds(k)) ? null : m.get(k)); } @Override public V put(K key, V value) { checkKeyBounds(key); return m.put(key, value); } @Override public V remove(Object key) { K k = (K)key; return (!inBounds(k))? null : m.remove(k); } @Override public int size() { Iterator<K> i = keyIterator(); int counter = 0; while(i.hasNext()){ counter++; i.next(); } return counter; } @Override public boolean isEmpty() { return !keyIterator().hasNext(); } @Override public boolean containsValue(Object value) { if(value==null) throw new NullPointerException(); Iterator<V> i = valueIterator(); while(i.hasNext()){ if(value.equals(i.next())) return true; } return false; } @Override public void clear() { Iterator<K> i = keyIterator(); while(i.hasNext()){ i.next(); i.remove(); } } /* ---------------- ConcurrentMap API methods -------------- */ @Override public V putIfAbsent(K key, V value) { checkKeyBounds(key); return m.putIfAbsent(key, value); } @Override public boolean remove(Object key, Object value) { K k = (K)key; return inBounds(k) && m.remove(k, value); } @Override public boolean replace(K key, V oldValue, V newValue) { checkKeyBounds(key); return m.replace(key, oldValue, newValue); } @Override public V replace(K key, V value) { checkKeyBounds(key); return m.replace(key, value); } /* ---------------- SortedMap API methods -------------- */ @Override public Comparator<? super K> comparator() { return m.comparator(); } /* ---------------- Relational methods -------------- */ @Override public Map.Entry<K,V> higherEntry(K key) { if(key==null)throw new NullPointerException(); if(tooLow(key))return null; if(tooHigh(key)) return firstEntry(); Entry<K,V> r = m.lowerEntry(key); return r!=null && !tooLow(r.getKey()) ? r :null; } @Override public K lowerKey(K key) { Entry<K,V> n = lowerEntry(key); return (n == null)? null : n.getKey(); } @Override public Map.Entry<K,V> ceilingEntry(K key) { if(key==null) throw new NullPointerException(); if(tooLow(key)) return null; if(tooHigh(key)){ return firstEntry(); } Entry<K,V> ret = m.floorEntry(key); if(ret!=null && tooLow(ret.getKey())) return null; return ret; } @Override public K floorKey(K key) { Entry<K,V> n = floorEntry(key); return (n == null)? null : n.getKey(); } @Override public Map.Entry<K,V> floorEntry(K key) { if(key==null) throw new NullPointerException(); if(tooHigh(key)) return null; if(tooLow(key)){ return lastEntry(); } Entry<K,V> ret = m.ceilingEntry(key); if(ret!=null && tooHigh(ret.getKey())) return null; return ret; } @Override public K ceilingKey(K key) { Entry<K,V> k = ceilingEntry(key); return k!=null? k.getKey():null; } @Override public Entry<K, V> lowerEntry(K key) { Entry<K,V> r = m.higherEntry(key); return r!=null && inBounds(r.getKey()) ? r : null; } @Override public K higherKey(K key) { Entry<K,V> k = higherEntry(key); return k!=null? k.getKey():null; } @Override public K firstKey() { Entry<K,V> e = firstEntry(); if(e==null) throw new NoSuchElementException(); return e.getKey(); } @Override public K lastKey() { Entry<K,V> e = lastEntry(); if(e==null) throw new NoSuchElementException(); return e.getKey(); } @Override public Map.Entry<K,V> lastEntry() { Entry<K,V> k = lo==null ? m.firstEntry(): m.findLarger(lo, loInclusive); return k!=null && inBounds(k.getKey())? k : null; } @Override public Map.Entry<K,V> firstEntry() { Entry<K,V> k = hi==null ? m.lastEntry(): m.findSmaller(hi, hiInclusive); return k!=null && inBounds(k.getKey())? k : null; } @Override public Entry<K, V> pollFirstEntry() { while(true){ Entry<K, V> e = firstEntry(); if(e==null || remove(e.getKey(),e.getValue())){ return e; } } } @Override public Entry<K, V> pollLastEntry() { while(true){ Entry<K, V> e = lastEntry(); if(e==null || remove(e.getKey(),e.getValue())){ return e; } } } /** * Utility to create submaps, where given bounds override * unbounded(null) ones and/or are checked against bounded ones. */ private DescendingMap<K,V> newSubMap( K toKey, boolean toInclusive, K fromKey, boolean fromInclusive) { // if(fromKey!=null && toKey!=null){ // int comp = m.comparator.compare(fromKey, toKey); // if((fromInclusive||!toInclusive) && comp==0) // throw new IllegalArgumentException(); // } if (lo != null) { if (fromKey == null) { fromKey = lo; fromInclusive = loInclusive; } else { int c = m.comparator.compare(fromKey, lo); if (c < 0 || (c == 0 && !loInclusive && fromInclusive)) throw new IllegalArgumentException("key out of range"); } } if (hi != null) { if (toKey == null) { toKey = hi; toInclusive = hiInclusive; } else { int c = m.comparator.compare(toKey, hi); if (c > 0 || (c == 0 && !hiInclusive && toInclusive)) throw new IllegalArgumentException("key out of range"); } } return new DescendingMap<K,V>(m, fromKey, fromInclusive, toKey, toInclusive); } @Override public DescendingMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { if (fromKey == null || toKey == null) throw new NullPointerException(); return newSubMap(fromKey, fromInclusive, toKey, toInclusive); } @Override public DescendingMap<K,V> headMap(K toKey, boolean inclusive) { if (toKey == null) throw new NullPointerException(); return newSubMap(null, false, toKey, inclusive); } @Override public DescendingMap<K,V> tailMap(K fromKey, boolean inclusive) { if (fromKey == null) throw new NullPointerException(); return newSubMap(fromKey, inclusive, null, false); } @Override public DescendingMap<K,V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public DescendingMap<K,V> headMap(K toKey) { return headMap(toKey, false); } @Override public DescendingMap<K,V> tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public ConcurrentNavigableMap<K,V> descendingMap() { if(lo==null && hi==null) return m; return m.subMap(lo,loInclusive,hi,hiInclusive); } @Override public NavigableSet<K> navigableKeySet() { return new KeySet<K>((ConcurrentNavigableMap<K,Object>) this,m.hasValues); } /* ---------------- Utilities -------------- */ private boolean tooLow(K key) { if (lo != null) { int c = m.comparator.compare(key, lo); if (c < 0 || (c == 0 && !loInclusive)) return true; } return false; } private boolean tooHigh(K key) { if (hi != null) { int c = m.comparator.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)) return true; } return false; } private boolean inBounds(K key) { return !tooLow(key) && !tooHigh(key); } private void checkKeyBounds(K key) throws IllegalArgumentException { if (key == null) throw new NullPointerException(); if (!inBounds(key)) throw new IllegalArgumentException("key out of range"); } @Override public NavigableSet<K> keySet() { return new KeySet<K>((ConcurrentNavigableMap<K,Object>) this, m.hasValues); } @Override public NavigableSet<K> descendingKeySet() { return new KeySet<K>((ConcurrentNavigableMap<K,Object>) descendingMap(), m.hasValues); } @Override public Set<Entry<K, V>> entrySet() { return new EntrySet<K, V>(this); } /* * ITERATORS */ abstract class Iter<E> implements Iterator<E> { Entry<K,V> current = DescendingMap.this.firstEntry(); Entry<K,V> last = null; @Override public boolean hasNext() { return current!=null; } public void advance() { if(current==null) throw new NoSuchElementException(); last = current; current = DescendingMap.this.higherEntry(current.getKey()); } @Override public void remove() { if(last==null) throw new IllegalStateException(); DescendingMap.this.remove(last.getKey()); last = null; } } Iterator<K> keyIterator() { return new Iter<K>() { @Override public K next() { advance(); return last.getKey(); } }; } Iterator<V> valueIterator() { return new Iter<V>() { @Override public V next() { advance(); return last.getValue(); } }; } Iterator<Map.Entry<K,V>> entryIterator() { return new Iter<Entry<K, V>>() { @Override public Entry<K, V> next() { advance(); return last; } }; } } /** * Make readonly snapshot view of current Map. Snapshot is immutable and not affected by modifications made by other threads. * Useful if you need consistent view on Map. * * Maintaining snapshot have some overhead, underlying Engine is closed after Map view is GCed. * Please make sure to release reference to this Map view, so snapshot view can be garbage collected. * * @return snapshot */ public NavigableMap<K,V> snapshot(){ Engine snapshot = TxEngine.createSnapshotFor(engine); return new BTreeMap<K, V>(snapshot, rootRecidRef, maxNodeSize, valsOutsideNodes, counter==null?0L:counter.recid, keySerializer, valueSerializer, comparator); } protected final Object modListenersLock = new Object(); protected Bind.MapListener<K,V>[] modListeners = new Bind.MapListener[0]; @Override public void addModificationListener(Bind.MapListener<K,V> listener) { synchronized (modListenersLock){ Bind.MapListener<K,V>[] modListeners2 = Arrays.copyOf(modListeners,modListeners.length+1); modListeners2[modListeners2.length-1] = listener; modListeners = modListeners2; } } @Override public void removeModificationListener(Bind.MapListener<K,V> listener) { synchronized (modListenersLock){ for(int i=0;i<modListeners.length;i++){ if(modListeners[i]==listener) modListeners[i]=null; } } } protected void notify(K key, V oldValue, V newValue) { if(oldValue instanceof ValRef) throw new InternalError(); if(newValue instanceof ValRef) throw new InternalError(); Bind.MapListener<K,V>[] modListeners2 = modListeners; for(Bind.MapListener<K,V> listener:modListeners2){ if(listener!=null) listener.update(key, oldValue, newValue); } } /** * Closes underlying storage and releases all resources. * Used mostly with temporary collections where engine is not accessible. */ public void close(){ engine.close(); } public void printTreeStructure() { final long rootRecid = engine.get(rootRecidRef, Serializer.LONG); printRecur(this, rootRecid, ""); } private static void printRecur(BTreeMap m, long recid, String s) { BTreeMap.BNode n = (BTreeMap.BNode) m.engine.get(recid, m.nodeSerializer); System.out.println(s+recid+"-"+n); if(!n.isLeaf()){ for(int i=0;i<n.child().length-1;i++){ long recid2 = n.child()[i]; if(recid2!=0) printRecur(m, recid2, s+" "); } } } }
true
true
protected V put2(K v, V value2, final boolean putOnlyIfAbsent){ if(v == null) throw new IllegalArgumentException("null key"); if(value2 == null) throw new IllegalArgumentException("null value"); Utils.checkMapValueIsNotCollecion(value2); V value = value2; if(valsOutsideNodes){ long recid = engine.put(value2, valueSerializer); value = (V) new ValRef(recid); } int stackPos = -1; long[] stackVals = new long[4]; final long rootRecid = engine.get(rootRecidRef, Serializer.LONG); long current = rootRecid; BNode A = engine.get(current, nodeSerializer); while(!A.isLeaf()){ long t = current; current = nextDir((DirNode) A, v); if(current == A.child()[A.child().length-1]){ //is link, do nothing }else{ //stack push t stackPos++; if(stackVals.length == stackPos) //grow if needed stackVals = Arrays.copyOf(stackVals, stackVals.length*2); stackVals[stackPos] = t; } A = engine.get(current, nodeSerializer); } int level = 1; long p=0; try{ while(true){ boolean found; do{ Utils.lock(nodeLocks, current); found = true; A = engine.get(current, nodeSerializer); int pos = findChildren(v, A.keys()); if(pos<A.keys().length-1 && v!=null && A.keys()[pos]!=null && 0==comparator.compare(v,A.keys()[pos])){ Object oldVal = (hasValues? A.vals()[pos-1] : Utils.EMPTY_STRING); if(putOnlyIfAbsent){ //is not absent, so quit Utils.unlock(nodeLocks, current); if(CC.PARANOID) Utils.assertNoLocks(nodeLocks); V ret = valExpand(oldVal); notify(v,ret, value2); return ret; } //insert new Object[] vals = null; if(hasValues){ vals = Arrays.copyOf(A.vals(), A.vals().length); vals[pos-1] = value; } A = new LeafNode(Arrays.copyOf(A.keys(), A.keys().length), vals, ((LeafNode)A).next); engine.update(current, A, nodeSerializer); //already in here Utils.unlock(nodeLocks, current); if(CC.PARANOID) Utils.assertNoLocks(nodeLocks); V ret = valExpand(oldVal); notify(v,ret, value2); return ret; } if(A.highKey() != null && comparator.compare(v, A.highKey())>0){ //follow link until necessary Utils.unlock(nodeLocks, current); found = false; int pos2 = findChildren(v, A.keys()); while(A!=null && pos2 == A.keys().length){ //TODO lock? long next = A.next(); if(next==0) break; current = next; A = engine.get(current, nodeSerializer); pos2 = findChildren(v, A.keys()); } } }while(!found); // can be new item inserted into A without splitting it? if(A.keys().length - (A.isLeaf()?2:1)<maxNodeSize){ int pos = findChildren(v, A.keys()); Object[] keys = Utils.arrayPut(A.keys(), pos, v); if(A.isLeaf()){ Object[] vals = hasValues? Utils.arrayPut(A.vals(), pos-1, value): null; LeafNode n = new LeafNode(keys, vals, ((LeafNode)A).next); engine.update(current, n, nodeSerializer); }else{ if(p==0) throw new InternalError(); long[] child = Utils.arrayLongPut(A.child(), pos, p); DirNode d = new DirNode(keys, child); engine.update(current, d, nodeSerializer); } Utils.unlock(nodeLocks, current); if(CC.PARANOID) Utils.assertNoLocks(nodeLocks); notify(v, null, value2); return null; }else{ //node is not safe, it requires splitting final boolean isRoot = (current == rootRecid); final int pos = findChildren(v, A.keys()); final Object[] keys = Utils.arrayPut(A.keys(), pos, v); final Object[] vals = (A.isLeaf() && hasValues)? Utils.arrayPut(A.vals(), pos-1, value) : null; final long[] child = A.isLeaf()? null : Utils.arrayLongPut(A.child(), pos, p); final int splitPos = keys.length/2; BNode B; if(A.isLeaf()){ Object[] vals2 = null; if(hasValues){ vals2 = Arrays.copyOfRange(vals, splitPos, vals.length); } B = new LeafNode( Arrays.copyOfRange(keys, splitPos, keys.length), vals2, ((LeafNode)A).next); }else{ B = new DirNode(Arrays.copyOfRange(keys, splitPos, keys.length), Arrays.copyOfRange(child, splitPos, keys.length)); } long q = engine.put(B, nodeSerializer); if(A.isLeaf()){ // splitPos+1 is there so A gets new high value (key) Object[] keys2 = Arrays.copyOf(keys, splitPos+2); keys2[keys2.length-1] = keys2[keys2.length-2]; Object[] vals2 = null; if(hasValues){ vals2 = Arrays.copyOf(vals, splitPos); } //TODO check high/low keys overlap A = new LeafNode(keys2, vals2, q); }else{ long[] child2 = Arrays.copyOf(child, splitPos+1); child2[splitPos] = q; A = new DirNode(Arrays.copyOf(keys, splitPos+1), child2); } engine.update(current, A, nodeSerializer); if(!isRoot){ Utils.unlock(nodeLocks, current); p = q; v = (K) A.highKey(); level = level+1; if(stackPos!=-1){ //if stack is not empty current = stackVals[stackPos--]; }else{ current = -1; //TODO pointer to left most node at level level throw new InternalError(); } }else{ BNode R = new DirNode( new Object[]{A.keys()[0], A.highKey(), B.highKey()}, new long[]{current,q, 0}); long newRootRecid = engine.put(R, nodeSerializer); //TODO tree root locking engine.update(rootRecidRef, newRootRecid, Serializer.LONG); //TODO update tree levels Utils.unlock(nodeLocks, current); if(CC.PARANOID) Utils.assertNoLocks(nodeLocks); notify(v, null, value2); return null; } } } }catch(RuntimeException e){ Utils.unlockAll(nodeLocks); throw e; }catch(Exception e){ Utils.unlockAll(nodeLocks); throw new RuntimeException(e); } }
protected V put2(K v, V value2, final boolean putOnlyIfAbsent){ if(v == null) throw new IllegalArgumentException("null key"); if(value2 == null) throw new IllegalArgumentException("null value"); Utils.checkMapValueIsNotCollecion(value2); V value = value2; if(valsOutsideNodes){ long recid = engine.put(value2, valueSerializer); value = (V) new ValRef(recid); } int stackPos = -1; long[] stackVals = new long[4]; final long rootRecid = engine.get(rootRecidRef, Serializer.LONG); long current = rootRecid; BNode A = engine.get(current, nodeSerializer); while(!A.isLeaf()){ long t = current; current = nextDir((DirNode) A, v); if(current == A.child()[A.child().length-1]){ //is link, do nothing }else{ //stack push t stackPos++; if(stackVals.length == stackPos) //grow if needed stackVals = Arrays.copyOf(stackVals, stackVals.length*2); stackVals[stackPos] = t; } A = engine.get(current, nodeSerializer); } int level = 1; long p=0; try{ while(true){ boolean found; do{ Utils.lock(nodeLocks, current); found = true; A = engine.get(current, nodeSerializer); int pos = findChildren(v, A.keys()); if(pos<A.keys().length-1 && v!=null && A.keys()[pos]!=null && 0==comparator.compare(v,A.keys()[pos])){ Object oldVal = (hasValues? A.vals()[pos-1] : Utils.EMPTY_STRING); if(putOnlyIfAbsent){ //is not absent, so quit Utils.unlock(nodeLocks, current); if(CC.PARANOID) Utils.assertNoLocks(nodeLocks); return valExpand(oldVal); } //insert new Object[] vals = null; if(hasValues){ vals = Arrays.copyOf(A.vals(), A.vals().length); vals[pos-1] = value; } A = new LeafNode(Arrays.copyOf(A.keys(), A.keys().length), vals, ((LeafNode)A).next); engine.update(current, A, nodeSerializer); //already in here Utils.unlock(nodeLocks, current); if(CC.PARANOID) Utils.assertNoLocks(nodeLocks); V ret = valExpand(oldVal); notify(v,ret, value2); return ret; } if(A.highKey() != null && comparator.compare(v, A.highKey())>0){ //follow link until necessary Utils.unlock(nodeLocks, current); found = false; int pos2 = findChildren(v, A.keys()); while(A!=null && pos2 == A.keys().length){ //TODO lock? long next = A.next(); if(next==0) break; current = next; A = engine.get(current, nodeSerializer); pos2 = findChildren(v, A.keys()); } } }while(!found); // can be new item inserted into A without splitting it? if(A.keys().length - (A.isLeaf()?2:1)<maxNodeSize){ int pos = findChildren(v, A.keys()); Object[] keys = Utils.arrayPut(A.keys(), pos, v); if(A.isLeaf()){ Object[] vals = hasValues? Utils.arrayPut(A.vals(), pos-1, value): null; LeafNode n = new LeafNode(keys, vals, ((LeafNode)A).next); engine.update(current, n, nodeSerializer); }else{ if(p==0) throw new InternalError(); long[] child = Utils.arrayLongPut(A.child(), pos, p); DirNode d = new DirNode(keys, child); engine.update(current, d, nodeSerializer); } Utils.unlock(nodeLocks, current); if(CC.PARANOID) Utils.assertNoLocks(nodeLocks); notify(v, null, value2); return null; }else{ //node is not safe, it requires splitting final boolean isRoot = (current == rootRecid); final int pos = findChildren(v, A.keys()); final Object[] keys = Utils.arrayPut(A.keys(), pos, v); final Object[] vals = (A.isLeaf() && hasValues)? Utils.arrayPut(A.vals(), pos-1, value) : null; final long[] child = A.isLeaf()? null : Utils.arrayLongPut(A.child(), pos, p); final int splitPos = keys.length/2; BNode B; if(A.isLeaf()){ Object[] vals2 = null; if(hasValues){ vals2 = Arrays.copyOfRange(vals, splitPos, vals.length); } B = new LeafNode( Arrays.copyOfRange(keys, splitPos, keys.length), vals2, ((LeafNode)A).next); }else{ B = new DirNode(Arrays.copyOfRange(keys, splitPos, keys.length), Arrays.copyOfRange(child, splitPos, keys.length)); } long q = engine.put(B, nodeSerializer); if(A.isLeaf()){ // splitPos+1 is there so A gets new high value (key) Object[] keys2 = Arrays.copyOf(keys, splitPos+2); keys2[keys2.length-1] = keys2[keys2.length-2]; Object[] vals2 = null; if(hasValues){ vals2 = Arrays.copyOf(vals, splitPos); } //TODO check high/low keys overlap A = new LeafNode(keys2, vals2, q); }else{ long[] child2 = Arrays.copyOf(child, splitPos+1); child2[splitPos] = q; A = new DirNode(Arrays.copyOf(keys, splitPos+1), child2); } engine.update(current, A, nodeSerializer); if(!isRoot){ Utils.unlock(nodeLocks, current); p = q; v = (K) A.highKey(); level = level+1; if(stackPos!=-1){ //if stack is not empty current = stackVals[stackPos--]; }else{ current = -1; //TODO pointer to left most node at level level throw new InternalError(); } }else{ BNode R = new DirNode( new Object[]{A.keys()[0], A.highKey(), B.highKey()}, new long[]{current,q, 0}); long newRootRecid = engine.put(R, nodeSerializer); //TODO tree root locking engine.update(rootRecidRef, newRootRecid, Serializer.LONG); //TODO update tree levels Utils.unlock(nodeLocks, current); if(CC.PARANOID) Utils.assertNoLocks(nodeLocks); notify(v, null, value2); return null; } } } }catch(RuntimeException e){ Utils.unlockAll(nodeLocks); throw e; }catch(Exception e){ Utils.unlockAll(nodeLocks); throw new RuntimeException(e); } }
diff --git a/source/net/sourceforge/texlipse/wizards/TexlipseProjectCreationWizardPage.java b/source/net/sourceforge/texlipse/wizards/TexlipseProjectCreationWizardPage.java index eb3341b..51214e8 100644 --- a/source/net/sourceforge/texlipse/wizards/TexlipseProjectCreationWizardPage.java +++ b/source/net/sourceforge/texlipse/wizards/TexlipseProjectCreationWizardPage.java @@ -1,419 +1,424 @@ /* * $Id$ * * Copyright (c) 2004-2005 by the TeXlapse Team. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package net.sourceforge.texlipse.wizards; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import net.sourceforge.texlipse.TexlipsePlugin; import net.sourceforge.texlipse.builder.BuilderChooser; import net.sourceforge.texlipse.properties.TexlipseProperties; import net.sourceforge.texlipse.templates.ProjectTemplateManager; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Text; /** * Prefs-page on the project creation wizard. * * @author kpkarlss */ public class TexlipseProjectCreationWizardPage extends TexlipseWizardPage { // textfield for project name private Text projectNameField; // project location, if not in workspace private Text projectLocationField; // textfield for template preview private Text descriptionField; // template chooser private List templateList; // template type (system/user) private Label typeLabel; // output format / build order chooser private BuilderChooser outputChooser; private String workspacePath; /** * * @param attributes Project attributes */ public TexlipseProjectCreationWizardPage(TexlipseProjectAttributes attributes) { super(0, attributes); } /** * Create the layout of the page. * @param parent parent component in the UI * @return number of components using a status message */ public void createComponents(Composite parent) { // path to the workspace root directory workspacePath = ResourcesPlugin.getWorkspace().getRoot().getLocation().addTrailingSeparator().toOSString(); createProjectNameControl(parent); addSpacer(parent, 2); createProjectLocationControl(parent); addSpacer(parent, 2); createOutputFormatControl(parent); addSeparator(parent); addSpacer(parent, 2); createLabels(parent); createTemplateControl(parent); //this updates the template description area and the template type label updateEntries(); } /** * @param parent parent component */ private void createOutputFormatControl(Composite parent) { outputChooser = new BuilderChooser(parent); GridData ngd = new GridData(GridData.FILL_HORIZONTAL); ngd.horizontalSpan = 2; outputChooser.setLayoutData(ngd); outputChooser.setSelectedBuilder(TexlipsePlugin.getDefault().getPreferenceStore().getInt(TexlipseProperties.BUILDER_NUMBER)); String o = attributes.getOutputFile(); attributes.setOutputFile(o.substring(0, o.lastIndexOf('.')+1) + outputChooser.getSelectedFormat()); attributes.setOutputFormat(outputChooser.getSelectedFormat()); outputChooser.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String o = attributes.getOutputFile(); attributes.setOutputFile(o.substring(0, o.lastIndexOf('.')+1) + outputChooser.getSelectedFormat()); attributes.setOutputFormat(outputChooser.getSelectedFormat()); attributes.setBuilder(outputChooser.getSelectedBuilder()); }}); } /** * Create project name settings box. * @param composite the parent container */ private void createProjectNameControl(Composite composite) { // add label Label label = new Label(composite, SWT.LEFT); label.setText(TexlipsePlugin.getResourceString("projectWizardNameLabel")); label.setToolTipText(TexlipsePlugin.getResourceString("projectWizardNameTooltip")); label.setLayoutData(new GridData()); // add text field projectNameField = new Text(composite, SWT.SINGLE | SWT.BORDER); projectNameField.setText(attributes.getProjectName()); projectNameField.setToolTipText(TexlipsePlugin.getResourceString("projectWizardNameTooltip")); projectNameField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); projectNameField.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { if (!projectNameField.isDisposed()) { validateProjectName(projectNameField.getText()); if (!projectLocationField.isEnabled()) { projectLocationField.setText(workspacePath + projectNameField.getText()); } } } }); } /** * Create project name settings box. * @param composite the parent container */ private void createProjectLocationControl(Composite parent) { // create borders Group group = new Group(parent, SWT.NULL); group.setText(TexlipsePlugin.getResourceString("projectWizardLocationTitle")); group.setLayout(new GridLayout()); GridData lgd = new GridData(GridData.FILL_HORIZONTAL); lgd.horizontalSpan = 2; group.setLayoutData(lgd); // add radioButtons - Button createLocalProjectButton = new Button(group, SWT.RADIO | SWT.LEFT); + final Button createLocalProjectButton = new Button(group, SWT.RADIO | SWT.LEFT); createLocalProjectButton.setLayoutData(new GridData()); createLocalProjectButton.setText(TexlipsePlugin.getResourceString("projectWizardLocationLocal")); createLocalProjectButton.setSelection(true); createLocalProjectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { + //Only execute if this field becomes selected + if (!createLocalProjectButton.getSelection()) return; projectLocationField.setText(workspacePath + projectNameField.getText()); Control[] c = projectLocationField.getParent().getChildren(); for (int i = 0; i < c.length; i++) { c[i].setEnabled(false); } attributes.setProjectLocation(null); + updateStatus(createStatus(IStatus.OK, ""), projectLocationField); }}); - Button createExternalProjectButton = new Button(group, SWT.RADIO | SWT.LEFT); + final Button createExternalProjectButton = new Button(group, SWT.RADIO | SWT.LEFT); createExternalProjectButton.setLayoutData(new GridData()); createExternalProjectButton.setText(TexlipsePlugin.getResourceString("projectWizardLocationExternal")); createExternalProjectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { + //Only execute if this field becomes selected + if (!createExternalProjectButton.getSelection()) return; Control[] c = projectLocationField.getParent().getChildren(); for (int i = 0; i < c.length; i++) { c[i].setEnabled(true); } projectLocationField.setText(""); }}); Composite composite = new Composite(group, SWT.NULL); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayout cgl = new GridLayout(); cgl.numColumns = 3; composite.setLayout(cgl); // add location label Label label = new Label(composite, SWT.LEFT); label.setText(TexlipsePlugin.getResourceString("projectWizardLocationLabel")); label.setLayoutData(new GridData()); label.setEnabled(false); // add location field projectLocationField = new Text(composite, SWT.SINGLE | SWT.BORDER); projectLocationField.setText(workspacePath); projectLocationField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); projectLocationField.setEnabled(false); projectLocationField.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { if (!projectLocationField.isDisposed() && projectLocationField.isEnabled()) { validateProjectLocation(projectLocationField.getText()); } }}); Button browseLocationButton = new Button(composite, SWT.PUSH); browseLocationButton.setText(TexlipsePlugin.getResourceString("openBrowse")); browseLocationButton.setLayoutData(new GridData()); browseLocationButton.setEnabled(false); browseLocationButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { DirectoryDialog dialog = new DirectoryDialog(projectLocationField.getShell()); dialog.setMessage(TexlipsePlugin.getResourceString("projectWizardLocationSelect")); dialog.setText(TexlipsePlugin.getResourceString("projectWizardLocationSelect")); String current = projectLocationField.getText(); if (current == null || current.length() == 0) { current = workspacePath; } dialog.setFilterPath(current); String dirStr = dialog.open(); if (dirStr != null) { File dir = new File(dirStr); if (dir.exists() && dir.isDirectory()) { projectLocationField.setText(dir.getAbsolutePath()); } } }}); } /** * Check if the external project location is valid. * This method updates the status message for the project location. * @param text the path to project location */ private void validateProjectLocation(String text) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IProject p = workspace.getRoot().getProject(projectNameField.getText()); IStatus status = workspace.validateProjectLocation(p, new Path(text)); if (status.getSeverity() == IStatus.OK) { attributes.setProjectLocation(text); } updateStatus(status, projectLocationField); } /** * Creates labels for the template list and the dexription text area * to the given Composite object * * @param composite the parent container */ private void createLabels(Composite composite) { // add label for the list of templates Label label = new Label(composite, SWT.LEFT); label.setText(TexlipsePlugin.getResourceString("projectWizardTemplateListLabel")); label.setToolTipText(TexlipsePlugin.getResourceString("projectWizardTemplateListTooltip")); label.setLayoutData(new GridData()); // add composite containing a label for the description area and templatetype (system/user) label Composite c = new Composite(composite, SWT.NONE); c.setLayout(new GridLayout(2,false)); c.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // add label for the description area Label l = new Label(c, SWT.LEFT); l.setText(TexlipsePlugin.getResourceString("projectWizardTemplateDescriptionLabel")); l.setToolTipText(TexlipsePlugin.getResourceString("projectWizardTemplateDescriptionTooltip")); l.setLayoutData(new GridData()); // add label for presenting the type of the selected template typeLabel = new Label(c, SWT.RIGHT); //Note that thetext of this label is set by updateEntries() typeLabel.setToolTipText(TexlipsePlugin.getResourceString("projectWizardTemplateTypeTooltip")); typeLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); } /** * Creates a list element containing available templates (system and user) * and a text area next to it for showing description about the selected template * * @param composite the parent container */ private void createTemplateControl(Composite composite) { // add list for templates templateList = new List(composite, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); templateList.setItems(ProjectTemplateManager.loadTemplateNames()); templateList.setLayoutData(new GridData(GridData.FILL_VERTICAL)); templateList.setToolTipText(TexlipsePlugin.getResourceString("projectWizardTemplateTooltip")); templateList.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { attributes.setTemplate(templateList.getSelection()[0]); updateEntries(); }}); templateList.setSelection(0); // this has to be done, because setSelection() doesn't generate an event attributes.setTemplate(templateList.getItem(0)); // add TextField for the selected template's description descriptionField = new Text(composite, SWT.MULTI | SWT.BORDER); descriptionField.setToolTipText(TexlipsePlugin.getResourceString("projectWizardTemplateDescriptionTooltip")); descriptionField.setLayoutData(new GridData(GridData.FILL_BOTH)); descriptionField.setEditable(false); } /** * Updates the description text area and template type label * */ private void updateEntries(){ typeLabel.setText(templateType(attributes.getTemplate())); readProjectTemplateDescription(attributes.getTemplate()); } /** * Returns the type of the given template. * * @param template name of a template (should be the selected item from * the list element containing all available templates). * @return Either "User defined template" or "System defined template" depending * wether the given template is found in plugins templates directory (former if not, * latter if yes). */ private String templateType(String template){ URL templateUrl = TexlipsePlugin.getDefault().getBundle().getEntry("templates" + File.separator + template + ".tex"); if(templateUrl==null) return "User defined template"; else return "System template"; } /** * Starts to read the given template (assuming it is found * from either plugins template directory or user's template directory... * if not, the description is set to "") and puts all lines * starting with "%%" (excluding "%%") to the description text area. * Reading is ended, when a line not starting wiht "%%" is encountered * or the end of file is reached. * * @param template name of a template */ private void readProjectTemplateDescription(String template) { //if system template, then it is found here URL templateUrl = TexlipsePlugin.getDefault().getBundle().getEntry("templates" + File.separator + template + ".tex"); String userTemplate = null; if (templateUrl==null){ //if not, then the template is user defined File userTemplateFolder = ProjectTemplateManager.getUserTemplateFolder(); userTemplate = userTemplateFolder.getAbsolutePath()+File.separator+template+".tex"; } try { String line = null; BufferedReader r; if(templateUrl!=null) r = new BufferedReader(new InputStreamReader(templateUrl.openStream())); else r = new BufferedReader(new FileReader(userTemplate)); StringBuffer sb = new StringBuffer(); while ((line = r.readLine()) != null) { if(!line.startsWith("%%")) break; if(line.length()>2) sb.append(line.substring(2)); sb.append('\n'); } r.close(); sb.toString(); descriptionField.setText(sb.toString()); } catch (IOException e) { TexlipsePlugin.log("Reading a description of template file:", e); descriptionField.setText(""); } } /** * Update the status line when the page becomes visible. */ public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { validateProjectName(projectNameField.getText()); } } /** * Check if there already is a project under the given name. * @param text */ private void validateProjectName(String text) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IStatus status = workspace.validateName(text, IResource.PROJECT); if (status.isOK()) { if (workspace.getRoot().getProject(text).exists()) { status = createStatus(IStatus.ERROR, TexlipsePlugin.getResourceString("projectWizardNameError")); } attributes.setProjectName(text); } updateStatus(status, projectNameField); } }
false
true
private void createProjectLocationControl(Composite parent) { // create borders Group group = new Group(parent, SWT.NULL); group.setText(TexlipsePlugin.getResourceString("projectWizardLocationTitle")); group.setLayout(new GridLayout()); GridData lgd = new GridData(GridData.FILL_HORIZONTAL); lgd.horizontalSpan = 2; group.setLayoutData(lgd); // add radioButtons Button createLocalProjectButton = new Button(group, SWT.RADIO | SWT.LEFT); createLocalProjectButton.setLayoutData(new GridData()); createLocalProjectButton.setText(TexlipsePlugin.getResourceString("projectWizardLocationLocal")); createLocalProjectButton.setSelection(true); createLocalProjectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { projectLocationField.setText(workspacePath + projectNameField.getText()); Control[] c = projectLocationField.getParent().getChildren(); for (int i = 0; i < c.length; i++) { c[i].setEnabled(false); } attributes.setProjectLocation(null); }}); Button createExternalProjectButton = new Button(group, SWT.RADIO | SWT.LEFT); createExternalProjectButton.setLayoutData(new GridData()); createExternalProjectButton.setText(TexlipsePlugin.getResourceString("projectWizardLocationExternal")); createExternalProjectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { Control[] c = projectLocationField.getParent().getChildren(); for (int i = 0; i < c.length; i++) { c[i].setEnabled(true); } projectLocationField.setText(""); }}); Composite composite = new Composite(group, SWT.NULL); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayout cgl = new GridLayout(); cgl.numColumns = 3; composite.setLayout(cgl); // add location label Label label = new Label(composite, SWT.LEFT); label.setText(TexlipsePlugin.getResourceString("projectWizardLocationLabel")); label.setLayoutData(new GridData()); label.setEnabled(false); // add location field projectLocationField = new Text(composite, SWT.SINGLE | SWT.BORDER); projectLocationField.setText(workspacePath); projectLocationField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); projectLocationField.setEnabled(false); projectLocationField.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { if (!projectLocationField.isDisposed() && projectLocationField.isEnabled()) { validateProjectLocation(projectLocationField.getText()); } }}); Button browseLocationButton = new Button(composite, SWT.PUSH); browseLocationButton.setText(TexlipsePlugin.getResourceString("openBrowse")); browseLocationButton.setLayoutData(new GridData()); browseLocationButton.setEnabled(false); browseLocationButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { DirectoryDialog dialog = new DirectoryDialog(projectLocationField.getShell()); dialog.setMessage(TexlipsePlugin.getResourceString("projectWizardLocationSelect")); dialog.setText(TexlipsePlugin.getResourceString("projectWizardLocationSelect")); String current = projectLocationField.getText(); if (current == null || current.length() == 0) { current = workspacePath; } dialog.setFilterPath(current); String dirStr = dialog.open(); if (dirStr != null) { File dir = new File(dirStr); if (dir.exists() && dir.isDirectory()) { projectLocationField.setText(dir.getAbsolutePath()); } } }}); }
private void createProjectLocationControl(Composite parent) { // create borders Group group = new Group(parent, SWT.NULL); group.setText(TexlipsePlugin.getResourceString("projectWizardLocationTitle")); group.setLayout(new GridLayout()); GridData lgd = new GridData(GridData.FILL_HORIZONTAL); lgd.horizontalSpan = 2; group.setLayoutData(lgd); // add radioButtons final Button createLocalProjectButton = new Button(group, SWT.RADIO | SWT.LEFT); createLocalProjectButton.setLayoutData(new GridData()); createLocalProjectButton.setText(TexlipsePlugin.getResourceString("projectWizardLocationLocal")); createLocalProjectButton.setSelection(true); createLocalProjectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { //Only execute if this field becomes selected if (!createLocalProjectButton.getSelection()) return; projectLocationField.setText(workspacePath + projectNameField.getText()); Control[] c = projectLocationField.getParent().getChildren(); for (int i = 0; i < c.length; i++) { c[i].setEnabled(false); } attributes.setProjectLocation(null); updateStatus(createStatus(IStatus.OK, ""), projectLocationField); }}); final Button createExternalProjectButton = new Button(group, SWT.RADIO | SWT.LEFT); createExternalProjectButton.setLayoutData(new GridData()); createExternalProjectButton.setText(TexlipsePlugin.getResourceString("projectWizardLocationExternal")); createExternalProjectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { //Only execute if this field becomes selected if (!createExternalProjectButton.getSelection()) return; Control[] c = projectLocationField.getParent().getChildren(); for (int i = 0; i < c.length; i++) { c[i].setEnabled(true); } projectLocationField.setText(""); }}); Composite composite = new Composite(group, SWT.NULL); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayout cgl = new GridLayout(); cgl.numColumns = 3; composite.setLayout(cgl); // add location label Label label = new Label(composite, SWT.LEFT); label.setText(TexlipsePlugin.getResourceString("projectWizardLocationLabel")); label.setLayoutData(new GridData()); label.setEnabled(false); // add location field projectLocationField = new Text(composite, SWT.SINGLE | SWT.BORDER); projectLocationField.setText(workspacePath); projectLocationField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); projectLocationField.setEnabled(false); projectLocationField.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { if (!projectLocationField.isDisposed() && projectLocationField.isEnabled()) { validateProjectLocation(projectLocationField.getText()); } }}); Button browseLocationButton = new Button(composite, SWT.PUSH); browseLocationButton.setText(TexlipsePlugin.getResourceString("openBrowse")); browseLocationButton.setLayoutData(new GridData()); browseLocationButton.setEnabled(false); browseLocationButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { DirectoryDialog dialog = new DirectoryDialog(projectLocationField.getShell()); dialog.setMessage(TexlipsePlugin.getResourceString("projectWizardLocationSelect")); dialog.setText(TexlipsePlugin.getResourceString("projectWizardLocationSelect")); String current = projectLocationField.getText(); if (current == null || current.length() == 0) { current = workspacePath; } dialog.setFilterPath(current); String dirStr = dialog.open(); if (dirStr != null) { File dir = new File(dirStr); if (dir.exists() && dir.isDirectory()) { projectLocationField.setText(dir.getAbsolutePath()); } } }}); }
diff --git a/src/util/FormatterText.java b/src/util/FormatterText.java index 4ef1cec..499f943 100644 --- a/src/util/FormatterText.java +++ b/src/util/FormatterText.java @@ -1,216 +1,221 @@ package util; import com.ebay.services.finding.Amount; import com.ebay.services.finding.SearchItem; import java.text.SimpleDateFormat; import java.util.*; public class FormatterText { public final static SimpleDateFormat dateformatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); private final static SimpleDateFormat dateForSearchDay = new SimpleDateFormat("yyyy-MM-dd"); private final static SimpleDateFormat dateForSearchTime = new SimpleDateFormat("hh:mm:ss.SSS"); public static String buildDate(Calendar cal) { return dateForSearchDay.format(cal.getTime()) + "T" + dateForSearchTime.format(cal.getTime()) + "Z"; } /** * This method makes specail formats data for file * @param items * @param type * @param id * @return */ public static String buildCsvFile(List<SearchItem> items, String type, String id, String typeSearch) { Map<String, List<SearchItem>> listByComdition = new LinkedHashMap<String, List<SearchItem>>(); //this map we use for sort our items by condition for (SearchItem item : items) { String condition = item.getCondition().getConditionDisplayName(); List<SearchItem> conditionList = listByComdition.get(condition); if (conditionList == null) { conditionList = new ArrayList<SearchItem>(); } conditionList.add(item); listByComdition.put(condition, conditionList); } StringBuilder sb = new StringBuilder("Type search : " + typeSearch); sb.append(type).append(" (").append(id).append(")").append("\n\n"); for (Map.Entry<String, List<SearchItem>> entry : listByComdition.entrySet()) { sb.append("Condition (").append(entry.getKey()).append(")").append("\n"); for (SearchItem item : entry.getValue()) { sb.append(item.getItemId()).append("\n"); } sb.append("\n"); } return sb.toString(); } public static String formatForConsole(List<SearchItem> items, Map<String, Boolean> showOpts, String id, String type) { StringBuilder sb = new StringBuilder(); sb.append(type).append(" (").append(id).append(")").append("\n\n"); for (SearchItem item : items) { for (Map.Entry<String, Boolean> entry : showOpts.entrySet()) { if ("autoPay".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(String.valueOf(item.isAutoPay())).append("\n"); } if ("charityId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getCharityId()).append("\n"); } if ("compatibility".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getCompatibility()).append("\n"); } if ("conditionDisplayName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getCondition().getConditionDisplayName()).append("\n"); } if ("country".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getCountry()).append("\n"); } if ("distance".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getDistance()).append("\n"); } if ("galleryURL".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getGalleryURL()).append("\n"); } if ("galleryPlusPictureURL".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getGalleryPlusPictureURL()).append("\n"); } if ("globalId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getGlobalId()).append("\n"); } if ("itemId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getItemId()).append("\n"); } if ("bestOfferEnabled".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().isBestOfferEnabled()).append("\n"); } if ("buyItNowAvailable".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().isBuyItNowAvailable()).append("\n"); } if ("buyItNowPrice".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().getBuyItNowPrice()).append("\n"); } if ("convertedBuyItNowPrice".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().getConvertedBuyItNowPrice()).append("\n"); } if ("endTime".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(dateformatter.format(item.getListingInfo().getEndTime().getTime())).append("\n"); } if ("gift".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().isGift()).append("\n"); } if ("listingType".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().getListingType()).append("\n"); } if ("startTime".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(dateformatter.format(item.getListingInfo().getStartTime().getTime())).append("\n"); } if ("primaryCategoryId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getPrimaryCategory().getCategoryId()).append("\n"); } if ("primaryCategoryName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getPrimaryCategory().getCategoryName()).append("\n"); } if ("location".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getLocation()).append("\n"); } if ("paymentMethod".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getPaymentMethod()).append("\n"); } if ("postalCode".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getPostalCode()).append("\n"); } if ("productId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getProductId()).append("\n"); } if ("returnsAccepted".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.isReturnsAccepted()).append("\n"); } if ("secondaryCategoryId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSecondaryCategory().getCategoryId()).append("\n"); } if ("secondaryCategoryName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSecondaryCategory().getCategoryName()).append("\n"); } if ("feedbackRatingStar".equals(entry.getKey())) { - sb.append(entry.getKey()).append(" : ").append(item.getSellerInfo().getFeedbackRatingStar()).append("\n"); + String value = item.getSellerInfo() != null ? item.getSellerInfo().getFeedbackRatingStar() : ""; + sb.append(entry.getKey()).append(" : ").append(value).append("\n"); } if ("feedbackScore".equals(entry.getKey())) { - sb.append(entry.getKey()).append(" : ").append(item.getSellerInfo().getFeedbackScore()).append("\n"); + String value = item.getSellerInfo() != null ? String.valueOf(item.getSellerInfo().getFeedbackScore()) : ""; + sb.append(entry.getKey()).append(" : ").append(value).append("\n"); } if ("positiveFeedbackPercent".equals(entry.getKey())) { - sb.append(entry.getKey()).append(" : ").append(item.getSellerInfo().getPositiveFeedbackPercent()).append("\n"); + String value = item.getSellerInfo() != null ? String.valueOf(item.getSellerInfo().getPositiveFeedbackPercent()) : ""; + sb.append(entry.getKey()).append(" : ").append(value).append("\n"); } if ("sellerUserName".equals(entry.getKey())) { - sb.append(entry.getKey()).append(" : ").append(item.getSellerInfo().getSellerUserName()).append("\n"); + String value = item.getSellerInfo() != null ? String.valueOf(item.getSellerInfo().getSellerUserName()) : ""; + sb.append(entry.getKey()).append(" : ").append(value).append("\n"); } if ("topRatedSeller".equals(entry.getKey())) { - sb.append(entry.getKey()).append(" : ").append(item.getSellerInfo().isTopRatedSeller()).append("\n"); + String value = item.getSellerInfo() != null ? String.valueOf(item.getSellerInfo().isTopRatedSeller()) : ""; + sb.append(entry.getKey()).append(" : ").append(value).append("\n"); } if ("bidCount".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellingStatus().getBidCount()).append("\n"); } if ("convertedCurrentPrice".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellingStatus().getConvertedCurrentPrice()).append("\n"); } if ("currentPrice".equals(entry.getKey())) { String value = String.valueOf(item.getSellingStatus().getCurrentPrice().getValue()); String rate = item.getSellingStatus().getCurrentPrice().getCurrencyId(); sb.append(entry.getKey()).append(" : ").append(buildPrice(item.getSellingStatus().getCurrentPrice())).append("\n"); } if ("sellingState".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellingStatus().getSellingState()).append("\n"); } if ("timeLeft".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellingStatus().getTimeLeft()).append("\n"); } if ("expeditedShipping".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().isExpeditedShipping()).append("\n"); } if ("handlingTime".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().getHandlingTime()).append("\n"); } if ("oneDayShippingAvailable".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().isOneDayShippingAvailable()).append("\n"); } if ("shippingServiceCost".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(buildPrice(item.getShippingInfo().getShippingServiceCost())).append("\n"); } if ("shippingType".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().getShippingType()).append("\n"); } if ("shipToLocations".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().getShipToLocations()).append("\n"); } if ("storeName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getStoreInfo().getStoreName()).append("\n"); } if ("storeURL".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getStoreInfo().getStoreURL()).append("\n"); } if ("subtitle".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSubtitle()).append("\n"); } if ("title".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getTitle()).append("\n"); } if ("viewItemURL".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getViewItemURL()).append("\n"); } } sb.append("\n"); } return sb.toString(); } private static String buildPrice(Amount amount) { if (amount != null) { String value = String.valueOf(amount.getValue()); String rate = amount.getCurrencyId(); return value + " " + rate; } else { return null; } } }
false
true
public static String formatForConsole(List<SearchItem> items, Map<String, Boolean> showOpts, String id, String type) { StringBuilder sb = new StringBuilder(); sb.append(type).append(" (").append(id).append(")").append("\n\n"); for (SearchItem item : items) { for (Map.Entry<String, Boolean> entry : showOpts.entrySet()) { if ("autoPay".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(String.valueOf(item.isAutoPay())).append("\n"); } if ("charityId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getCharityId()).append("\n"); } if ("compatibility".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getCompatibility()).append("\n"); } if ("conditionDisplayName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getCondition().getConditionDisplayName()).append("\n"); } if ("country".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getCountry()).append("\n"); } if ("distance".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getDistance()).append("\n"); } if ("galleryURL".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getGalleryURL()).append("\n"); } if ("galleryPlusPictureURL".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getGalleryPlusPictureURL()).append("\n"); } if ("globalId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getGlobalId()).append("\n"); } if ("itemId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getItemId()).append("\n"); } if ("bestOfferEnabled".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().isBestOfferEnabled()).append("\n"); } if ("buyItNowAvailable".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().isBuyItNowAvailable()).append("\n"); } if ("buyItNowPrice".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().getBuyItNowPrice()).append("\n"); } if ("convertedBuyItNowPrice".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().getConvertedBuyItNowPrice()).append("\n"); } if ("endTime".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(dateformatter.format(item.getListingInfo().getEndTime().getTime())).append("\n"); } if ("gift".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().isGift()).append("\n"); } if ("listingType".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().getListingType()).append("\n"); } if ("startTime".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(dateformatter.format(item.getListingInfo().getStartTime().getTime())).append("\n"); } if ("primaryCategoryId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getPrimaryCategory().getCategoryId()).append("\n"); } if ("primaryCategoryName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getPrimaryCategory().getCategoryName()).append("\n"); } if ("location".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getLocation()).append("\n"); } if ("paymentMethod".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getPaymentMethod()).append("\n"); } if ("postalCode".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getPostalCode()).append("\n"); } if ("productId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getProductId()).append("\n"); } if ("returnsAccepted".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.isReturnsAccepted()).append("\n"); } if ("secondaryCategoryId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSecondaryCategory().getCategoryId()).append("\n"); } if ("secondaryCategoryName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSecondaryCategory().getCategoryName()).append("\n"); } if ("feedbackRatingStar".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellerInfo().getFeedbackRatingStar()).append("\n"); } if ("feedbackScore".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellerInfo().getFeedbackScore()).append("\n"); } if ("positiveFeedbackPercent".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellerInfo().getPositiveFeedbackPercent()).append("\n"); } if ("sellerUserName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellerInfo().getSellerUserName()).append("\n"); } if ("topRatedSeller".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellerInfo().isTopRatedSeller()).append("\n"); } if ("bidCount".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellingStatus().getBidCount()).append("\n"); } if ("convertedCurrentPrice".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellingStatus().getConvertedCurrentPrice()).append("\n"); } if ("currentPrice".equals(entry.getKey())) { String value = String.valueOf(item.getSellingStatus().getCurrentPrice().getValue()); String rate = item.getSellingStatus().getCurrentPrice().getCurrencyId(); sb.append(entry.getKey()).append(" : ").append(buildPrice(item.getSellingStatus().getCurrentPrice())).append("\n"); } if ("sellingState".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellingStatus().getSellingState()).append("\n"); } if ("timeLeft".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellingStatus().getTimeLeft()).append("\n"); } if ("expeditedShipping".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().isExpeditedShipping()).append("\n"); } if ("handlingTime".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().getHandlingTime()).append("\n"); } if ("oneDayShippingAvailable".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().isOneDayShippingAvailable()).append("\n"); } if ("shippingServiceCost".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(buildPrice(item.getShippingInfo().getShippingServiceCost())).append("\n"); } if ("shippingType".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().getShippingType()).append("\n"); } if ("shipToLocations".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().getShipToLocations()).append("\n"); } if ("storeName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getStoreInfo().getStoreName()).append("\n"); } if ("storeURL".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getStoreInfo().getStoreURL()).append("\n"); } if ("subtitle".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSubtitle()).append("\n"); } if ("title".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getTitle()).append("\n"); } if ("viewItemURL".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getViewItemURL()).append("\n"); } } sb.append("\n"); } return sb.toString(); }
public static String formatForConsole(List<SearchItem> items, Map<String, Boolean> showOpts, String id, String type) { StringBuilder sb = new StringBuilder(); sb.append(type).append(" (").append(id).append(")").append("\n\n"); for (SearchItem item : items) { for (Map.Entry<String, Boolean> entry : showOpts.entrySet()) { if ("autoPay".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(String.valueOf(item.isAutoPay())).append("\n"); } if ("charityId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getCharityId()).append("\n"); } if ("compatibility".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getCompatibility()).append("\n"); } if ("conditionDisplayName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getCondition().getConditionDisplayName()).append("\n"); } if ("country".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getCountry()).append("\n"); } if ("distance".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getDistance()).append("\n"); } if ("galleryURL".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getGalleryURL()).append("\n"); } if ("galleryPlusPictureURL".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getGalleryPlusPictureURL()).append("\n"); } if ("globalId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getGlobalId()).append("\n"); } if ("itemId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getItemId()).append("\n"); } if ("bestOfferEnabled".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().isBestOfferEnabled()).append("\n"); } if ("buyItNowAvailable".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().isBuyItNowAvailable()).append("\n"); } if ("buyItNowPrice".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().getBuyItNowPrice()).append("\n"); } if ("convertedBuyItNowPrice".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().getConvertedBuyItNowPrice()).append("\n"); } if ("endTime".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(dateformatter.format(item.getListingInfo().getEndTime().getTime())).append("\n"); } if ("gift".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().isGift()).append("\n"); } if ("listingType".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getListingInfo().getListingType()).append("\n"); } if ("startTime".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(dateformatter.format(item.getListingInfo().getStartTime().getTime())).append("\n"); } if ("primaryCategoryId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getPrimaryCategory().getCategoryId()).append("\n"); } if ("primaryCategoryName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getPrimaryCategory().getCategoryName()).append("\n"); } if ("location".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getLocation()).append("\n"); } if ("paymentMethod".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getPaymentMethod()).append("\n"); } if ("postalCode".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getPostalCode()).append("\n"); } if ("productId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getProductId()).append("\n"); } if ("returnsAccepted".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.isReturnsAccepted()).append("\n"); } if ("secondaryCategoryId".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSecondaryCategory().getCategoryId()).append("\n"); } if ("secondaryCategoryName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSecondaryCategory().getCategoryName()).append("\n"); } if ("feedbackRatingStar".equals(entry.getKey())) { String value = item.getSellerInfo() != null ? item.getSellerInfo().getFeedbackRatingStar() : ""; sb.append(entry.getKey()).append(" : ").append(value).append("\n"); } if ("feedbackScore".equals(entry.getKey())) { String value = item.getSellerInfo() != null ? String.valueOf(item.getSellerInfo().getFeedbackScore()) : ""; sb.append(entry.getKey()).append(" : ").append(value).append("\n"); } if ("positiveFeedbackPercent".equals(entry.getKey())) { String value = item.getSellerInfo() != null ? String.valueOf(item.getSellerInfo().getPositiveFeedbackPercent()) : ""; sb.append(entry.getKey()).append(" : ").append(value).append("\n"); } if ("sellerUserName".equals(entry.getKey())) { String value = item.getSellerInfo() != null ? String.valueOf(item.getSellerInfo().getSellerUserName()) : ""; sb.append(entry.getKey()).append(" : ").append(value).append("\n"); } if ("topRatedSeller".equals(entry.getKey())) { String value = item.getSellerInfo() != null ? String.valueOf(item.getSellerInfo().isTopRatedSeller()) : ""; sb.append(entry.getKey()).append(" : ").append(value).append("\n"); } if ("bidCount".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellingStatus().getBidCount()).append("\n"); } if ("convertedCurrentPrice".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellingStatus().getConvertedCurrentPrice()).append("\n"); } if ("currentPrice".equals(entry.getKey())) { String value = String.valueOf(item.getSellingStatus().getCurrentPrice().getValue()); String rate = item.getSellingStatus().getCurrentPrice().getCurrencyId(); sb.append(entry.getKey()).append(" : ").append(buildPrice(item.getSellingStatus().getCurrentPrice())).append("\n"); } if ("sellingState".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellingStatus().getSellingState()).append("\n"); } if ("timeLeft".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSellingStatus().getTimeLeft()).append("\n"); } if ("expeditedShipping".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().isExpeditedShipping()).append("\n"); } if ("handlingTime".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().getHandlingTime()).append("\n"); } if ("oneDayShippingAvailable".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().isOneDayShippingAvailable()).append("\n"); } if ("shippingServiceCost".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(buildPrice(item.getShippingInfo().getShippingServiceCost())).append("\n"); } if ("shippingType".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().getShippingType()).append("\n"); } if ("shipToLocations".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getShippingInfo().getShipToLocations()).append("\n"); } if ("storeName".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getStoreInfo().getStoreName()).append("\n"); } if ("storeURL".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getStoreInfo().getStoreURL()).append("\n"); } if ("subtitle".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getSubtitle()).append("\n"); } if ("title".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getTitle()).append("\n"); } if ("viewItemURL".equals(entry.getKey())) { sb.append(entry.getKey()).append(" : ").append(item.getViewItemURL()).append("\n"); } } sb.append("\n"); } return sb.toString(); }
diff --git a/net.atos.optimus.m2m.engine.parent/net.atos.optimus.m2m.engine.core/src/main/java/net/atos/optimus/m2m/engine/core/masks/PreferencesTransformationMask.java b/net.atos.optimus.m2m.engine.parent/net.atos.optimus.m2m.engine.core/src/main/java/net/atos/optimus/m2m/engine/core/masks/PreferencesTransformationMask.java index ec3cd68..13e7865 100644 --- a/net.atos.optimus.m2m.engine.parent/net.atos.optimus.m2m.engine.core/src/main/java/net/atos/optimus/m2m/engine/core/masks/PreferencesTransformationMask.java +++ b/net.atos.optimus.m2m.engine.parent/net.atos.optimus.m2m.engine.core/src/main/java/net/atos/optimus/m2m/engine/core/masks/PreferencesTransformationMask.java @@ -1,48 +1,48 @@ package net.atos.optimus.m2m.engine.core.masks; import net.atos.optimus.m2m.engine.core.Activator; import org.eclipse.jface.preference.IPreferenceStore; public class PreferencesTransformationMask implements ITransformationMask { /** * Static internal class, in charge of holding the Singleton instance. * * @generated XA Singleton Generator on 2013-07-10 15:28:48 CEST */ private static class SingletonHolder { static PreferencesTransformationMask instance = new PreferencesTransformationMask(); } /** * Returns the Singleton instance of this class. * * @generated XA Singleton Generator on 2013-07-10 15:28:48 CEST */ public static PreferencesTransformationMask getInstance() { return SingletonHolder.instance; } /** * Default constructor. Generated because used in singleton instanciation & * needs to be private * * @generated XA Singleton Generator on 2013-07-10 15:28:48 CEST */ private PreferencesTransformationMask() { } private IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); public boolean isTransformationEnabled(String id) { String enablementKey = Activator.PLUGIN_ID + ".disabled." + id; - return this.preferenceStore.getBoolean(enablementKey); + return !this.preferenceStore.getBoolean(enablementKey); } public void setTransformationEnabled(String id, boolean enabled) { String enablementKey = Activator.PLUGIN_ID + ".disabled." + id; this.preferenceStore.setValue(enablementKey, !enabled); } }
true
true
public boolean isTransformationEnabled(String id) { String enablementKey = Activator.PLUGIN_ID + ".disabled." + id; return this.preferenceStore.getBoolean(enablementKey); }
public boolean isTransformationEnabled(String id) { String enablementKey = Activator.PLUGIN_ID + ".disabled." + id; return !this.preferenceStore.getBoolean(enablementKey); }
diff --git a/tool/src/java/org/sakaiproject/assignment2/tool/entity/Assignment2SubmissionEntityProvider.java b/tool/src/java/org/sakaiproject/assignment2/tool/entity/Assignment2SubmissionEntityProvider.java index 0285a308..976e6539 100644 --- a/tool/src/java/org/sakaiproject/assignment2/tool/entity/Assignment2SubmissionEntityProvider.java +++ b/tool/src/java/org/sakaiproject/assignment2/tool/entity/Assignment2SubmissionEntityProvider.java @@ -1,292 +1,295 @@ package org.sakaiproject.assignment2.tool.entity; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.sakaiproject.assignment2.logic.AssignmentBundleLogic; import org.sakaiproject.assignment2.logic.AssignmentLogic; import org.sakaiproject.assignment2.logic.AssignmentPermissionLogic; import org.sakaiproject.assignment2.logic.AssignmentSubmissionLogic; import org.sakaiproject.assignment2.logic.ExternalGradebookLogic; import org.sakaiproject.assignment2.logic.ExternalLogic; import org.sakaiproject.assignment2.logic.GradeInformation; import org.sakaiproject.assignment2.model.Assignment2; import org.sakaiproject.assignment2.model.AssignmentSubmission; import org.sakaiproject.assignment2.model.constants.AssignmentConstants; import org.sakaiproject.assignment2.tool.params.GradeViewParams; import org.sakaiproject.assignment2.tool.producers.GradeProducer; import org.sakaiproject.entitybroker.EntityReference; import org.sakaiproject.entitybroker.entityprovider.CoreEntityProvider; import org.sakaiproject.entitybroker.entityprovider.capabilities.RESTful; import org.sakaiproject.entitybroker.entityprovider.capabilities.RequestAware; import org.sakaiproject.entitybroker.entityprovider.capabilities.RequestStorable; import org.sakaiproject.entitybroker.entityprovider.extension.RequestGetter; import org.sakaiproject.entitybroker.entityprovider.extension.RequestStorage; import org.sakaiproject.entitybroker.entityprovider.search.Order; import org.sakaiproject.entitybroker.entityprovider.search.Search; import org.sakaiproject.entitybroker.util.AbstractEntityProvider; import uk.org.ponder.rsf.components.UIBranchContainer; import uk.org.ponder.rsf.components.UIInternalLink; import uk.org.ponder.rsf.components.UIOutput; public class Assignment2SubmissionEntityProvider extends AbstractEntityProvider implements CoreEntityProvider, RESTful, RequestStorable, RequestAware{ public static final String STUDENT_NAME_PROP = "studentName"; public static final String STUDENT_ID_PROP = "studentId"; public static final String SUBMITTED_DATE = "submittedDate"; public static final String SUBMITTED_DATE_FORMATTED = "submittedDateFormat"; public static final String SUBMISSION_STATUS = "submissionStatus"; public static final String SUBMISSION_GRADE = "grade"; public static final String SUBMISSION_FEEDBACK_RELEASED = "feedbackReleased"; /** * Dependency */ private AssignmentSubmissionLogic submissionLogic; public void setSubmissionLogic(AssignmentSubmissionLogic submissionLogic) { this.submissionLogic = submissionLogic; } /** * Dependency */ private AssignmentLogic assignmentLogic; public void setAssignmentLogic(AssignmentLogic assignmentLogic) { this.assignmentLogic = assignmentLogic; } /** * Dependency */ private ExternalGradebookLogic externalGradebookLogic; public void setExternalGradebookLogic(ExternalGradebookLogic externalGradebookLogic) { this.externalGradebookLogic = externalGradebookLogic; } /** * Dependency */ private ExternalLogic externalLogic; public void setExternalLogic(ExternalLogic externalLogic) { this.externalLogic = externalLogic; } /** * Dependency */ private AssignmentPermissionLogic permissionLogic; public void setPermissionLogic(AssignmentPermissionLogic permissionLogic) { this.permissionLogic = permissionLogic; } /** * Dependency */ private RequestStorage requestStorage; public void setRequestStorage(RequestStorage requestStorage) { this.requestStorage = requestStorage; } /** * Dependency */ private RequestGetter requestGetter; public void setRequestGetter(RequestGetter requestGetter) { this.requestGetter = requestGetter; } /** * Dependency */ private AssignmentBundleLogic assignmentBundleLogic; public void setAssignmentBundleLogic(AssignmentBundleLogic assignmentBundleLogic) { this.assignmentBundleLogic = assignmentBundleLogic; } public boolean entityExists(String id) { // TODO Auto-generated method stub return false; } public final static String PREFIX = "assignment2submission"; public String getEntityPrefix() { return PREFIX; } public String createEntity(EntityReference ref, Object entity, Map<String, Object> params) { // TODO Auto-generated method stub return null; } public Object getSampleEntity() { // TODO Auto-generated method stub return null; } public void updateEntity(EntityReference ref, Object entity, Map<String, Object> params) { // TODO Auto-generated method stub } public Object getEntity(EntityReference ref) { // TODO Auto-generated method stub return null; } public void deleteEntity(EntityReference ref, Map<String, Object> params) { // TODO Auto-generated method stub } @SuppressWarnings("unchecked") public List<?> getEntities(EntityReference ref, Search search) { Long assignmentId = requestStorage.getStoredValueAsType(Long.class, "asnnid"); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, assignmentBundleLogic.getLocale()); List togo = new ArrayList(); String filterGroupId = requestStorage.getStoredValueAsType(String.class, "groupId"); List<AssignmentSubmission> submissions = submissionLogic.getViewableSubmissionsWithHistoryForAssignmentId(assignmentId, filterGroupId); if (submissions == null) { return togo; } // put studentIds in a list List<String> studentIdList = new ArrayList<String>(); for (AssignmentSubmission submission : submissions) { studentIdList.add(submission.getUserId()); } Assignment2 assignment = assignmentLogic.getAssignmentById(assignmentId); Map<String, GradeInformation> studentIdGradeInfoMap = new HashMap<String, GradeInformation>(); if (submissions != null && assignment.isGraded() && assignment.getGradebookItemId() != null) { // now retrieve all of the GradeInformation studentIdGradeInfoMap = externalGradebookLogic.getGradeInformationForStudents( studentIdList, assignment.getContextId(), assignment.getGradebookItemId()); } Map<String, String> studentIdSortNameMap = externalLogic.getUserIdToSortNameMap(studentIdList); for (AssignmentSubmission as : submissions) { Map submap = new HashMap(); submap.put("studentName", studentIdSortNameMap.get(as.getUserId())); submap.put("studentId", as.getUserId()); // submission info columns are not displayed for non-electronic assignments if (assignment.getSubmissionType() != AssignmentConstants.SUBMIT_NON_ELECTRONIC) { if (as.getCurrentSubmissionVersion() != null && as.getCurrentSubmissionVersion().getSubmittedDate() != null){ submap.put("submittedDate", as.getCurrentSubmissionVersion().getSubmittedDate()); submap.put("submittedDateFormat", df.format(as.getCurrentSubmissionVersion().getSubmittedDate())); } else { // We're not addign this to the subject. } // set the textual representation of the submission status String status = ""; int statusConstant = AssignmentConstants.SUBMISSION_NOT_STARTED; if (as != null) { statusConstant = submissionLogic.getSubmissionStatusConstantForCurrentVersion( as.getCurrentSubmissionVersion(), assignment.getDueDate()); status = assignmentBundleLogic.getString( "assignment2.assignment_grade-assignment.submission_status." + statusConstant); submap.put("submissionStatus", status); } } if (assignment.isGraded()) { String grade = ""; GradeInformation gradeInfo = studentIdGradeInfoMap.get(as.getUserId()); if (gradeInfo != null) { grade = gradeInfo.getGradebookGrade(); } submap.put("grade", grade); } if (as.getCurrentSubmissionVersion() != null) { submap.put("feedbackReleased",as.getCurrentSubmissionVersion().isFeedbackReleased()); } else { submap.put("feedbackReleased", false); } togo.add(submap); } if (search.getOrders() != null && search.getOrders().length > 0) { Order order = search.getOrders()[0]; // We can sort by: // studentName, submittedDate, submissionStatus, grade, and feedbackReleased final String orderBy = order.getProperty(); final boolean ascending = order.ascending; if (orderBy.equals(STUDENT_NAME_PROP) || orderBy.equals(SUBMITTED_DATE) || orderBy.equals(SUBMISSION_STATUS) || (orderBy.equals(SUBMISSION_GRADE) && assignment.isGraded()) || orderBy.equals(SUBMISSION_FEEDBACK_RELEASED)) { Collections.sort(togo, new Comparator() { public int compare(Object o1, Object o2) { Map m1, m2; if (ascending) { m1 = (Map) o1; m2 = (Map) o2; } else { m2 = (Map) o1; m1 = (Map) o2; } if (m1.get(orderBy) instanceof Date) { return ((Date)m1.get(orderBy)).compareTo(((Date)m2.get(orderBy))); } else if (m1.get(orderBy) instanceof Boolean) { return ((Boolean)m1.get(orderBy)).compareTo(((Boolean)m2.get(orderBy))); } else { return m1.get(orderBy).toString().compareTo(m2.get(orderBy).toString()); } }}); } } long start = (int) search.getStart(); - if (start >= togo.size()) { + if (togo.size() == 0) { + start = 0; + } + else if (start >= togo.size()) { start = togo.size() - 1; } long end = togo.size(); if (search.getLimit() > 0) { end = start + search.getLimit(); if (end > togo.size()) { end = togo.size(); } } return togo.subList((int)start, (int)end); } public String[] getHandledOutputFormats() { // TODO Auto-generated method stub return null; } public String[] getHandledInputFormats() { // TODO Auto-generated method stub return null; } }
true
true
public List<?> getEntities(EntityReference ref, Search search) { Long assignmentId = requestStorage.getStoredValueAsType(Long.class, "asnnid"); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, assignmentBundleLogic.getLocale()); List togo = new ArrayList(); String filterGroupId = requestStorage.getStoredValueAsType(String.class, "groupId"); List<AssignmentSubmission> submissions = submissionLogic.getViewableSubmissionsWithHistoryForAssignmentId(assignmentId, filterGroupId); if (submissions == null) { return togo; } // put studentIds in a list List<String> studentIdList = new ArrayList<String>(); for (AssignmentSubmission submission : submissions) { studentIdList.add(submission.getUserId()); } Assignment2 assignment = assignmentLogic.getAssignmentById(assignmentId); Map<String, GradeInformation> studentIdGradeInfoMap = new HashMap<String, GradeInformation>(); if (submissions != null && assignment.isGraded() && assignment.getGradebookItemId() != null) { // now retrieve all of the GradeInformation studentIdGradeInfoMap = externalGradebookLogic.getGradeInformationForStudents( studentIdList, assignment.getContextId(), assignment.getGradebookItemId()); } Map<String, String> studentIdSortNameMap = externalLogic.getUserIdToSortNameMap(studentIdList); for (AssignmentSubmission as : submissions) { Map submap = new HashMap(); submap.put("studentName", studentIdSortNameMap.get(as.getUserId())); submap.put("studentId", as.getUserId()); // submission info columns are not displayed for non-electronic assignments if (assignment.getSubmissionType() != AssignmentConstants.SUBMIT_NON_ELECTRONIC) { if (as.getCurrentSubmissionVersion() != null && as.getCurrentSubmissionVersion().getSubmittedDate() != null){ submap.put("submittedDate", as.getCurrentSubmissionVersion().getSubmittedDate()); submap.put("submittedDateFormat", df.format(as.getCurrentSubmissionVersion().getSubmittedDate())); } else { // We're not addign this to the subject. } // set the textual representation of the submission status String status = ""; int statusConstant = AssignmentConstants.SUBMISSION_NOT_STARTED; if (as != null) { statusConstant = submissionLogic.getSubmissionStatusConstantForCurrentVersion( as.getCurrentSubmissionVersion(), assignment.getDueDate()); status = assignmentBundleLogic.getString( "assignment2.assignment_grade-assignment.submission_status." + statusConstant); submap.put("submissionStatus", status); } } if (assignment.isGraded()) { String grade = ""; GradeInformation gradeInfo = studentIdGradeInfoMap.get(as.getUserId()); if (gradeInfo != null) { grade = gradeInfo.getGradebookGrade(); } submap.put("grade", grade); } if (as.getCurrentSubmissionVersion() != null) { submap.put("feedbackReleased",as.getCurrentSubmissionVersion().isFeedbackReleased()); } else { submap.put("feedbackReleased", false); } togo.add(submap); } if (search.getOrders() != null && search.getOrders().length > 0) { Order order = search.getOrders()[0]; // We can sort by: // studentName, submittedDate, submissionStatus, grade, and feedbackReleased final String orderBy = order.getProperty(); final boolean ascending = order.ascending; if (orderBy.equals(STUDENT_NAME_PROP) || orderBy.equals(SUBMITTED_DATE) || orderBy.equals(SUBMISSION_STATUS) || (orderBy.equals(SUBMISSION_GRADE) && assignment.isGraded()) || orderBy.equals(SUBMISSION_FEEDBACK_RELEASED)) { Collections.sort(togo, new Comparator() { public int compare(Object o1, Object o2) { Map m1, m2; if (ascending) { m1 = (Map) o1; m2 = (Map) o2; } else { m2 = (Map) o1; m1 = (Map) o2; } if (m1.get(orderBy) instanceof Date) { return ((Date)m1.get(orderBy)).compareTo(((Date)m2.get(orderBy))); } else if (m1.get(orderBy) instanceof Boolean) { return ((Boolean)m1.get(orderBy)).compareTo(((Boolean)m2.get(orderBy))); } else { return m1.get(orderBy).toString().compareTo(m2.get(orderBy).toString()); } }}); } } long start = (int) search.getStart(); if (start >= togo.size()) { start = togo.size() - 1; } long end = togo.size(); if (search.getLimit() > 0) { end = start + search.getLimit(); if (end > togo.size()) { end = togo.size(); } } return togo.subList((int)start, (int)end); }
public List<?> getEntities(EntityReference ref, Search search) { Long assignmentId = requestStorage.getStoredValueAsType(Long.class, "asnnid"); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, assignmentBundleLogic.getLocale()); List togo = new ArrayList(); String filterGroupId = requestStorage.getStoredValueAsType(String.class, "groupId"); List<AssignmentSubmission> submissions = submissionLogic.getViewableSubmissionsWithHistoryForAssignmentId(assignmentId, filterGroupId); if (submissions == null) { return togo; } // put studentIds in a list List<String> studentIdList = new ArrayList<String>(); for (AssignmentSubmission submission : submissions) { studentIdList.add(submission.getUserId()); } Assignment2 assignment = assignmentLogic.getAssignmentById(assignmentId); Map<String, GradeInformation> studentIdGradeInfoMap = new HashMap<String, GradeInformation>(); if (submissions != null && assignment.isGraded() && assignment.getGradebookItemId() != null) { // now retrieve all of the GradeInformation studentIdGradeInfoMap = externalGradebookLogic.getGradeInformationForStudents( studentIdList, assignment.getContextId(), assignment.getGradebookItemId()); } Map<String, String> studentIdSortNameMap = externalLogic.getUserIdToSortNameMap(studentIdList); for (AssignmentSubmission as : submissions) { Map submap = new HashMap(); submap.put("studentName", studentIdSortNameMap.get(as.getUserId())); submap.put("studentId", as.getUserId()); // submission info columns are not displayed for non-electronic assignments if (assignment.getSubmissionType() != AssignmentConstants.SUBMIT_NON_ELECTRONIC) { if (as.getCurrentSubmissionVersion() != null && as.getCurrentSubmissionVersion().getSubmittedDate() != null){ submap.put("submittedDate", as.getCurrentSubmissionVersion().getSubmittedDate()); submap.put("submittedDateFormat", df.format(as.getCurrentSubmissionVersion().getSubmittedDate())); } else { // We're not addign this to the subject. } // set the textual representation of the submission status String status = ""; int statusConstant = AssignmentConstants.SUBMISSION_NOT_STARTED; if (as != null) { statusConstant = submissionLogic.getSubmissionStatusConstantForCurrentVersion( as.getCurrentSubmissionVersion(), assignment.getDueDate()); status = assignmentBundleLogic.getString( "assignment2.assignment_grade-assignment.submission_status." + statusConstant); submap.put("submissionStatus", status); } } if (assignment.isGraded()) { String grade = ""; GradeInformation gradeInfo = studentIdGradeInfoMap.get(as.getUserId()); if (gradeInfo != null) { grade = gradeInfo.getGradebookGrade(); } submap.put("grade", grade); } if (as.getCurrentSubmissionVersion() != null) { submap.put("feedbackReleased",as.getCurrentSubmissionVersion().isFeedbackReleased()); } else { submap.put("feedbackReleased", false); } togo.add(submap); } if (search.getOrders() != null && search.getOrders().length > 0) { Order order = search.getOrders()[0]; // We can sort by: // studentName, submittedDate, submissionStatus, grade, and feedbackReleased final String orderBy = order.getProperty(); final boolean ascending = order.ascending; if (orderBy.equals(STUDENT_NAME_PROP) || orderBy.equals(SUBMITTED_DATE) || orderBy.equals(SUBMISSION_STATUS) || (orderBy.equals(SUBMISSION_GRADE) && assignment.isGraded()) || orderBy.equals(SUBMISSION_FEEDBACK_RELEASED)) { Collections.sort(togo, new Comparator() { public int compare(Object o1, Object o2) { Map m1, m2; if (ascending) { m1 = (Map) o1; m2 = (Map) o2; } else { m2 = (Map) o1; m1 = (Map) o2; } if (m1.get(orderBy) instanceof Date) { return ((Date)m1.get(orderBy)).compareTo(((Date)m2.get(orderBy))); } else if (m1.get(orderBy) instanceof Boolean) { return ((Boolean)m1.get(orderBy)).compareTo(((Boolean)m2.get(orderBy))); } else { return m1.get(orderBy).toString().compareTo(m2.get(orderBy).toString()); } }}); } } long start = (int) search.getStart(); if (togo.size() == 0) { start = 0; } else if (start >= togo.size()) { start = togo.size() - 1; } long end = togo.size(); if (search.getLimit() > 0) { end = start + search.getLimit(); if (end > togo.size()) { end = togo.size(); } } return togo.subList((int)start, (int)end); }
diff --git a/workspace-android/BarcodeScanner/src/net/redlinesoft/app/barcodescanner/MainActivity.java b/workspace-android/BarcodeScanner/src/net/redlinesoft/app/barcodescanner/MainActivity.java index d7c1696..8519c9e 100644 --- a/workspace-android/BarcodeScanner/src/net/redlinesoft/app/barcodescanner/MainActivity.java +++ b/workspace-android/BarcodeScanner/src/net/redlinesoft/app/barcodescanner/MainActivity.java @@ -1,59 +1,58 @@ package net.redlinesoft.app.barcodescanner; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bntScan = (Button) findViewById(R.id.button1); bntScan.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { - Activity MainActivity = null; // TODO Auto-generated method stub IntentIntegrator integrator = new IntentIntegrator(MainActivity.this); integrator.initiateScan(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (scanResult != null) { TextView txtBarcode = (TextView) findViewById(R.id.textView1); txtBarcode.setText(scanResult.getContents().toString()); } else { Toast.makeText(this, "No data!", Toast.LENGTH_SHORT).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bntScan = (Button) findViewById(R.id.button1); bntScan.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Activity MainActivity = null; // TODO Auto-generated method stub IntentIntegrator integrator = new IntentIntegrator(MainActivity.this); integrator.initiateScan(); } }); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bntScan = (Button) findViewById(R.id.button1); bntScan.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub IntentIntegrator integrator = new IntentIntegrator(MainActivity.this); integrator.initiateScan(); } }); }
diff --git a/lang/java/tools/src/main/java/org/apache/avro/tool/BinaryFragmentToJsonTool.java b/lang/java/tools/src/main/java/org/apache/avro/tool/BinaryFragmentToJsonTool.java index bcb63a42..f2cc5939 100644 --- a/lang/java/tools/src/main/java/org/apache/avro/tool/BinaryFragmentToJsonTool.java +++ b/lang/java/tools/src/main/java/org/apache/avro/tool/BinaryFragmentToJsonTool.java @@ -1,85 +1,85 @@ /** * 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.avro.tool; import java.io.FileInputStream; import java.io.InputStream; import java.io.PrintStream; import java.util.List; import org.apache.avro.Schema; import org.apache.avro.io.DecoderFactory; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.EncoderFactory; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericDatumWriter; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator; /** Converts an input file from Avro binary into JSON. */ public class BinaryFragmentToJsonTool implements Tool { @Override public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args) throws Exception { if (args.size() != 2) { - err.println("Expected 1 arguments: schema binary_data_file"); + err.println("Expected 2 arguments: schema binary_data_file"); err.println("Use '-' as binary_data_file for stdin."); return 1; } Schema schema = Schema.parse(args.get(0)); InputStream input; boolean needsClosing; if (args.get(1).equals("-")) { input = stdin; needsClosing = false; } else { input = new FileInputStream(args.get(1)); needsClosing = true; } try { DatumReader<Object> reader = new GenericDatumReader<Object>(schema); Object datum = reader.read(null, DecoderFactory.get().binaryDecoder(input, null)); DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema); JsonGenerator g = new JsonFactory().createJsonGenerator(out, JsonEncoding.UTF8); g.useDefaultPrettyPrinter(); writer.write(datum, EncoderFactory.get().jsonEncoder(schema, g)); g.flush(); out.println(); out.flush(); } finally { if (needsClosing) { input.close(); } } return 0; } @Override public String getName() { return "fragtojson"; } @Override public String getShortDescription() { return "Renders a binary-encoded Avro datum as JSON."; } }
true
true
public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args) throws Exception { if (args.size() != 2) { err.println("Expected 1 arguments: schema binary_data_file"); err.println("Use '-' as binary_data_file for stdin."); return 1; } Schema schema = Schema.parse(args.get(0)); InputStream input; boolean needsClosing; if (args.get(1).equals("-")) { input = stdin; needsClosing = false; } else { input = new FileInputStream(args.get(1)); needsClosing = true; } try { DatumReader<Object> reader = new GenericDatumReader<Object>(schema); Object datum = reader.read(null, DecoderFactory.get().binaryDecoder(input, null)); DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema); JsonGenerator g = new JsonFactory().createJsonGenerator(out, JsonEncoding.UTF8); g.useDefaultPrettyPrinter(); writer.write(datum, EncoderFactory.get().jsonEncoder(schema, g)); g.flush(); out.println(); out.flush(); } finally { if (needsClosing) { input.close(); } } return 0; }
public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args) throws Exception { if (args.size() != 2) { err.println("Expected 2 arguments: schema binary_data_file"); err.println("Use '-' as binary_data_file for stdin."); return 1; } Schema schema = Schema.parse(args.get(0)); InputStream input; boolean needsClosing; if (args.get(1).equals("-")) { input = stdin; needsClosing = false; } else { input = new FileInputStream(args.get(1)); needsClosing = true; } try { DatumReader<Object> reader = new GenericDatumReader<Object>(schema); Object datum = reader.read(null, DecoderFactory.get().binaryDecoder(input, null)); DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema); JsonGenerator g = new JsonFactory().createJsonGenerator(out, JsonEncoding.UTF8); g.useDefaultPrettyPrinter(); writer.write(datum, EncoderFactory.get().jsonEncoder(schema, g)); g.flush(); out.println(); out.flush(); } finally { if (needsClosing) { input.close(); } } return 0; }
diff --git a/src/main/java/hu/sztaki/ilab/longneck/process/task/ProcessWorker.java b/src/main/java/hu/sztaki/ilab/longneck/process/task/ProcessWorker.java index 92e8ba4..6d5656c 100644 --- a/src/main/java/hu/sztaki/ilab/longneck/process/task/ProcessWorker.java +++ b/src/main/java/hu/sztaki/ilab/longneck/process/task/ProcessWorker.java @@ -1,188 +1,189 @@ package hu.sztaki.ilab.longneck.process.task; import hu.sztaki.ilab.longneck.Record; import hu.sztaki.ilab.longneck.bootstrap.PropertyUtils; import hu.sztaki.ilab.longneck.process.FailException; import hu.sztaki.ilab.longneck.process.FilterException; import hu.sztaki.ilab.longneck.process.FrameAddressResolver; import hu.sztaki.ilab.longneck.process.Kernel; import hu.sztaki.ilab.longneck.process.block.Sequence; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; /** * * @author Molnár Péter <[email protected]> */ public class ProcessWorker extends AbstractTask implements Runnable { /** Log to write messages to. */ private final Logger LOG = Logger.getLogger(ProcessWorker.class); /** The source queue, where records are read from. */ private final BlockingQueue<QueueItem> sourceQueue; /** The target queue, where records are written to. */ private final BlockingQueue<QueueItem> targetQueue; /** The error queue, where errors are written to. */ private final BlockingQueue<QueueItem> errorQueue; /** Local queue for cloned records. */ private final List<Record> localCloneQueue = new ArrayList<Record>(); /** Enable running of thread. */ private volatile boolean running = true; /** The bulk size. */ private int bulkSize = 100; private Kernel kernel; public ProcessWorker(BlockingQueue<QueueItem> sourceQueue, BlockingQueue<QueueItem> targetQueue, BlockingQueue<QueueItem> errorQueue, FrameAddressResolver frameAddressResolver, Sequence topLevelSequence, Properties runtimeProperties) { this.sourceQueue = sourceQueue; this.targetQueue = targetQueue; this.errorQueue = errorQueue; kernel = new Kernel(topLevelSequence, frameAddressResolver, localCloneQueue); // Read settings from runtime properties measureTimeEnabled = PropertyUtils.getBooleanProperty( runtimeProperties, "measureTimeEnabled", false); } @Override public void run() { // Run parent method super.run(); LOG.info("Starting up."); // Create queue item list List<Record> queueItemList = new ArrayList<Record>(bulkSize); boolean shutdownReceived = false; List<Record> targetRecords = new ArrayList<Record>(bulkSize); List<Record> errorRecords = new ArrayList<Record>(bulkSize); QueueItem item; try { while (running && (! shutdownReceived || ! localCloneQueue.isEmpty())) { item = null; // Query cloned records if (localCloneQueue.size() >= bulkSize || shutdownReceived) { // Determine count of removable elements int subListSize = Math.min(bulkSize, localCloneQueue.size()); // Clear queue item list and add elements from cloned record queue queueItemList.clear(); queueItemList.addAll(localCloneQueue.subList(0, subListSize)); // Remove items from cloned record queue localCloneQueue.subList(0, subListSize).clear(); // Create new queue item item = new QueueItem(queueItemList); // Increase counter stats.cloned += subListSize; } if (item == null && ! shutdownReceived) { // Get record from source queue; cloned records are taken first item = sourceQueue.poll(100, TimeUnit.MILLISECONDS); } // Check record, if null if (item == null) { continue; } stats.in += item.getRecords().size(); if (item.isNoMoreRecords()) { shutdownReceived = true; } List<Record> inRecords = item.getRecords(); for (Record record : inRecords) { try { // Process with kernel kernel.process(record); // Add record to output targetRecords.add(record); errorRecords.add(record); } catch (FailException ex) { LOG.debug(ex.getMessage(), ex); stats.failed += 1; } catch (FilterException ex) { // LOG.info(ex.getMessage(), ex); LOG.trace(ex.getMessage()) ; stats.filtered += 1; + errorRecords.add(record); } } // Write to output if (! targetRecords.isEmpty()) { QueueItem outItem = new QueueItem(targetRecords); targetQueue.put(outItem); stats.out += outItem.getRecords().size(); } if (! errorRecords.isEmpty()) { errorQueue.put(new QueueItem(errorRecords)); } // Clean up targetRecords.clear(); errorRecords.clear(); } } catch (InterruptedException ex) { LOG.info("Interrupted.", ex); } catch (Exception ex) { LOG.fatal("Fatal error during processing.", ex); } // Log timings if (measureTimeEnabled) { stats.totalTimeMillis = this.getTotalTime(); stats.blockedTimeMillis = mxBean.getThreadInfo(Thread.currentThread().getId()).getBlockedTime(); } stats.setMeasureTimeEnabled(measureTimeEnabled); LOG.info(stats.toString()); LOG.info("Shutting down."); } public BlockingQueue<QueueItem> getSourceQueue() { return sourceQueue; } public BlockingQueue<QueueItem> getTargetQueue() { return targetQueue; } public BlockingQueue<QueueItem> getErrorQueue() { return errorQueue; } public Logger getLog() { return LOG; } public boolean isRunning() { return running; } public void setRunning(boolean running) { this.running = running; } }
true
true
public void run() { // Run parent method super.run(); LOG.info("Starting up."); // Create queue item list List<Record> queueItemList = new ArrayList<Record>(bulkSize); boolean shutdownReceived = false; List<Record> targetRecords = new ArrayList<Record>(bulkSize); List<Record> errorRecords = new ArrayList<Record>(bulkSize); QueueItem item; try { while (running && (! shutdownReceived || ! localCloneQueue.isEmpty())) { item = null; // Query cloned records if (localCloneQueue.size() >= bulkSize || shutdownReceived) { // Determine count of removable elements int subListSize = Math.min(bulkSize, localCloneQueue.size()); // Clear queue item list and add elements from cloned record queue queueItemList.clear(); queueItemList.addAll(localCloneQueue.subList(0, subListSize)); // Remove items from cloned record queue localCloneQueue.subList(0, subListSize).clear(); // Create new queue item item = new QueueItem(queueItemList); // Increase counter stats.cloned += subListSize; } if (item == null && ! shutdownReceived) { // Get record from source queue; cloned records are taken first item = sourceQueue.poll(100, TimeUnit.MILLISECONDS); } // Check record, if null if (item == null) { continue; } stats.in += item.getRecords().size(); if (item.isNoMoreRecords()) { shutdownReceived = true; } List<Record> inRecords = item.getRecords(); for (Record record : inRecords) { try { // Process with kernel kernel.process(record); // Add record to output targetRecords.add(record); errorRecords.add(record); } catch (FailException ex) { LOG.debug(ex.getMessage(), ex); stats.failed += 1; } catch (FilterException ex) { // LOG.info(ex.getMessage(), ex); LOG.trace(ex.getMessage()) ; stats.filtered += 1; } } // Write to output if (! targetRecords.isEmpty()) { QueueItem outItem = new QueueItem(targetRecords); targetQueue.put(outItem); stats.out += outItem.getRecords().size(); } if (! errorRecords.isEmpty()) { errorQueue.put(new QueueItem(errorRecords)); } // Clean up targetRecords.clear(); errorRecords.clear(); } } catch (InterruptedException ex) { LOG.info("Interrupted.", ex); } catch (Exception ex) { LOG.fatal("Fatal error during processing.", ex); } // Log timings if (measureTimeEnabled) { stats.totalTimeMillis = this.getTotalTime(); stats.blockedTimeMillis = mxBean.getThreadInfo(Thread.currentThread().getId()).getBlockedTime(); } stats.setMeasureTimeEnabled(measureTimeEnabled); LOG.info(stats.toString()); LOG.info("Shutting down."); }
public void run() { // Run parent method super.run(); LOG.info("Starting up."); // Create queue item list List<Record> queueItemList = new ArrayList<Record>(bulkSize); boolean shutdownReceived = false; List<Record> targetRecords = new ArrayList<Record>(bulkSize); List<Record> errorRecords = new ArrayList<Record>(bulkSize); QueueItem item; try { while (running && (! shutdownReceived || ! localCloneQueue.isEmpty())) { item = null; // Query cloned records if (localCloneQueue.size() >= bulkSize || shutdownReceived) { // Determine count of removable elements int subListSize = Math.min(bulkSize, localCloneQueue.size()); // Clear queue item list and add elements from cloned record queue queueItemList.clear(); queueItemList.addAll(localCloneQueue.subList(0, subListSize)); // Remove items from cloned record queue localCloneQueue.subList(0, subListSize).clear(); // Create new queue item item = new QueueItem(queueItemList); // Increase counter stats.cloned += subListSize; } if (item == null && ! shutdownReceived) { // Get record from source queue; cloned records are taken first item = sourceQueue.poll(100, TimeUnit.MILLISECONDS); } // Check record, if null if (item == null) { continue; } stats.in += item.getRecords().size(); if (item.isNoMoreRecords()) { shutdownReceived = true; } List<Record> inRecords = item.getRecords(); for (Record record : inRecords) { try { // Process with kernel kernel.process(record); // Add record to output targetRecords.add(record); errorRecords.add(record); } catch (FailException ex) { LOG.debug(ex.getMessage(), ex); stats.failed += 1; } catch (FilterException ex) { // LOG.info(ex.getMessage(), ex); LOG.trace(ex.getMessage()) ; stats.filtered += 1; errorRecords.add(record); } } // Write to output if (! targetRecords.isEmpty()) { QueueItem outItem = new QueueItem(targetRecords); targetQueue.put(outItem); stats.out += outItem.getRecords().size(); } if (! errorRecords.isEmpty()) { errorQueue.put(new QueueItem(errorRecords)); } // Clean up targetRecords.clear(); errorRecords.clear(); } } catch (InterruptedException ex) { LOG.info("Interrupted.", ex); } catch (Exception ex) { LOG.fatal("Fatal error during processing.", ex); } // Log timings if (measureTimeEnabled) { stats.totalTimeMillis = this.getTotalTime(); stats.blockedTimeMillis = mxBean.getThreadInfo(Thread.currentThread().getId()).getBlockedTime(); } stats.setMeasureTimeEnabled(measureTimeEnabled); LOG.info(stats.toString()); LOG.info("Shutting down."); }
diff --git a/srcj/com/sun/electric/tool/routing/SimpleWirer.java b/srcj/com/sun/electric/tool/routing/SimpleWirer.java index c3e53f06e..a0ddaffd4 100644 --- a/srcj/com/sun/electric/tool/routing/SimpleWirer.java +++ b/srcj/com/sun/electric/tool/routing/SimpleWirer.java @@ -1,227 +1,227 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: SimpleWirer.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Electric(tm) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.routing; import com.sun.electric.database.geometry.PolyMerge; import com.sun.electric.database.geometry.DBMath; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.prototype.PortProto; import com.sun.electric.technology.ArcProto; import com.sun.electric.technology.PrimitiveNode; import com.sun.electric.technology.Layer; import com.sun.electric.technology.SizeOffset; import com.sun.electric.technology.technologies.Generic; import com.sun.electric.tool.user.User; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; /** * A Simple wiring tool for the user to draw wires. */ public class SimpleWirer extends InteractiveRouter { /* ----------------------- Router Methods ------------------------------------- */ public String toString() { return "SimpleWirer"; } protected boolean planRoute(Route route, Cell cell, RouteElementPort endRE, Point2D startLoc, Point2D endLoc, Point2D clicked, PolyMerge stayInside, VerticalRoute vroute, boolean contactsOnEndObj, boolean extendArcHead, boolean extendArcTail) { RouteElementPort startRE = route.getEnd(); // find port protos of startRE and endRE, and find connecting arc type PortProto startPort = startRE.getPortProto(); PortProto endPort = endRE.getPortProto(); ArcProto useArc = getArcToUse(startPort, endPort); // first, find location of corner of L if routing will be an L shape Point2D cornerLoc = null; if (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY() || (useArc != null && (useArc.getAngleIncrement() == 0))) { // single arc if (contactsOnEndObj) cornerLoc = endLoc; else cornerLoc = startLoc; } else { Point2D pin1 = new Point2D.Double(startLoc.getX(), endLoc.getY()); Point2D pin2 = new Point2D.Double(endLoc.getX(), startLoc.getY()); // find which pin to use int clickedQuad = findQuadrant(endLoc, clicked); int pin1Quad = findQuadrant(endLoc, pin1); int pin2Quad = findQuadrant(endLoc, pin2); int oppositeQuad = (clickedQuad + 2) % 4; // presume pin1 by default cornerLoc = pin1; if (pin2Quad == clickedQuad) { cornerLoc = pin2; // same quad as pin2, use pin2 } else if (pin1Quad == clickedQuad) { cornerLoc = pin1; // same quad as pin1, use pin1 } else if (pin1Quad == oppositeQuad) { cornerLoc = pin2; // near to pin2 quad, use pin2 } if (stayInside != null && useArc != null) { // make sure the bend stays inside of the merge area double pinSize = useArc.getDefaultLambdaBaseWidth(); Layer pinLayer = useArc.getLayerIterator().next(); Rectangle2D pin1Rect = new Rectangle2D.Double(pin1.getX()-pinSize/2, pin1.getY()-pinSize/2, pinSize, pinSize); Rectangle2D pin2Rect = new Rectangle2D.Double(pin2.getX()-pinSize/2, pin2.getY()-pinSize/2, pinSize, pinSize); if (stayInside.contains(pinLayer, pin1Rect)) cornerLoc = pin1; else if (stayInside.contains(pinLayer, pin2Rect)) cornerLoc = pin2; } } // never use universal arcs unless the user has selected them if (useArc == null) { // use universal if selected if (User.getUserTool().getCurrentArcProto() == Generic.tech.universal_arc) useArc = Generic.tech.universal_arc; else { route.add(endRE); route.setEnd(endRE); vroute.buildRoute(route, cell, startRE, endRE, startLoc, endLoc, cornerLoc, stayInside); return true; } } route.add(endRE); route.setEnd(endRE); // startRE and endRE can be connected with an arc. If one of them is a bisectArcPin, // and can be replaced by the other, just replace it and we're done. if (route.replaceBisectPin(startRE, endRE)) { route.remove(startRE); return true; } else if (route.replaceBisectPin(endRE, startRE)) { route.remove(endRE); route.setEnd(startRE); return true; } // find arc width to use double width = getArcWidthToUse(startRE, useArc); double width2 = getArcWidthToUse(endRE, useArc); if (width2 > width) width = width2; // see if we should only draw a single arc boolean singleArc = false; if (useArc.getAngleIncrement() == 0) singleArc = true; else { - if (useArc.getAngleIncrement() == 900) + if (useArc.getAngleIncrement() == 90) { if (endLoc.getX() == startLoc.getX() || endLoc.getY() == startLoc.getY()) singleArc = true; else { double angleD = Math.atan2(endLoc.getY()-startLoc.getY(), endLoc.getX()-startLoc.getX()); int angle = (int)Math.round(angleD * 180 / Math.PI); if ((angle % useArc.getAngleIncrement()) == 0) singleArc = true; } } } if (singleArc) { // draw single RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE, startLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside); route.add(arcRE); return true; } // this router only draws horizontal and vertical arcs // if either X or Y coords are the same, create a single arc // boolean newV = DBMath.areEquals(startLoc.getX(), endLoc.getX()) || DBMath.areEquals(startLoc.getY(), endLoc.getY()); // boolean oldV = (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY()); // if (newV != oldV) // System.out.println("Precision problem in SimpleWireer"); if (DBMath.areEquals(startLoc.getX(), endLoc.getX()) || DBMath.areEquals(startLoc.getY(), endLoc.getY())) { // single arc RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE, startLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside); route.add(arcRE); } else { // otherwise, create new pin and two arcs for corner // make new pin of arc type PrimitiveNode pn = useArc.findOverridablePinProto(); SizeOffset so = pn.getProtoSizeOffset(); double defwidth = pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset(); double defheight = pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset(); RouteElementPort pinRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), cornerLoc, defwidth, defheight); RouteElement arcRE1 = RouteElementArc.newArc(cell, useArc, width, startRE, pinRE, startLoc, cornerLoc, null, null, null, extendArcHead, extendArcTail, stayInside); RouteElement arcRE2 = RouteElementArc.newArc(cell, useArc, width, pinRE, endRE, cornerLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside); route.add(pinRE); route.add(arcRE1); route.add(arcRE2); } return true; } /** * Determines what route quadrant pt is compared to refPoint. * A route can be drawn vertically or horizontally so this * method will return a number between 0 and 3, inclusive, * where quadrants are defined based on the angle relationship * of refPoint to pt. Imagine a circle with <i>refPoint</i> as * the center and <i>pt</i> a point on the circumference of the * circle. Then theta is the angle described by the arc refPoint->pt, * and quadrants are defined as: * <code> * <p>quadrant : angle (theta) * <p>0 : -45 degrees to 45 degrees * <p>1 : 45 degress to 135 degrees * <p>2 : 135 degrees to 225 degrees * <p>3 : 225 degrees to 315 degrees (-45 degrees) * * @param refPoint reference point * @param pt variable point * @return which quadrant <i>pt</i> is in. */ protected static int findQuadrant(Point2D refPoint, Point2D pt) { // find angle double angle = Math.atan((pt.getY()-refPoint.getY())/(pt.getX()-refPoint.getX())); if (pt.getX() < refPoint.getX()) angle += Math.PI; if ((angle > -Math.PI/4) && (angle <= Math.PI/4)) return 0; else if ((angle > Math.PI/4) && (angle <= Math.PI*3/4)) return 1; else if ((angle > Math.PI*3/4) &&(angle <= Math.PI*5/4)) return 2; else return 3; } }
true
true
protected boolean planRoute(Route route, Cell cell, RouteElementPort endRE, Point2D startLoc, Point2D endLoc, Point2D clicked, PolyMerge stayInside, VerticalRoute vroute, boolean contactsOnEndObj, boolean extendArcHead, boolean extendArcTail) { RouteElementPort startRE = route.getEnd(); // find port protos of startRE and endRE, and find connecting arc type PortProto startPort = startRE.getPortProto(); PortProto endPort = endRE.getPortProto(); ArcProto useArc = getArcToUse(startPort, endPort); // first, find location of corner of L if routing will be an L shape Point2D cornerLoc = null; if (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY() || (useArc != null && (useArc.getAngleIncrement() == 0))) { // single arc if (contactsOnEndObj) cornerLoc = endLoc; else cornerLoc = startLoc; } else { Point2D pin1 = new Point2D.Double(startLoc.getX(), endLoc.getY()); Point2D pin2 = new Point2D.Double(endLoc.getX(), startLoc.getY()); // find which pin to use int clickedQuad = findQuadrant(endLoc, clicked); int pin1Quad = findQuadrant(endLoc, pin1); int pin2Quad = findQuadrant(endLoc, pin2); int oppositeQuad = (clickedQuad + 2) % 4; // presume pin1 by default cornerLoc = pin1; if (pin2Quad == clickedQuad) { cornerLoc = pin2; // same quad as pin2, use pin2 } else if (pin1Quad == clickedQuad) { cornerLoc = pin1; // same quad as pin1, use pin1 } else if (pin1Quad == oppositeQuad) { cornerLoc = pin2; // near to pin2 quad, use pin2 } if (stayInside != null && useArc != null) { // make sure the bend stays inside of the merge area double pinSize = useArc.getDefaultLambdaBaseWidth(); Layer pinLayer = useArc.getLayerIterator().next(); Rectangle2D pin1Rect = new Rectangle2D.Double(pin1.getX()-pinSize/2, pin1.getY()-pinSize/2, pinSize, pinSize); Rectangle2D pin2Rect = new Rectangle2D.Double(pin2.getX()-pinSize/2, pin2.getY()-pinSize/2, pinSize, pinSize); if (stayInside.contains(pinLayer, pin1Rect)) cornerLoc = pin1; else if (stayInside.contains(pinLayer, pin2Rect)) cornerLoc = pin2; } } // never use universal arcs unless the user has selected them if (useArc == null) { // use universal if selected if (User.getUserTool().getCurrentArcProto() == Generic.tech.universal_arc) useArc = Generic.tech.universal_arc; else { route.add(endRE); route.setEnd(endRE); vroute.buildRoute(route, cell, startRE, endRE, startLoc, endLoc, cornerLoc, stayInside); return true; } } route.add(endRE); route.setEnd(endRE); // startRE and endRE can be connected with an arc. If one of them is a bisectArcPin, // and can be replaced by the other, just replace it and we're done. if (route.replaceBisectPin(startRE, endRE)) { route.remove(startRE); return true; } else if (route.replaceBisectPin(endRE, startRE)) { route.remove(endRE); route.setEnd(startRE); return true; } // find arc width to use double width = getArcWidthToUse(startRE, useArc); double width2 = getArcWidthToUse(endRE, useArc); if (width2 > width) width = width2; // see if we should only draw a single arc boolean singleArc = false; if (useArc.getAngleIncrement() == 0) singleArc = true; else { if (useArc.getAngleIncrement() == 900) { if (endLoc.getX() == startLoc.getX() || endLoc.getY() == startLoc.getY()) singleArc = true; else { double angleD = Math.atan2(endLoc.getY()-startLoc.getY(), endLoc.getX()-startLoc.getX()); int angle = (int)Math.round(angleD * 180 / Math.PI); if ((angle % useArc.getAngleIncrement()) == 0) singleArc = true; } } } if (singleArc) { // draw single RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE, startLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside); route.add(arcRE); return true; } // this router only draws horizontal and vertical arcs // if either X or Y coords are the same, create a single arc // boolean newV = DBMath.areEquals(startLoc.getX(), endLoc.getX()) || DBMath.areEquals(startLoc.getY(), endLoc.getY()); // boolean oldV = (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY()); // if (newV != oldV) // System.out.println("Precision problem in SimpleWireer"); if (DBMath.areEquals(startLoc.getX(), endLoc.getX()) || DBMath.areEquals(startLoc.getY(), endLoc.getY())) { // single arc RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE, startLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside); route.add(arcRE); } else { // otherwise, create new pin and two arcs for corner // make new pin of arc type PrimitiveNode pn = useArc.findOverridablePinProto(); SizeOffset so = pn.getProtoSizeOffset(); double defwidth = pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset(); double defheight = pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset(); RouteElementPort pinRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), cornerLoc, defwidth, defheight); RouteElement arcRE1 = RouteElementArc.newArc(cell, useArc, width, startRE, pinRE, startLoc, cornerLoc, null, null, null, extendArcHead, extendArcTail, stayInside); RouteElement arcRE2 = RouteElementArc.newArc(cell, useArc, width, pinRE, endRE, cornerLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside); route.add(pinRE); route.add(arcRE1); route.add(arcRE2); } return true; }
protected boolean planRoute(Route route, Cell cell, RouteElementPort endRE, Point2D startLoc, Point2D endLoc, Point2D clicked, PolyMerge stayInside, VerticalRoute vroute, boolean contactsOnEndObj, boolean extendArcHead, boolean extendArcTail) { RouteElementPort startRE = route.getEnd(); // find port protos of startRE and endRE, and find connecting arc type PortProto startPort = startRE.getPortProto(); PortProto endPort = endRE.getPortProto(); ArcProto useArc = getArcToUse(startPort, endPort); // first, find location of corner of L if routing will be an L shape Point2D cornerLoc = null; if (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY() || (useArc != null && (useArc.getAngleIncrement() == 0))) { // single arc if (contactsOnEndObj) cornerLoc = endLoc; else cornerLoc = startLoc; } else { Point2D pin1 = new Point2D.Double(startLoc.getX(), endLoc.getY()); Point2D pin2 = new Point2D.Double(endLoc.getX(), startLoc.getY()); // find which pin to use int clickedQuad = findQuadrant(endLoc, clicked); int pin1Quad = findQuadrant(endLoc, pin1); int pin2Quad = findQuadrant(endLoc, pin2); int oppositeQuad = (clickedQuad + 2) % 4; // presume pin1 by default cornerLoc = pin1; if (pin2Quad == clickedQuad) { cornerLoc = pin2; // same quad as pin2, use pin2 } else if (pin1Quad == clickedQuad) { cornerLoc = pin1; // same quad as pin1, use pin1 } else if (pin1Quad == oppositeQuad) { cornerLoc = pin2; // near to pin2 quad, use pin2 } if (stayInside != null && useArc != null) { // make sure the bend stays inside of the merge area double pinSize = useArc.getDefaultLambdaBaseWidth(); Layer pinLayer = useArc.getLayerIterator().next(); Rectangle2D pin1Rect = new Rectangle2D.Double(pin1.getX()-pinSize/2, pin1.getY()-pinSize/2, pinSize, pinSize); Rectangle2D pin2Rect = new Rectangle2D.Double(pin2.getX()-pinSize/2, pin2.getY()-pinSize/2, pinSize, pinSize); if (stayInside.contains(pinLayer, pin1Rect)) cornerLoc = pin1; else if (stayInside.contains(pinLayer, pin2Rect)) cornerLoc = pin2; } } // never use universal arcs unless the user has selected them if (useArc == null) { // use universal if selected if (User.getUserTool().getCurrentArcProto() == Generic.tech.universal_arc) useArc = Generic.tech.universal_arc; else { route.add(endRE); route.setEnd(endRE); vroute.buildRoute(route, cell, startRE, endRE, startLoc, endLoc, cornerLoc, stayInside); return true; } } route.add(endRE); route.setEnd(endRE); // startRE and endRE can be connected with an arc. If one of them is a bisectArcPin, // and can be replaced by the other, just replace it and we're done. if (route.replaceBisectPin(startRE, endRE)) { route.remove(startRE); return true; } else if (route.replaceBisectPin(endRE, startRE)) { route.remove(endRE); route.setEnd(startRE); return true; } // find arc width to use double width = getArcWidthToUse(startRE, useArc); double width2 = getArcWidthToUse(endRE, useArc); if (width2 > width) width = width2; // see if we should only draw a single arc boolean singleArc = false; if (useArc.getAngleIncrement() == 0) singleArc = true; else { if (useArc.getAngleIncrement() == 90) { if (endLoc.getX() == startLoc.getX() || endLoc.getY() == startLoc.getY()) singleArc = true; else { double angleD = Math.atan2(endLoc.getY()-startLoc.getY(), endLoc.getX()-startLoc.getX()); int angle = (int)Math.round(angleD * 180 / Math.PI); if ((angle % useArc.getAngleIncrement()) == 0) singleArc = true; } } } if (singleArc) { // draw single RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE, startLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside); route.add(arcRE); return true; } // this router only draws horizontal and vertical arcs // if either X or Y coords are the same, create a single arc // boolean newV = DBMath.areEquals(startLoc.getX(), endLoc.getX()) || DBMath.areEquals(startLoc.getY(), endLoc.getY()); // boolean oldV = (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY()); // if (newV != oldV) // System.out.println("Precision problem in SimpleWireer"); if (DBMath.areEquals(startLoc.getX(), endLoc.getX()) || DBMath.areEquals(startLoc.getY(), endLoc.getY())) { // single arc RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE, startLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside); route.add(arcRE); } else { // otherwise, create new pin and two arcs for corner // make new pin of arc type PrimitiveNode pn = useArc.findOverridablePinProto(); SizeOffset so = pn.getProtoSizeOffset(); double defwidth = pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset(); double defheight = pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset(); RouteElementPort pinRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), cornerLoc, defwidth, defheight); RouteElement arcRE1 = RouteElementArc.newArc(cell, useArc, width, startRE, pinRE, startLoc, cornerLoc, null, null, null, extendArcHead, extendArcTail, stayInside); RouteElement arcRE2 = RouteElementArc.newArc(cell, useArc, width, pinRE, endRE, cornerLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside); route.add(pinRE); route.add(arcRE1); route.add(arcRE2); } return true; }
diff --git a/src/test/java/org/codehaus/gmavenplus/util/ReflectionUtilsTest.java b/src/test/java/org/codehaus/gmavenplus/util/ReflectionUtilsTest.java index 14276f2a..b49525a2 100644 --- a/src/test/java/org/codehaus/gmavenplus/util/ReflectionUtilsTest.java +++ b/src/test/java/org/codehaus/gmavenplus/util/ReflectionUtilsTest.java @@ -1,155 +1,155 @@ /* * Copyright (C) 2013 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.codehaus.gmavenplus.util; import org.junit.Assert; import org.junit.Test; /** * Unit tests for the ReflectionUtils class. * * @author Keegan Witt */ public class ReflectionUtilsTest { @Test public void testHappyPaths() throws Exception { String expectedString = "some string"; Object test1 = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(TestClass.class)); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(TestClass.class, "setStringField", String.class), test1, expectedString); Assert.assertEquals(expectedString, ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(TestClass.class, "getStringField"), test1)); - Assert.assertEquals(TestClass.HELLO_WORLD, ReflectionUtils.invokeStaticMethod(ReflectionUtils.findMethod(TestClass.class, "helloWorld"), test1)); + Assert.assertEquals(TestClass.HELLO_WORLD, ReflectionUtils.invokeStaticMethod(ReflectionUtils.findMethod(TestClass.class, "helloWorld"))); Assert.assertEquals(TestClass.ENUM.VALUE, ReflectionUtils.getEnumValue(TestClass.ENUM.class, "VALUE")); Assert.assertEquals(TestClass.HELLO_WORLD, ReflectionUtils.getStaticField(ReflectionUtils.findField(TestClass.class, "HELLO_WORLD", null))); Object test2 = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(TestClass.class, String.class), expectedString ); Assert.assertEquals(expectedString, ReflectionUtils.getField(ReflectionUtils.findField(TestClass.class, "stringField", String.class), test2)); } @Test(expected = IllegalArgumentException.class) public void testFindConstructorClassNull() { ReflectionUtils.findConstructor(null); } @Test(expected = IllegalArgumentException.class) public void testFindConstructorNotFound() { ReflectionUtils.findConstructor(TestClass.class, TestClass.class); } @Test(expected = IllegalArgumentException.class) public void testFindFieldClassNull() { ReflectionUtils.findField(null, null, null); } @Test(expected = IllegalArgumentException.class) public void testFindFieldNameAndTypeNull() { ReflectionUtils.findField(TestClass.class, null, null); } @Test(expected = IllegalArgumentException.class) public void testFindFieldNotFound() { ReflectionUtils.findField(TestClass.class, "nonExistentField", null); } @Test(expected = IllegalArgumentException.class) public void testFindMethodClassNull() { ReflectionUtils.findMethod(null, null); } @Test(expected = IllegalArgumentException.class) public void testFindMethodNameNull() { ReflectionUtils.findMethod(TestClass.class, null); } @Test(expected = IllegalArgumentException.class) public void testFindMethodNotFound() { ReflectionUtils.findMethod(TestClass.class, "nonExistentMethod"); } @Test(expected = IllegalArgumentException.class) public void testGetEnumConstantNonEnumClass() { ReflectionUtils.getEnumValue(TestClass.class, "VALUE"); } @Test(expected = IllegalArgumentException.class) public void testGetEnumConstantValueNotFound() { ReflectionUtils.getEnumValue(TestClass.ENUM.class, "NON_EXISTENT_VALUE"); } @Test(expected = IllegalArgumentException.class) public void testGetStaticFieldNotStatic() throws Exception { ReflectionUtils.getStaticField(ReflectionUtils.findField(TestClass.class, "stringField", String.class)); } @Test(expected = IllegalArgumentException.class) public void testInvokeConstructorNull() throws Exception { ReflectionUtils.invokeConstructor(null); } @Test(expected = IllegalArgumentException.class) public void testInvokeMethodMethodNull() throws Exception { ReflectionUtils.invokeMethod(null, null); } @Test(expected = IllegalArgumentException.class) public void testInvokeMethodObjectNull() throws Exception { ReflectionUtils.invokeMethod(TestClass.class.getMethod("getStringField"), null); } @Test(expected = IllegalArgumentException.class) public void testInvokeStaticMethodMethodNull() throws Exception { ReflectionUtils.invokeStaticMethod(null); } @Test(expected = IllegalArgumentException.class) public void testInvokeStaticMethodMethodNotStatic() throws Exception { ReflectionUtils.invokeStaticMethod(TestClass.class.getMethod("getStringField")); } @Test public void testConstructor() throws Exception { ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(ReflectionUtils.class)); } private static class TestClass { public static final String HELLO_WORLD = "Hello world!"; public String stringField; public TestClass() { } public TestClass(String stringField) { this.stringField = stringField; } public String getStringField() { return stringField; } public void setStringField(String stringField) { this.stringField = stringField; } public static String helloWorld() { return HELLO_WORLD; } protected static enum ENUM { VALUE } } }
true
true
public void testHappyPaths() throws Exception { String expectedString = "some string"; Object test1 = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(TestClass.class)); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(TestClass.class, "setStringField", String.class), test1, expectedString); Assert.assertEquals(expectedString, ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(TestClass.class, "getStringField"), test1)); Assert.assertEquals(TestClass.HELLO_WORLD, ReflectionUtils.invokeStaticMethod(ReflectionUtils.findMethod(TestClass.class, "helloWorld"), test1)); Assert.assertEquals(TestClass.ENUM.VALUE, ReflectionUtils.getEnumValue(TestClass.ENUM.class, "VALUE")); Assert.assertEquals(TestClass.HELLO_WORLD, ReflectionUtils.getStaticField(ReflectionUtils.findField(TestClass.class, "HELLO_WORLD", null))); Object test2 = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(TestClass.class, String.class), expectedString ); Assert.assertEquals(expectedString, ReflectionUtils.getField(ReflectionUtils.findField(TestClass.class, "stringField", String.class), test2)); }
public void testHappyPaths() throws Exception { String expectedString = "some string"; Object test1 = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(TestClass.class)); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(TestClass.class, "setStringField", String.class), test1, expectedString); Assert.assertEquals(expectedString, ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(TestClass.class, "getStringField"), test1)); Assert.assertEquals(TestClass.HELLO_WORLD, ReflectionUtils.invokeStaticMethod(ReflectionUtils.findMethod(TestClass.class, "helloWorld"))); Assert.assertEquals(TestClass.ENUM.VALUE, ReflectionUtils.getEnumValue(TestClass.ENUM.class, "VALUE")); Assert.assertEquals(TestClass.HELLO_WORLD, ReflectionUtils.getStaticField(ReflectionUtils.findField(TestClass.class, "HELLO_WORLD", null))); Object test2 = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(TestClass.class, String.class), expectedString ); Assert.assertEquals(expectedString, ReflectionUtils.getField(ReflectionUtils.findField(TestClass.class, "stringField", String.class), test2)); }
diff --git a/src/main/java/cn/mobiledaily/web/controller/NewsController.java b/src/main/java/cn/mobiledaily/web/controller/NewsController.java index 483bef0..e052591 100644 --- a/src/main/java/cn/mobiledaily/web/controller/NewsController.java +++ b/src/main/java/cn/mobiledaily/web/controller/NewsController.java @@ -1,173 +1,174 @@ package cn.mobiledaily.web.controller; import cn.mobiledaily.module.exhibition.domain.Exhibition; import cn.mobiledaily.module.news.domain.News; import cn.mobiledaily.common.exception.InternalServerError; import cn.mobiledaily.common.exception.InvalidValueException; import cn.mobiledaily.common.exception.ValidationException; import cn.mobiledaily.module.exhibition.service.ExhibitionService; import cn.mobiledaily.common.service.FileService; import cn.mobiledaily.module.news.service.NewsService; import cn.mobiledaily.common.service.SecurityService; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.multipart.MultipartFile; import java.util.LinkedList; import java.util.List; @Controller @RequestMapping("news") public class NewsController { private Logger logger = LoggerFactory.getLogger(NewsController.class); @Autowired private ExhibitionService exhibitionService; @Autowired private NewsService newsService; @Autowired private FileService fileService; @Autowired private SecurityService securityService; @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "put", method = RequestMethod.POST) public void saveNews( String pwd, String exKey, String newsKey, MultipartFile icon, String title, MultipartFile content ) { try { if (!securityService.isValidExchangePassword(pwd)) { throw new InvalidValueException("pwd", "****", pwd); } if (!StringUtils.isAlphanumeric(exKey)) { throw new InvalidValueException("exKey", "[0-9A-Za-z]", exKey); } if (!StringUtils.isAlphanumeric(newsKey)) { throw new InvalidValueException("newsKey", "[0-9A-Za-z]", newsKey); } Exhibition exhibition = exhibitionService.findByExKey(exKey); if (exhibition == null) { throw new InvalidValueException("exKey", "existed exhibition", exKey); } News news = newsService.findByNewsKey(newsKey, exhibition); if (news == null) { news = new News(); news.setExhibition(exhibition); + news.setNewsKey(newsKey); } if (StringUtils.isNotEmpty(title)) { news.setTitle(title); } if (icon != null) { fileService.save(icon.getInputStream(), exKey + "/news/" + newsKey + ".png"); } if (content != null) { fileService.save(content.getInputStream(), exKey + "/news/" + newsKey + ".html"); } newsService.save(news); } catch (ValidationException e) { throw e; } catch (Exception e) { logger.error("/news/put", e); throw new InternalServerError("/news/put", e); } } @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "delete", method = RequestMethod.POST) public void deleteNews(String pwd, String exKey, String newsKey) { try { if (!securityService.isValidExchangePassword(pwd)) { throw new InvalidValueException("pwd", "****", pwd); } newsService.delete(exKey, newsKey); } catch (ValidationException e) { throw e; } catch (Exception e) { logger.error("/news/delete", e); throw new InternalServerError("/news/delete", e); } } @RequestMapping("find") @ResponseBody public NewsObjectWrapper findNews(String exKey) { try { NewsObjectWrapper wrapper = new NewsObjectWrapper(); List<News> newses = newsService.findByExKey(exKey); for (News news : newses) { wrapper.addNews(new NewsObject(news)); } return wrapper; } catch (ValidationException e) { throw e; } catch (Exception e) { logger.error("/news/find", e); throw new InternalServerError("/news/find", e); } } public static class NewsObjectWrapper { String exKey; List<NewsObject> list = new LinkedList<>(); public void addNews(NewsObject newsObject) { list.add(newsObject); } public String getExKey() { return exKey; } public List<NewsObject> getList() { return list; } } public static class NewsObject { String newsKey; String title; long createdAt; public NewsObject(News news) { newsKey = news.getNewsKey(); title = news.getTitle(); createdAt = news.getCreatedAt().getTime(); } public String getNewsKey() { return newsKey; } public void setNewsKey(String newsKey) { this.newsKey = newsKey; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public long getCreatedAt() { return createdAt; } public void setCreatedAt(long createdAt) { this.createdAt = createdAt; } } }
true
true
public void saveNews( String pwd, String exKey, String newsKey, MultipartFile icon, String title, MultipartFile content ) { try { if (!securityService.isValidExchangePassword(pwd)) { throw new InvalidValueException("pwd", "****", pwd); } if (!StringUtils.isAlphanumeric(exKey)) { throw new InvalidValueException("exKey", "[0-9A-Za-z]", exKey); } if (!StringUtils.isAlphanumeric(newsKey)) { throw new InvalidValueException("newsKey", "[0-9A-Za-z]", newsKey); } Exhibition exhibition = exhibitionService.findByExKey(exKey); if (exhibition == null) { throw new InvalidValueException("exKey", "existed exhibition", exKey); } News news = newsService.findByNewsKey(newsKey, exhibition); if (news == null) { news = new News(); news.setExhibition(exhibition); } if (StringUtils.isNotEmpty(title)) { news.setTitle(title); } if (icon != null) { fileService.save(icon.getInputStream(), exKey + "/news/" + newsKey + ".png"); } if (content != null) { fileService.save(content.getInputStream(), exKey + "/news/" + newsKey + ".html"); } newsService.save(news); } catch (ValidationException e) { throw e; } catch (Exception e) { logger.error("/news/put", e); throw new InternalServerError("/news/put", e); } }
public void saveNews( String pwd, String exKey, String newsKey, MultipartFile icon, String title, MultipartFile content ) { try { if (!securityService.isValidExchangePassword(pwd)) { throw new InvalidValueException("pwd", "****", pwd); } if (!StringUtils.isAlphanumeric(exKey)) { throw new InvalidValueException("exKey", "[0-9A-Za-z]", exKey); } if (!StringUtils.isAlphanumeric(newsKey)) { throw new InvalidValueException("newsKey", "[0-9A-Za-z]", newsKey); } Exhibition exhibition = exhibitionService.findByExKey(exKey); if (exhibition == null) { throw new InvalidValueException("exKey", "existed exhibition", exKey); } News news = newsService.findByNewsKey(newsKey, exhibition); if (news == null) { news = new News(); news.setExhibition(exhibition); news.setNewsKey(newsKey); } if (StringUtils.isNotEmpty(title)) { news.setTitle(title); } if (icon != null) { fileService.save(icon.getInputStream(), exKey + "/news/" + newsKey + ".png"); } if (content != null) { fileService.save(content.getInputStream(), exKey + "/news/" + newsKey + ".html"); } newsService.save(news); } catch (ValidationException e) { throw e; } catch (Exception e) { logger.error("/news/put", e); throw new InternalServerError("/news/put", e); } }
diff --git a/src/com/oresomecraft/maps/arcade/ArcadeMap.java b/src/com/oresomecraft/maps/arcade/ArcadeMap.java index 6a7dd62..c8e5180 100644 --- a/src/com/oresomecraft/maps/arcade/ArcadeMap.java +++ b/src/com/oresomecraft/maps/arcade/ArcadeMap.java @@ -1,45 +1,45 @@ package com.oresomecraft.maps.arcade; import com.oresomecraft.OresomeBattles.api.events.EndBattleEvent; import com.oresomecraft.maps.Map; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; public abstract class ArcadeMap extends Map { private boolean damage = true; /** * Ends the battle */ public void end() { Bukkit.getPluginManager().callEvent(new EndBattleEvent(getMode())); } /** * Disables PvP and mob damage * * @param check The boolean to set it */ public void setAllowPhysicalDamage(boolean check) { damage = check; } /** * Disables damage caused by ENTITY_ATTACK if disabled * * @param event and Event called by bukkit */ @EventHandler public void onDamage(EntityDamageByEntityEvent event) { if (!event.getEntity().getWorld().getName().equals(name)) return; - if (!damage) return; + if (damage) return; if (event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_ATTACK)) event.setCancelled(true); } }
true
true
public void onDamage(EntityDamageByEntityEvent event) { if (!event.getEntity().getWorld().getName().equals(name)) return; if (!damage) return; if (event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_ATTACK)) event.setCancelled(true); }
public void onDamage(EntityDamageByEntityEvent event) { if (!event.getEntity().getWorld().getName().equals(name)) return; if (damage) return; if (event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_ATTACK)) event.setCancelled(true); }
diff --git a/King.java b/King.java index 2c4b37a..de68e8f 100644 --- a/King.java +++ b/King.java @@ -1,58 +1,58 @@ public class King extends Piece{ public String color; public boolean hasMoved; public boolean castled; public King(String color){ this.color = color; this.hasMoved = false; this.castled = false; } @Override public boolean validateMove(Piece[][] board, int currentRow, int currentCol, int newRow, int newCol) { if(Math.abs(newRow - currentRow) > 1 || Math.abs(newCol - currentCol) > 1){ if(hasMoved){ return false; } //Do castling logic here if(newCol - currentCol == 2 && currentRow == newRow){ //Castle kingside if(board[newRow][currentCol + 1] != null || board[newRow][currentCol + 2] != null){ castled = false; return false; } }else if(currentCol - newCol == 3 && currentRow == newRow){ if(board[newRow][currentCol - 1] != null || board[newRow][currentCol - 2] != null || board[newRow][currentCol - 3] != null){ castled = false; return false; } }else{ castled = false; return false; } castled = true; } - hasMoved = true; + //hasMoved = true; return true; } public String getColor(){ return this.color; } public String toString(){ return color.charAt(0) + "K"; } }
true
true
public boolean validateMove(Piece[][] board, int currentRow, int currentCol, int newRow, int newCol) { if(Math.abs(newRow - currentRow) > 1 || Math.abs(newCol - currentCol) > 1){ if(hasMoved){ return false; } //Do castling logic here if(newCol - currentCol == 2 && currentRow == newRow){ //Castle kingside if(board[newRow][currentCol + 1] != null || board[newRow][currentCol + 2] != null){ castled = false; return false; } }else if(currentCol - newCol == 3 && currentRow == newRow){ if(board[newRow][currentCol - 1] != null || board[newRow][currentCol - 2] != null || board[newRow][currentCol - 3] != null){ castled = false; return false; } }else{ castled = false; return false; } castled = true; } hasMoved = true; return true; }
public boolean validateMove(Piece[][] board, int currentRow, int currentCol, int newRow, int newCol) { if(Math.abs(newRow - currentRow) > 1 || Math.abs(newCol - currentCol) > 1){ if(hasMoved){ return false; } //Do castling logic here if(newCol - currentCol == 2 && currentRow == newRow){ //Castle kingside if(board[newRow][currentCol + 1] != null || board[newRow][currentCol + 2] != null){ castled = false; return false; } }else if(currentCol - newCol == 3 && currentRow == newRow){ if(board[newRow][currentCol - 1] != null || board[newRow][currentCol - 2] != null || board[newRow][currentCol - 3] != null){ castled = false; return false; } }else{ castled = false; return false; } castled = true; } //hasMoved = true; return true; }
diff --git a/freemind/freemind/view/mindmapview/MapView.java b/freemind/freemind/view/mindmapview/MapView.java index 18970c0..5d302d7 100644 --- a/freemind/freemind/view/mindmapview/MapView.java +++ b/freemind/freemind/view/mindmapview/MapView.java @@ -1,1487 +1,1487 @@ /*FreeMind - A Program for creating and viewing Mindmaps *Copyright (C) 2000-2001 Joerg Mueller <[email protected]> *See COPYING for Details * *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. */ /* $Id: MapView.java,v 1.30.16.16.2.62 2009/12/05 23:21:32 christianfoltin Exp $ */ package freemind.view.mindmapview; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.KeyboardFocusManager; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.dnd.Autoscroll; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DropTargetListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.awt.geom.CubicCurve2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; import java.util.Timer; import java.util.TimerTask; import java.util.Vector; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JViewport; import freemind.controller.Controller; import freemind.controller.NodeKeyListener; import freemind.controller.NodeMotionListener; import freemind.controller.NodeMouseMotionListener; import freemind.main.FreeMind; import freemind.main.Resources; import freemind.main.Tools; import freemind.main.Tools.Pair; import freemind.modes.MindMap; import freemind.modes.MindMapArrowLink; import freemind.modes.MindMapLink; import freemind.modes.MindMapNode; import freemind.preferences.FreemindPropertyListener; /** * This class represents the view of a whole MindMap * (in analogy to class JTree). */ public class MapView extends JPanel implements Printable, Autoscroll{ /** * Currently, this listener does nothing. * But it should move the map according to the resize event, * such that the current map's center stays at the same location * (seen relative). */ private final class ResizeListener extends ComponentAdapter { Dimension mSize; ResizeListener() { mSize = getSize(); } public void componentResized(ComponentEvent pE) { logger.fine("Component resized " +pE + " old size " + mSize + " new size " + getSize()); int deltaWidth = mSize.width - getWidth(); int deltaHeight = mSize.height - getHeight(); JViewport mapViewport = (JViewport)getParent(); Point viewPosition = mapViewport.getViewPosition(); viewPosition.x += deltaWidth/2; viewPosition.y += deltaHeight/2; // mapViewport.setViewPosition(viewPosition); mSize = getSize(); } } static public class ScrollPane extends JScrollPane{ protected void validateTree() { final Component view = getViewport().getView(); if(view != null){ view.validate(); } super.validateTree(); } } int mPaintingTime; int mPaintingAmount; static boolean printOnWhiteBackground; static Color standardMapBackgroundColor; static Color standardSelectColor; static Color standardSelectRectangleColor; public static Color standardNodeTextColor; static boolean standardDrawRectangleForSelection; private static Stroke standardSelectionStroke; static private FreemindPropertyListener propertyChangeListener; private class Selected { private Vector mySelected = new Vector(); public Selected() {}; public void clear() { if(size() >0 ) { removeSelectionForHooks(get(0)); } mySelected.clear(); logger.finest("Cleared selected."); } public int size() { return mySelected.size(); } public void remove(NodeView node) { if(mySelected.indexOf(node)==0) { removeSelectionForHooks(node); } mySelected.remove(node); logger.finest("Removed selected "+node); } public void add(NodeView node) { if(size() >0 ) { removeSelectionForHooks(get(0)); } mySelected.add(0, node); addSelectionForHooks(node); logger.finest("Added selected "+node + "\nAll="+mySelected); } private void removeSelectionForHooks(NodeView node) { if(node.getModel() == null) return; getModel().getModeController().onDeselectHook(node); } private void addSelectionForHooks(NodeView node) { getModel().getModeController().onSelectHook(node); } public NodeView get(int i) { return (NodeView) mySelected.get(i); } public boolean contains(NodeView node) { return mySelected.contains(node); } /** */ public void moveToFirst(NodeView newSelected) { if(contains(newSelected)) { int pos = mySelected.indexOf(newSelected); if( pos > 0 ){ // move if(size() >0 ) { removeSelectionForHooks(get(0)); } mySelected.remove(newSelected); mySelected.add(0, newSelected); } } else { add(newSelected); } addSelectionForHooks(newSelected); logger.finest("MovedToFront selected "+newSelected + "\nAll="+mySelected); } } // Logging: private static java.util.logging.Logger logger; private MindMap model; private NodeView rootView = null; private Selected selected = new Selected(); private Controller controller = null; private float zoom=1F; private boolean disableMoveCursor = true; private int siblingMaxLevel; private boolean isPrinting = false; // use for remove selection from print private NodeView shiftSelectionOrigin = null; private int maxNodeWidth = 0; private Color background = null; private Rectangle boundingRectangle = null; private boolean fitToPage = true; /** Used to identify a right click onto a link curve.*/ private Vector/* of ArrowLinkViews*/ ArrowLinkViews; private Point rootContentLocation; private NodeView nodeToBeVisible = null; private int extraWidth; private boolean selectedsValid = true; // // Constructors // static boolean NEED_PREF_SIZE_BUG_FIX = Controller.JAVA_VERSION.compareTo("1.5.0") < 0; public MapView( MindMap model, Controller controller ) { super(); this.model = model; this.controller= controller; + mCenterNodeTimer = new Timer(); // initialize the standard colors. if (standardNodeTextColor == null) { try{ String stdcolor = getController().getFrame().getProperty(FreeMind.RESOURCES_BACKGROUND_COLOR); standardMapBackgroundColor = Tools.xmlToColor(stdcolor); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardMapBackgroundColor = Color.WHITE; } try{ String stdcolor = getController().getFrame().getProperty(FreeMind.RESOURCES_NODE_TEXT_COLOR); standardNodeTextColor = Tools.xmlToColor(stdcolor); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardSelectColor = Color.WHITE; } // initialize the selectedColor: try{ String stdcolor = getController().getFrame().getProperty(FreeMind.RESOURCES_SELECTED_NODE_COLOR); standardSelectColor = Tools.xmlToColor(stdcolor); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardSelectColor = Color.BLUE.darker(); } // initialize the selectedTextColor: try{ String stdtextcolor = getController().getFrame().getProperty(FreeMind.RESOURCES_SELECTED_NODE_RECTANGLE_COLOR); standardSelectRectangleColor = Tools.xmlToColor(stdtextcolor); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardSelectRectangleColor = Color.WHITE; } try{ String drawCircle = getController().getFrame().getProperty(FreeMind.RESOURCE_DRAW_RECTANGLE_FOR_SELECTION); standardDrawRectangleForSelection = Tools.xmlToBoolean(drawCircle); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardDrawRectangleForSelection = false; } try { String printOnWhite = getController().getFrame().getProperty( FreeMind.RESOURCE_PRINT_ON_WHITE_BACKGROUND); printOnWhiteBackground = Tools.xmlToBoolean(printOnWhite); } catch (Exception ex) { freemind.main.Resources.getInstance().logException(ex); printOnWhiteBackground = true; } createPropertyChangeListener(); } if(logger == null) logger = controller.getFrame().getLogger(this.getClass().getName()); this.setAutoscrolls(true); this.setLayout( new MindMapLayout( ) ); initRoot(); setBackground(standardMapBackgroundColor); addMouseListener( controller.getMapMouseMotionListener() ); addMouseMotionListener( controller.getMapMouseMotionListener() ); addMouseWheelListener( controller.getMapMouseWheelListener() ); // fc, 20.6.2004: to enable tab for insert. setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET); setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET); setFocusTraversalKeys(KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, Collections.EMPTY_SET); // end change. // like in excel - write a letter means edit (PN) // on the other hand it doesn't allow key navigation (sdfe) disableMoveCursor = Resources.getInstance().getBoolProperty("disable_cursor_move_paper"); addComponentListener(new ResizeListener()); - mCenterNodeTimer = new Timer(); } private void createPropertyChangeListener() { propertyChangeListener = new FreemindPropertyListener() { public void propertyChanged(String propertyName, String newValue, String oldValue) { if (propertyName .equals(FreeMind.RESOURCES_NODE_TEXT_COLOR)) { standardNodeTextColor = Tools.xmlToColor(newValue); controller.getMapModule().getView().getRoot().updateAll(); } else if (propertyName .equals(FreeMind.RESOURCES_BACKGROUND_COLOR)) { standardMapBackgroundColor = Tools.xmlToColor(newValue); controller.getMapModule().getView().setBackground(standardMapBackgroundColor); } else if (propertyName .equals(FreeMind.RESOURCES_SELECTED_NODE_COLOR)) { standardSelectColor = Tools.xmlToColor(newValue); controller.getMapModule().getView().repaintSelecteds(); } else if (propertyName .equals(FreeMind.RESOURCES_SELECTED_NODE_RECTANGLE_COLOR)) { standardSelectRectangleColor = Tools.xmlToColor(newValue); controller.getMapModule().getView().repaintSelecteds(); } else if (propertyName .equals(FreeMind.RESOURCE_DRAW_RECTANGLE_FOR_SELECTION)) { standardDrawRectangleForSelection = Tools.xmlToBoolean(newValue); controller.getMapModule().getView().repaintSelecteds(); } else if (propertyName .equals(FreeMind.RESOURCE_PRINT_ON_WHITE_BACKGROUND)) { printOnWhiteBackground = Tools.xmlToBoolean(newValue); } } }; Controller .addPropertyChangeListener(propertyChangeListener); } public void initRoot() { rootContentLocation = new Point(); rootView = NodeViewFactory.getInstance().newNodeView( getModel().getRootNode(), 0, this, this ); rootView.insert(); revalidate(); } public int getMaxNodeWidth() { if (maxNodeWidth == 0) { try { maxNodeWidth = Integer.parseInt(controller.getProperty("max_node_width")); } catch (NumberFormatException e) { freemind.main.Resources.getInstance().logException(e); maxNodeWidth = Integer.parseInt(controller.getProperty("el__max_default_window_width")); }} return maxNodeWidth; } // // Navigation // class CheckLaterForCenterNodeTask extends TimerTask { NodeView mNode; public CheckLaterForCenterNodeTask(NodeView pNode) { super(); mNode = pNode; } public void run() { centerNode(mNode); } } /** * Problem: Before scrollRectToVisible is called, the node has the location (0,0), ie. the location first gets * calculated after the scrollpane is actually scrolled. Thus, as a workaround, I simply call scrollRectToVisible * twice, the first time the location of the node is calculated, the second time the scrollPane is actually * scrolled. */ public void centerNode( final NodeView node ) { JViewport viewPort = (JViewport)getParent(); // FIXME: Correct the resize map behaviour. Tools.waitForEventQueue(); if (!isValid()) { mCenterNodeTimer.schedule(new CheckLaterForCenterNodeTask(node), 100); return; } Dimension d = viewPort.getExtentSize(); JComponent content = node.getContent(); Rectangle rect = new Rectangle(content.getWidth()/2 - d.width/2, content.getHeight()/2 - d.height/2, d.width, d.height); logger.fine("Scroll to " + rect + ", pref size="+viewPort.getPreferredSize() + ", " + this.getPreferredSize()); // One call of scrollRectToVisible suffices // after patching the FreeMind.java // and the FreeMindApplet content.scrollRectToVisible(rect); } // scroll with extension (PN 6.2) public void scrollNodeToVisible( NodeView node ) { scrollNodeToVisible( node, 0); } // scroll with extension (PN) // e.g. the input field is bigger than the node view => scroll in order to // fit the input field into the screen public void scrollNodeToVisible( NodeView node, int extraWidth) { //see centerNode() if (! isValid()){ nodeToBeVisible = node; this.extraWidth = extraWidth; return; } final int HORIZ_SPACE = 10; final int HORIZ_SPACE2 = 20; final int VERT_SPACE = 5; final int VERT_SPACE2 = 10; // get left/right dimension final JComponent nodeContent = node.getContent(); int width = nodeContent.getWidth(); if (extraWidth < 0) { // extra left width width -= extraWidth; nodeContent.scrollRectToVisible( new Rectangle(- HORIZ_SPACE + extraWidth, - VERT_SPACE, width + HORIZ_SPACE2, nodeContent.getHeight() + VERT_SPACE2) ); } else { // extra right width width += extraWidth; nodeContent.scrollRectToVisible( new Rectangle(- HORIZ_SPACE, - VERT_SPACE, width + HORIZ_SPACE2, nodeContent.getHeight() + VERT_SPACE2) ); } } /** * Returns the size of the visible part of the view in view coordinates. */ public Dimension getViewportSize(){ JViewport mapViewport = (JViewport)getParent(); return mapViewport == null ? null : mapViewport.getSize(); } /** * Scroll the viewport of the map to the south-west, i.e. scroll the map itself to the north-east. */ public void scrollBy(int x, int y) { JViewport mapViewport = (JViewport) getParent(); if (mapViewport != null) { Point currentPoint = mapViewport.getViewPosition(); // Get View // Position currentPoint.translate(x, y); // Add the difference to it setViewLocation(currentPoint.x, currentPoint.y); } } /** * @return the position of the view or null, if not present. */ public Point getViewLocation(){ JViewport mapViewport = (JViewport) getParent(); if (mapViewport != null) { return mapViewport.getViewPosition(); } return null; } public void setViewLocation(int x, int y) { JViewport mapViewport = (JViewport) getParent(); if (mapViewport != null) { Point currentPoint = new Point(x,y); // Watch for the boundaries // Low boundaries if (currentPoint.getX() < 0) { currentPoint.setLocation(0, currentPoint.getY()); } if (currentPoint.getY() < 0) { currentPoint.setLocation(currentPoint.getX(), 0); } // High boundaries double maxX = getSize().getWidth() - mapViewport.getExtentSize().getWidth(); // getView() gets // viewed area - // JPanel double maxY = getSize().getHeight() - mapViewport.getExtentSize().getHeight(); if (currentPoint.getX() > maxX) { currentPoint.setLocation(maxX, currentPoint.getY()); } if (currentPoint.getY() > maxY) { currentPoint.setLocation(currentPoint.getX(), maxY); } mapViewport.setViewPosition(currentPoint); } } // // Node Navigation // private NodeView getVisibleLeft(NodeView oldSelected) { NodeView newSelected = oldSelected; if (oldSelected.getModel().isRoot()) { newSelected = oldSelected.getPreferredVisibleChild(true); } else if (!oldSelected.isLeft()) { newSelected = oldSelected.getVisibleParentView(); } else { // If folded in the direction, unfold if (oldSelected.getModel().isFolded()) { model.getModeController().setFolded(oldSelected.getModel(), false); return oldSelected; } newSelected = oldSelected.getPreferredVisibleChild(true); while (newSelected != null && !newSelected.isContentVisible()) { newSelected = newSelected.getPreferredVisibleChild(true); } } return newSelected; } private NodeView getVisibleRight(NodeView oldSelected) { NodeView newSelected = oldSelected; if (oldSelected.getModel().isRoot()) { newSelected = oldSelected.getPreferredVisibleChild(false); } else if (oldSelected.isLeft()) { newSelected = oldSelected.getVisibleParentView(); } else { // If folded in the direction, unfold if (oldSelected.getModel().isFolded()) { model.getModeController().setFolded(oldSelected.getModel(), false); return oldSelected; } newSelected = oldSelected.getPreferredVisibleChild(false); while (newSelected != null && !newSelected.isContentVisible()) { newSelected = newSelected.getPreferredVisibleChild(false); } } return newSelected; } private NodeView getVisibleNeighbour(int directionCode) { NodeView oldSelected = getSelected(); NodeView newSelected = null; switch (directionCode) { case KeyEvent.VK_LEFT: newSelected = getVisibleLeft(oldSelected); if(newSelected != null){ setSiblingMaxLevel(newSelected.getModel().getNodeLevel()); } return newSelected; case KeyEvent.VK_RIGHT: newSelected = getVisibleRight(oldSelected); if(newSelected != null){ setSiblingMaxLevel(newSelected.getModel().getNodeLevel()); } return newSelected; case KeyEvent.VK_UP: newSelected = oldSelected.getPreviousVisibleSibling(); break; case KeyEvent.VK_DOWN: newSelected = oldSelected.getNextVisibleSibling(); break; case KeyEvent.VK_PAGE_UP: newSelected = oldSelected.getPreviousPage(); break; case KeyEvent.VK_PAGE_DOWN: newSelected = oldSelected.getNextPage(); break; } return newSelected != oldSelected ? newSelected : null; } public void move(KeyEvent e) { NodeView newSelected = getVisibleNeighbour(e.getKeyCode()); if (newSelected != null) { if(! (newSelected == getSelected())){ extendSelectionWithKeyMove(newSelected, e); scrollNodeToVisible( newSelected ); } e.consume(); } } public void resetShiftSelectionOrigin(){ shiftSelectionOrigin = null; } private void extendSelectionWithKeyMove(NodeView newlySelectedNodeView, KeyEvent e) { if (e.isShiftDown()) { // left or right if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT) { shiftSelectionOrigin = null; NodeView toBeNewSelected = newlySelectedNodeView.isParentOf(getSelected()) ? newlySelectedNodeView : getSelected(); selectBranch(toBeNewSelected, false); makeTheSelected(toBeNewSelected); return; } if (shiftSelectionOrigin == null) { shiftSelectionOrigin = getSelected(); } final int newY = getMainViewY(newlySelectedNodeView); final int selectionOriginY = getMainViewY(shiftSelectionOrigin); int deltaY = newY - selectionOriginY; NodeView currentSelected = getSelected(); // page up and page down if (e.getKeyCode() == KeyEvent.VK_PAGE_UP) { for (;;) { final int currentSelectedY = getMainViewY(currentSelected); if (currentSelectedY > selectionOriginY) deselect(currentSelected); else makeTheSelected(currentSelected); if (currentSelectedY <= newY) break; currentSelected = currentSelected.getPreviousVisibleSibling(); } return; } if (e.getKeyCode() == KeyEvent.VK_PAGE_DOWN) { for (;;) { final int currentSelectedY = getMainViewY(currentSelected); if (currentSelectedY < selectionOriginY) deselect(currentSelected); else makeTheSelected(currentSelected); if (currentSelectedY >= newY) break; currentSelected = currentSelected.getNextVisibleSibling(); } return; } boolean enlargingMove = (deltaY > 0) && (e.getKeyCode() == KeyEvent.VK_DOWN) || (deltaY < 0) && (e.getKeyCode() == KeyEvent.VK_UP); if (enlargingMove) { toggleSelected(newlySelectedNodeView); } else { toggleSelected(getSelected()); makeTheSelected(newlySelectedNodeView); }} else { shiftSelectionOrigin = null; selectAsTheOnlyOneSelected(newlySelectedNodeView); }} private int getMainViewY(NodeView node) { Point newSelectedLocation = new Point(); Tools.convertPointToAncestor(node.getMainView(), newSelectedLocation, this); final int newY = newSelectedLocation.y; return newY; } public void moveToRoot() { selectAsTheOnlyOneSelected( getRoot() ); centerNode( getRoot() ); } /** * Select the node, resulting in only that one being selected. */ public void selectAsTheOnlyOneSelected(NodeView newSelected) { selectAsTheOnlyOneSelected(newSelected, true); } public void selectAsTheOnlyOneSelected(NodeView newSelected, boolean requestFocus) { logger.finest("selectAsTheOnlyOneSelected"); LinkedList oldSelecteds = getSelecteds(); //select new node this.selected.clear(); this.selected.add(newSelected); if(requestFocus) newSelected.requestFocus(); // getController().getMode().getDefaultModeController().onSelectHook(newSelected.getModel()); // set last focused as preferred (PN) if (newSelected.getModel().getParentNode() != null) { ((NodeView)newSelected.getParent()).setPreferredChild(newSelected); } scrollNodeToVisible(newSelected); newSelected.repaintSelected(); for(ListIterator e = oldSelecteds.listIterator();e.hasNext();) { NodeView oldSelected = (NodeView)e.next(); if (oldSelected != null) { oldSelected.repaintSelected(); } } } /** * Add the node to the selection if it is not yet there, remove it otherwise. */ public void toggleSelected(NodeView newSelected) { logger.finest("toggleSelected"); NodeView oldSelected = getSelected(); if (isSelected(newSelected)) { if (selected.size() > 1) { selected.remove(newSelected); oldSelected=newSelected; } } else { selected.add(newSelected); } getSelected().requestFocus(); getSelected().repaintSelected(); if(oldSelected != null) oldSelected.repaintSelected(); } /** * Add the node to the selection if it is not yet there, making it the focused selected node. */ public void makeTheSelected(NodeView newSelected) { logger.finest("makeTheSelected"); if (isSelected(newSelected)) { selected.moveToFirst(newSelected); } else { selected.add(newSelected); } getSelected().requestFocus(); getSelected().repaintSelected(); } public void deselect(NodeView newSelected) { if (isSelected(newSelected)) { selected.remove(newSelected); newSelected.repaintSelected(); } } /** * Select the node and his descendants. On extend = false clear up the previous selection. * if extend is false, the past selection will be empty. * if yes, the selection will extended with this node and its children */ public void selectBranch(NodeView newlySelectedNodeView, boolean extend) { //if (!extend || !isSelected(newlySelectedNodeView)) // toggleSelected(newlySelectedNodeView); if (!extend) { selectAsTheOnlyOneSelected(newlySelectedNodeView); } else if (!isSelected(newlySelectedNodeView) && newlySelectedNodeView.isContentVisible()) { toggleSelected(newlySelectedNodeView); } //select(newSelected,extend); for (ListIterator e = newlySelectedNodeView.getChildrenViews().listIterator(); e.hasNext(); ) { NodeView target = (NodeView)e.next(); selectBranch(target,true); } } public boolean selectContinuous(NodeView newSelected) { /* fc, 25.1.2004: corrected due to completely inconsistent behaviour.*/ NodeView oldSelected = null; // search for the last already selected item among the siblings: LinkedList selList = getSelecteds(); ListIterator j = selList.listIterator(/*selList.size()*/); while(j.hasNext()) { NodeView selectedNode = (NodeView)j.next(); if(selectedNode != newSelected && newSelected.isSiblingOf(selectedNode)) { oldSelected = selectedNode; break; } } // no such sibling found. select the new one, and good bye. if(oldSelected == null) { if(!isSelected(newSelected) && newSelected.isContentVisible()) { toggleSelected(newSelected); return true; } return false; } // fc, bug fix: only select the nodes on the same side: boolean oldPositionLeft = oldSelected.isLeft(); boolean newPositionLeft = newSelected.isLeft(); /* find old starting point. */ ListIterator i = newSelected.getSiblingViews().listIterator(); while (i.hasNext()) { NodeView nodeView = (NodeView)i.next(); if ( nodeView == oldSelected ) { break; } } /* Remove all selections for the siblings in the connected component between old and new.*/ ListIterator i_backup = i; while (i.hasNext()) { NodeView nodeView = (NodeView)i.next(); if((nodeView.isLeft() == oldPositionLeft || nodeView.isLeft() == newPositionLeft)) { if ( isSelected(nodeView) ) deselect(nodeView); else break; } } /* other direction. */ i = i_backup; if(i.hasPrevious()) { i.previous(); /* this is old selected! */ while (i.hasPrevious()) { NodeView nodeView = (NodeView)i.previous(); if(nodeView.isLeft() == oldPositionLeft || nodeView.isLeft() == newPositionLeft){ if ( isSelected(nodeView) ) deselect(nodeView); else break; } } } /* reset iterator */ i = newSelected.getSiblingViews().listIterator(); /* find starting point. */ i = newSelected.getSiblingViews().listIterator(); while (i.hasNext()) { NodeView nodeView = (NodeView)i.next(); if ( nodeView == newSelected || nodeView == oldSelected ) { if( ! isSelected(nodeView) && nodeView.isContentVisible()) toggleSelected(nodeView); break; } } /* select all up to the end point.*/ while (i.hasNext()) { NodeView nodeView = (NodeView)i.next(); if( (nodeView.isLeft() == oldPositionLeft || nodeView.isLeft() == newPositionLeft) && ! isSelected(nodeView) && nodeView.isContentVisible()) toggleSelected(nodeView); if ( nodeView == newSelected || nodeView == oldSelected ) { break; } } // now, make oldSelected the last of the list in order to make this repeatable: toggleSelected(oldSelected); toggleSelected(oldSelected); return true; } // // get/set methods // public MindMap getModel() { return model; } // e.g. for dragging cursor (PN) public void setMoveCursor(boolean isHand) { int requiredCursor = (isHand && !disableMoveCursor) ? Cursor.MOVE_CURSOR : Cursor.DEFAULT_CURSOR; if (getCursor().getType() != requiredCursor) { setCursor(requiredCursor != Cursor.DEFAULT_CURSOR ? new Cursor(requiredCursor) : null); } } NodeMouseMotionListener getNodeMouseMotionListener() { return getController().getNodeMouseMotionListener(); } NodeMotionListener getNodeMotionListener() { return getController().getNodeMotionListener(); } NodeKeyListener getNodeKeyListener() { return getController().getNodeKeyListener(); } DragGestureListener getNodeDragListener() { return getController().getNodeDragListener(); } DropTargetListener getNodeDropListener() { return getController().getNodeDropListener(); } public NodeView getSelected() { if(selected.size() > 0) return selected.get(0); else return null; } private NodeView getSelected(int i) { return selected.get(i); } public LinkedList getSelecteds() { // return an ArrayList of NodeViews. LinkedList result = new LinkedList(); for (int i=0; i<selected.size();i++) { result.add( getSelected(i) ); } return result; } /** * @return an ArrayList of MindMapNode objects. * If both ancestor and descendant node are selected, only the ancestor is returned */ public ArrayList /*of MindMapNodes*/ getSelectedNodesSortedByY() { final HashSet selectedNodesSet = new HashSet(); for (int i=0; i<selected.size();i++) { selectedNodesSet.add(getSelected(i).getModel()); } LinkedList pointNodePairs = new LinkedList(); Point point = new Point(); iteration: for (int i=0; i<selected.size();i++) { final NodeView view = getSelected(i); final MindMapNode node = view.getModel(); for(MindMapNode parent = node.getParentNode(); parent != null; parent = parent.getParentNode()){ if(selectedNodesSet.contains(parent)){ continue iteration; } } view.getContent().getLocation(point); Tools.convertPointToAncestor(view, point, this); pointNodePairs.add(new Pair(new Integer(point.y), node)); } // do the sorting: Collections.sort(pointNodePairs, new Comparator(){ public int compare(Object arg0, Object arg1) { if (arg0 instanceof Pair) { Pair pair0 = (Pair) arg0; if (arg1 instanceof Pair) { Pair pair1 = (Pair) arg1; Integer int0 = (Integer)pair0.getFirst(); Integer int1 = (Integer)pair1.getFirst(); return int0.compareTo(int1); } } throw new IllegalArgumentException("Wrong compare arguments "+arg0 + ", " + arg1); }}); ArrayList selectedNodes = new ArrayList(); for(Iterator it = pointNodePairs.iterator();it.hasNext();) { selectedNodes.add( ((Pair)it.next()).getSecond() ); } // logger.fine("Cutting #" + selectedNodes.size()); // for (Iterator it = selectedNodes.iterator(); it.hasNext();) { // MindMapNode node = (MindMapNode) it.next(); // logger.fine("Cutting " + node); // } return selectedNodes; } /** * @return an ArrayList of MindMapNode objects. * If both ancestor and descandant node are selected, only the ancestor ist returned */ public ArrayList /*of MindMapNodes*/ getSingleSelectedNodes() { ArrayList selectedNodes = new ArrayList(selected.size()); for (int i=selected.size()-1; i >= 0; i--) { selectedNodes.add(getSelected(i).getModel().shallowCopy()); } return selectedNodes; } public boolean isSelected(NodeView n) { if (isPrinting) return false; return selected.contains(n); } public float getZoom() { return zoom; } public int getZoomed(int number) { return (int)(number*zoom); } public void setZoom(float zoom) { this.zoom = zoom; getRoot().updateAll(); revalidate(); nodeToBeVisible = getSelected(); } /* (non-Javadoc) * @see java.awt.Container#validateTree() */ protected void validateTree() { validateSelecteds(); super.validateTree(); setViewPositionAfterValidate(); } private void setViewPositionAfterValidate() { JViewport vp = (JViewport)getParent(); Point viewPosition = vp.getViewPosition(); Point oldRootContentLocation = rootContentLocation; final NodeView root = getRoot(); Point newRootContentLocation = root.getContent().getLocation(); Tools.convertPointToAncestor(getRoot(), newRootContentLocation, getParent()); final int deltaX = newRootContentLocation.x - oldRootContentLocation.x ; final int deltaY = newRootContentLocation.y - oldRootContentLocation.y; if(deltaX != 0 || deltaY != 0) { viewPosition.x += deltaX; viewPosition.y += deltaY; final int scrollMode = vp.getScrollMode(); //avoid immediate scrolling here: vp.setScrollMode(JViewport.SIMPLE_SCROLL_MODE); vp.setViewPosition(viewPosition); vp.setScrollMode(scrollMode); } else { vp.repaint(); } if(nodeToBeVisible != null){ final int scrollMode = vp.getScrollMode(); vp.setScrollMode(JViewport.SIMPLE_SCROLL_MODE); scrollNodeToVisible(nodeToBeVisible, extraWidth); vp.setScrollMode(scrollMode); nodeToBeVisible = null; } } /***************************************************************** ** P A I N T I N G ** *****************************************************************/ // private static Image image = null; /* (non-Javadoc) * @see javax.swing.JComponent#paint(java.awt.Graphics) */ public void paint(Graphics g) { long startMilli = System.currentTimeMillis(); if(isValid()){ getRoot().getContent().getLocation(rootContentLocation); Tools.convertPointToAncestor(getRoot(), rootContentLocation, getParent()); } final Graphics2D g2 = (Graphics2D)g; final Object renderingHint = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); final Object renderingTextHint = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); getController().setTextRenderingHint(g2); final Object oldRenderingHintFM = g2.getRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS); final Object newRenderingHintFM = getZoom() != 1F ? RenderingHints.VALUE_FRACTIONALMETRICS_ON : RenderingHints.VALUE_FRACTIONALMETRICS_OFF; if(oldRenderingHintFM != newRenderingHintFM) { g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, newRenderingHintFM ); } super.paint(g); if(oldRenderingHintFM != newRenderingHintFM && RenderingHints.KEY_FRACTIONALMETRICS.isCompatibleValue(oldRenderingHintFM)) { g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, oldRenderingHintFM); } if(RenderingHints.KEY_ANTIALIASING.isCompatibleValue(renderingHint)){ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, renderingHint); } if(RenderingHints.KEY_TEXT_ANTIALIASING.isCompatibleValue(renderingTextHint)){ g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, renderingTextHint); } // final Rectangle rect = getInnerBounds(); // g2.drawRect(rect.x, rect.y, rect.width, rect.height); long localTime = System.currentTimeMillis()-startMilli; mPaintingAmount++; mPaintingTime += localTime; logger.fine("End paint of " + getModel().getRestorable() + " in "+localTime+ ". Mean time:" + (mPaintingTime/mPaintingAmount)); } public void paintChildren(Graphics graphics) { // first tries for background images. // if(image == null) { // image = MindIcon.factory("ksmiletris").getIcon(controller.getFrame()).getImage(); // } // graphics.drawImage(image, 0, 0, getHeight(), getWidth(), null); HashMap labels = new HashMap(); ArrowLinkViews = new Vector(); collectLabels(rootView, labels); super.paintChildren(graphics); Graphics2D graphics2d = (Graphics2D)graphics; Object renderingHint = getController().setEdgesRenderingHint(graphics2d); paintLinks(rootView, graphics2d, labels, null); Tools.restoreAntialiasing(graphics2d, renderingHint); paintSelecteds(graphics2d); } private void paintSelecteds(Graphics2D g) { if (!standardDrawRectangleForSelection || isCurrentlyPrinting()){ return; } final Color c = g.getColor(); final Stroke s = g.getStroke(); g.setColor(MapView.standardSelectRectangleColor); if(standardSelectionStroke == null){ standardSelectionStroke = new BasicStroke(2.0f); } g.setStroke(standardSelectionStroke); Object renderingHint = getController().setEdgesRenderingHint(g); final Iterator i = getSelecteds().iterator(); while(i.hasNext()){ NodeView selected = (NodeView) i.next(); paintSelected(g, selected); } Tools.restoreAntialiasing(g, renderingHint); g.setColor(c); g.setStroke(s); } private void paintSelected(Graphics2D g, NodeView selected) { final int arcWidth = 4; final JComponent content = selected.getContent(); Point contentLocation = new Point(); Tools.convertPointToAncestor(content, contentLocation, this); g.drawRoundRect(contentLocation.x - arcWidth, contentLocation.y - arcWidth, content.getWidth() + 2 * arcWidth, content.getHeight() + 2 * arcWidth, 15, 15); } /** collect all existing labels in the current map.*/ protected void collectLabels(NodeView source, HashMap labels) { // check for existing registry: if(getModel().getLinkRegistry()==null) return; // apply own label: String label = getModel().getLinkRegistry().getLabel(source.getModel()); if(label != null) labels.put(label, source); for(ListIterator e = source.getChildrenViews().listIterator(); e.hasNext(); ) { NodeView target = (NodeView)e.next(); collectLabels(target, labels); } } protected void paintLinks(NodeView source, Graphics2D graphics, HashMap labels, HashSet /* MindMapLink s*/ LinkAlreadyVisited) { // check for existing registry: if(getModel().getLinkRegistry()==null) return; if(LinkAlreadyVisited == null) LinkAlreadyVisited = new HashSet(); // references first // logger.fine("Searching for links of " + source.getModel().toString()); // paint own labels: Vector vec = getModel().getLinkRegistry().getAllLinks(source.getModel()); for(int i = 0; i< vec.size(); ++i) { MindMapLink ref = (MindMapLink) vec.get(i); if(LinkAlreadyVisited.add(ref)) { // determine type of link if(ref instanceof MindMapArrowLink) { ArrowLinkView arrowLink = new ArrowLinkView((MindMapArrowLink) ref, getNodeView(ref.getSource()), getNodeView(ref.getTarget())); arrowLink.paint(graphics); ArrowLinkViews.add(arrowLink); // resize map? // adjust container size // Rectangle rec = arrowLink.getBounds(); // the following does not work correctly. fc, 23.10.2003: // if (rec.x < 0) { // getMindMapLayout().resizeMap(rec.x); // } else if (rec.x+rec.width > getSize().width) { // getMindMapLayout().resizeMap(rec.x+rec.width); // } } } } for(ListIterator e = source.getChildrenViews().listIterator(); e.hasNext(); ) { NodeView target = (NodeView)e.next(); paintLinks(target, graphics, labels, LinkAlreadyVisited); } } public MindMapArrowLink detectCollision(Point p) { if(ArrowLinkViews == null) return null; for(int i = 0; i < ArrowLinkViews.size(); ++i) { ArrowLinkView arrowView = (ArrowLinkView) ArrowLinkViews.get(i); if(arrowView.detectCollision(p)) return arrowView.getModel(); } return null; } /** * Call preparePrinting() before printing * and endPrinting() after printing * to minimize calculation efforts */ public void preparePrinting() { if (!isPrinting){ isPrinting = true; /* repaint for printing:*/ if(NEED_PREF_SIZE_BUG_FIX){ getRoot().updateAll(); validate(); } else{ repaintSelecteds(); } if(printOnWhiteBackground){ background = getBackground(); setBackground(Color.WHITE); } boundingRectangle = getInnerBounds(); fitToPage = Resources.getInstance().getBoolProperty("fit_to_page"); } else { logger.warning("Called preparePrinting although isPrinting is true."); } } private void repaintSelecteds() { final Iterator iterator = getSelecteds().iterator(); while(iterator.hasNext()){ NodeView next = (NodeView)iterator.next(); next.repaintSelected(); } // repaint(); } /** * Call preparePrinting() before printing * and endPrinting() after printing * to minimize calculation efforts */ public void endPrinting() { if (isPrinting){ isPrinting = false; if(printOnWhiteBackground){ setBackground(background); } /* repaint for end printing:*/ if(NEED_PREF_SIZE_BUG_FIX){ getRoot().updateAll(); validate(); } else{ repaintSelecteds(); } } else { logger.warning("Called endPrinting although isPrinting is false."); } } public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) { // TODO: // ask user for : // - center in page (in page format ?) // - print zoom or maximize (in page format ?) // - print selection only // remember those parameters from one session to another // (as orientation & margin from pf) // User parameters double userZoomFactor = 1; try { userZoomFactor = Double.parseDouble(controller.getProperty("user_zoom")); } catch (Exception e) { // freemind.main.Resources.getInstance().logException(e); } userZoomFactor = Math.max(0,userZoomFactor); userZoomFactor = Math.min(2,userZoomFactor); // TODO: read user parameters from properties, make sure the multiple page // printing really works, have look at Book class. if (fitToPage && pageIndex > 0) { return Printable.NO_SUCH_PAGE; } Graphics2D graphics2D = (Graphics2D)graphics; try { preparePrinting(); double zoomFactor = 1; if (fitToPage) { double zoomFactorX = pageFormat.getImageableWidth()/boundingRectangle.getWidth(); double zoomFactorY = pageFormat.getImageableHeight()/boundingRectangle.getHeight(); zoomFactor = Math.min (zoomFactorX, zoomFactorY); } else { zoomFactor = userZoomFactor; int nrPagesInWidth = (int)Math.ceil(zoomFactor * boundingRectangle.getWidth() / pageFormat.getImageableWidth()); int nrPagesInHeight = (int)Math.ceil(zoomFactor *boundingRectangle.getHeight() / pageFormat.getImageableHeight()); if (pageIndex >= nrPagesInWidth * nrPagesInHeight) { return Printable.NO_SUCH_PAGE; } int yPageCoord = (int)Math.floor(pageIndex / nrPagesInWidth); int xPageCoord = pageIndex - yPageCoord * nrPagesInWidth; graphics2D.translate(- pageFormat.getImageableWidth() * xPageCoord, - pageFormat.getImageableHeight() * yPageCoord); } graphics2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); graphics2D.scale(zoomFactor, zoomFactor); graphics2D.translate(-boundingRectangle.getX(), -boundingRectangle.getY()); print(graphics2D); } finally { endPrinting(); } return Printable.PAGE_EXISTS; } // public void print(Graphics g) { // try{ // preparePrinting(); // super.print(g); // } // finally{ // endPrinting(); // } // } /** For nodes, they can ask, whether or not the width must be bigger to prevent the "..." at the output. (Bug of java).*/ public boolean isCurrentlyPrinting() { return isPrinting;}; /** * Return the bounding box of all the descendants of the source view, that without BORDER. * Should that be implemented in LayoutManager as minimum size? */ public Rectangle getInnerBounds() { final Rectangle innerBounds = getRoot().getInnerBounds(); innerBounds.x += getRoot().getX(); innerBounds.y += getRoot().getY(); final Rectangle maxBounds = new Rectangle(0, 0, getWidth(), getHeight()); for(int i = 0; i < ArrowLinkViews.size(); ++i) { ArrowLinkView arrowView = (ArrowLinkView) ArrowLinkViews.get(i); final CubicCurve2D arrowLinkCurve = arrowView.arrowLinkCurve; if(arrowLinkCurve == null){ continue; } Rectangle arrowViewBigBounds = arrowLinkCurve.getBounds(); if (! innerBounds.contains(arrowViewBigBounds)){ Rectangle arrowViewBounds =PathBBox.getBBox(arrowLinkCurve).getBounds(); innerBounds.add(arrowViewBounds); } } return innerBounds.intersection(maxBounds); } public NodeView getRoot() { return rootView; } private MindMapLayout getMindMapLayout() { return (MindMapLayout)getLayout(); } /** * This method is a workaround to allow the inner class access to "this". * Change it as soon the correct syntax is known. */ private MapView getMap() { return this; } public Controller getController() { return controller; } // this property is used when the user navigates up/down using cursor keys (PN) // it will keep the level of nodes that are understand as "siblings" public int getSiblingMaxLevel() { return this.siblingMaxLevel; } public void setSiblingMaxLevel(int level) { this.siblingMaxLevel = level; } private static final int margin = 20; private Timer mCenterNodeTimer; /* (non-Javadoc) * @see java.awt.dnd.Autoscroll#getAutoscrollInsets() */ public Insets getAutoscrollInsets() { Rectangle outer = getBounds(); Rectangle inner = getParent().getBounds(); return new Insets( inner.y - outer.y + margin, inner.x - outer.x + margin, outer.height - inner.height - inner.y + outer.y + margin, outer.width - inner.width - inner.x + outer.x + margin); } /* (non-Javadoc) * @see java.awt.dnd.Autoscroll#autoscroll(java.awt.Point) */ public void autoscroll(Point cursorLocn) { Rectangle r = new Rectangle((int)cursorLocn.getX() - margin, (int)cursorLocn.getY() - margin, 1+ 2*margin, 1+ 2*margin); scrollRectToVisible(r); } public NodeView getNodeView(MindMapNode node){ if(node == null){ return null; } Collection viewers = node.getViewers(); final Iterator iterator = viewers.iterator(); while(iterator.hasNext()){ NodeView candidateView =(NodeView) iterator.next(); if(candidateView.getMap() == this){ return candidateView; } } return null; } /* (non-Javadoc) * @see javax.swing.JComponent#getPreferredSize() */ public Dimension getPreferredSize() { if(! getParent().isValid()){ final Dimension preferredLayoutSize = getLayout().preferredLayoutSize(this); return preferredLayoutSize; } return super.getPreferredSize(); } void revalidateSelecteds() { selectedsValid = false; } private void validateSelecteds() { if(selectedsValid){ return; } selectedsValid = true; // Keep selected nodes logger.finest("validateSelecteds"); ArrayList selectedNodes = new ArrayList(); for (ListIterator it = getSelecteds().listIterator();it.hasNext();) { NodeView nodeView = (NodeView)it.next(); if (nodeView != null) { selectedNodes.add(nodeView); } } // Warning, the old views still exist, because JVM has not deleted them. But don't use them! selected.clear(); for (ListIterator it = selectedNodes.listIterator();it.hasNext();) { NodeView oldNodeView = ((NodeView)it.next()); if(oldNodeView.isContentVisible()) { NodeView newNodeView = getNodeView(oldNodeView.getModel()); // test, whether or not the node is still visible: if (newNodeView != null) { selected.add(newNodeView); } } } // if the focussed is deleted: NodeView focussedNodeView = getSelected(); // determine focussed node: if(focussedNodeView == null) { // if the focussed is deleted: focussedNodeView = getRoot(); } // now select focussed: focussedNodeView.requestFocus(); } public Point getNodeContentLocation(NodeView nodeView) { Point contentXY = new Point(0, 0); Tools.convertPointToAncestor(nodeView.getContent(), contentXY, this); return contentXY; } }
false
true
public MapView( MindMap model, Controller controller ) { super(); this.model = model; this.controller= controller; // initialize the standard colors. if (standardNodeTextColor == null) { try{ String stdcolor = getController().getFrame().getProperty(FreeMind.RESOURCES_BACKGROUND_COLOR); standardMapBackgroundColor = Tools.xmlToColor(stdcolor); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardMapBackgroundColor = Color.WHITE; } try{ String stdcolor = getController().getFrame().getProperty(FreeMind.RESOURCES_NODE_TEXT_COLOR); standardNodeTextColor = Tools.xmlToColor(stdcolor); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardSelectColor = Color.WHITE; } // initialize the selectedColor: try{ String stdcolor = getController().getFrame().getProperty(FreeMind.RESOURCES_SELECTED_NODE_COLOR); standardSelectColor = Tools.xmlToColor(stdcolor); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardSelectColor = Color.BLUE.darker(); } // initialize the selectedTextColor: try{ String stdtextcolor = getController().getFrame().getProperty(FreeMind.RESOURCES_SELECTED_NODE_RECTANGLE_COLOR); standardSelectRectangleColor = Tools.xmlToColor(stdtextcolor); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardSelectRectangleColor = Color.WHITE; } try{ String drawCircle = getController().getFrame().getProperty(FreeMind.RESOURCE_DRAW_RECTANGLE_FOR_SELECTION); standardDrawRectangleForSelection = Tools.xmlToBoolean(drawCircle); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardDrawRectangleForSelection = false; } try { String printOnWhite = getController().getFrame().getProperty( FreeMind.RESOURCE_PRINT_ON_WHITE_BACKGROUND); printOnWhiteBackground = Tools.xmlToBoolean(printOnWhite); } catch (Exception ex) { freemind.main.Resources.getInstance().logException(ex); printOnWhiteBackground = true; } createPropertyChangeListener(); } if(logger == null) logger = controller.getFrame().getLogger(this.getClass().getName()); this.setAutoscrolls(true); this.setLayout( new MindMapLayout( ) ); initRoot(); setBackground(standardMapBackgroundColor); addMouseListener( controller.getMapMouseMotionListener() ); addMouseMotionListener( controller.getMapMouseMotionListener() ); addMouseWheelListener( controller.getMapMouseWheelListener() ); // fc, 20.6.2004: to enable tab for insert. setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET); setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET); setFocusTraversalKeys(KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, Collections.EMPTY_SET); // end change. // like in excel - write a letter means edit (PN) // on the other hand it doesn't allow key navigation (sdfe) disableMoveCursor = Resources.getInstance().getBoolProperty("disable_cursor_move_paper"); addComponentListener(new ResizeListener()); mCenterNodeTimer = new Timer(); }
public MapView( MindMap model, Controller controller ) { super(); this.model = model; this.controller= controller; mCenterNodeTimer = new Timer(); // initialize the standard colors. if (standardNodeTextColor == null) { try{ String stdcolor = getController().getFrame().getProperty(FreeMind.RESOURCES_BACKGROUND_COLOR); standardMapBackgroundColor = Tools.xmlToColor(stdcolor); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardMapBackgroundColor = Color.WHITE; } try{ String stdcolor = getController().getFrame().getProperty(FreeMind.RESOURCES_NODE_TEXT_COLOR); standardNodeTextColor = Tools.xmlToColor(stdcolor); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardSelectColor = Color.WHITE; } // initialize the selectedColor: try{ String stdcolor = getController().getFrame().getProperty(FreeMind.RESOURCES_SELECTED_NODE_COLOR); standardSelectColor = Tools.xmlToColor(stdcolor); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardSelectColor = Color.BLUE.darker(); } // initialize the selectedTextColor: try{ String stdtextcolor = getController().getFrame().getProperty(FreeMind.RESOURCES_SELECTED_NODE_RECTANGLE_COLOR); standardSelectRectangleColor = Tools.xmlToColor(stdtextcolor); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardSelectRectangleColor = Color.WHITE; } try{ String drawCircle = getController().getFrame().getProperty(FreeMind.RESOURCE_DRAW_RECTANGLE_FOR_SELECTION); standardDrawRectangleForSelection = Tools.xmlToBoolean(drawCircle); } catch(Exception ex){ freemind.main.Resources.getInstance().logException(ex); standardDrawRectangleForSelection = false; } try { String printOnWhite = getController().getFrame().getProperty( FreeMind.RESOURCE_PRINT_ON_WHITE_BACKGROUND); printOnWhiteBackground = Tools.xmlToBoolean(printOnWhite); } catch (Exception ex) { freemind.main.Resources.getInstance().logException(ex); printOnWhiteBackground = true; } createPropertyChangeListener(); } if(logger == null) logger = controller.getFrame().getLogger(this.getClass().getName()); this.setAutoscrolls(true); this.setLayout( new MindMapLayout( ) ); initRoot(); setBackground(standardMapBackgroundColor); addMouseListener( controller.getMapMouseMotionListener() ); addMouseMotionListener( controller.getMapMouseMotionListener() ); addMouseWheelListener( controller.getMapMouseWheelListener() ); // fc, 20.6.2004: to enable tab for insert. setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET); setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET); setFocusTraversalKeys(KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, Collections.EMPTY_SET); // end change. // like in excel - write a letter means edit (PN) // on the other hand it doesn't allow key navigation (sdfe) disableMoveCursor = Resources.getInstance().getBoolProperty("disable_cursor_move_paper"); addComponentListener(new ResizeListener()); }
diff --git a/src/turkbait/Turkbait.java b/src/turkbait/Turkbait.java index 4b922d9..f2e05b2 100644 --- a/src/turkbait/Turkbait.java +++ b/src/turkbait/Turkbait.java @@ -1,131 +1,132 @@ package turkbait; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.File; import java.awt.Robot; import java.awt.Rectangle; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class Turkbait { public static final int X = 540; public static final int Y = 50; public static final int W = 600; public static final int H = 400; private static Robot robot; private static int mouseX, mouseY; public static void main(String[] args) { /* Create the robot. */ try { robot = new Robot(); } catch (java.awt.AWTException e) { System.out.println("Could not create Robot."); System.exit(1); return; } + robot.setAutoDelay(100); while (true) { robot.delay(1500); cast(); BufferedImage screen = getArea(); save(screen, "out.png"); if (!find(screen)) { System.out.println("error: could not find bobber!"); } BufferedImage start = getBobber(); for (int i = 0; i < 30; i++) { BufferedImage now = getBobber(); double diff = diff(start, now); System.out.println(diff); if (diff > 900) { System.out.println("BITE!"); break; } robot.delay(500); } robot.delay(500); robot.mousePress(InputEvent.BUTTON3_MASK); robot.mouseRelease(InputEvent.BUTTON3_MASK); } } private static double diff(BufferedImage a, BufferedImage b) { double sum = 0; for (int x = 0; x < a.getWidth(); x++) { for (int y = 0; y < b.getHeight(); y++) { int rgbA = a.getRGB(x, y); int rgbB = b.getRGB(x, y); int ra = (rgbA >> 16) & 0xFF; int ga = (rgbA >> 8) & 0xFF; int ba = (rgbA >> 0) & 0xFF; int rb = (rgbB >> 16) & 0xFF; int gb = (rgbB >> 8) & 0xFF; int bb = (rgbB >> 0) & 0xFF; sum += Math.pow(ra - rb, 2); sum += Math.pow(ga - gb, 2); sum += Math.pow(ba - bb, 2); } } return sum / (a.getWidth() * b.getHeight()); } private static boolean find(BufferedImage screen) { for (int x = 0; x < screen.getWidth(); x++) { for (int y = 0; y < screen.getHeight(); y++) { int rgb = screen.getRGB(x, y); int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = (rgb >> 0) & 0xFF; if (r > 50 && b < 50 && g < 50) { mouseX = X + x - 10; mouseY = Y + y; robot.mouseMove(mouseX, mouseY); return true; } } } return false; } private static void save(BufferedImage image, String name) { try { ImageIO.write(image, "PNG", new File(name)); } catch (java.io.IOException e) { System.out.println("warning: failed to save image"); } } private static BufferedImage getArea() { return robot.createScreenCapture(new Rectangle(X, Y, W, H)); } private static BufferedImage getBobber() { Rectangle r = new Rectangle(mouseX - 25, mouseY - 25, 50, 50); BufferedImage bob = robot.createScreenCapture(r); return bob; } private static BufferedImage read(String name) { try { return ImageIO.read(Turkbait.class.getResource(name)); } catch (java.io.IOException e) { System.out.println("Failed to read image."); System.exit(1); } return null; } private static void cast() { System.out.println("Casting ..."); robot.keyPress(KeyEvent.VK_J); robot.keyRelease(KeyEvent.VK_J); robot.delay(2500); } }
true
true
public static void main(String[] args) { /* Create the robot. */ try { robot = new Robot(); } catch (java.awt.AWTException e) { System.out.println("Could not create Robot."); System.exit(1); return; } while (true) { robot.delay(1500); cast(); BufferedImage screen = getArea(); save(screen, "out.png"); if (!find(screen)) { System.out.println("error: could not find bobber!"); } BufferedImage start = getBobber(); for (int i = 0; i < 30; i++) { BufferedImage now = getBobber(); double diff = diff(start, now); System.out.println(diff); if (diff > 900) { System.out.println("BITE!"); break; } robot.delay(500); } robot.delay(500); robot.mousePress(InputEvent.BUTTON3_MASK); robot.mouseRelease(InputEvent.BUTTON3_MASK); } }
public static void main(String[] args) { /* Create the robot. */ try { robot = new Robot(); } catch (java.awt.AWTException e) { System.out.println("Could not create Robot."); System.exit(1); return; } robot.setAutoDelay(100); while (true) { robot.delay(1500); cast(); BufferedImage screen = getArea(); save(screen, "out.png"); if (!find(screen)) { System.out.println("error: could not find bobber!"); } BufferedImage start = getBobber(); for (int i = 0; i < 30; i++) { BufferedImage now = getBobber(); double diff = diff(start, now); System.out.println(diff); if (diff > 900) { System.out.println("BITE!"); break; } robot.delay(500); } robot.delay(500); robot.mousePress(InputEvent.BUTTON3_MASK); robot.mouseRelease(InputEvent.BUTTON3_MASK); } }
diff --git a/de.hswt.hrm.plant.dao.jdbc/src/de/hswt/hrm/plant/dao/jdbc/PlantDao.java b/de.hswt.hrm.plant.dao.jdbc/src/de/hswt/hrm/plant/dao/jdbc/PlantDao.java index 3a088604..e189fd9e 100644 --- a/de.hswt.hrm.plant.dao.jdbc/src/de/hswt/hrm/plant/dao/jdbc/PlantDao.java +++ b/de.hswt.hrm.plant.dao.jdbc/src/de/hswt/hrm/plant/dao/jdbc/PlantDao.java @@ -1,228 +1,228 @@ package de.hswt.hrm.plant.dao.jdbc; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.dbutils.DbUtils; import static com.google.common.base.Preconditions.*; import de.hswt.hrm.common.database.DatabaseFactory; import de.hswt.hrm.common.database.NamedParameterStatement; import de.hswt.hrm.common.database.exception.DatabaseException; import de.hswt.hrm.common.database.exception.ElementNotFoundException; import de.hswt.hrm.common.database.exception.SaveException; import de.hswt.hrm.plant.model.Plant; import de.hswt.hrm.plant.dao.core.IPlantDao; public class PlantDao implements IPlantDao { @Override public Collection<Plant> findAll() throws DatabaseException { final String query = "SELECT Plant_ID, Plant_Place_FK, Plant_Inspection_Interval, " + "Plant_Manufacturer, Plant_Year_Of_Construction, Plant_Type " + "Plant_Airperformance, Plant_Motorpower, Plant_Motor_Rpm, Plant_Ventilatorperformance, " + "Plant_Current, Plant_Voltage, Plant_Note, Plant_Description FROM Plant ;"; try (Connection con = DatabaseFactory.getConnection()) { try (NamedParameterStatement stmt = NamedParameterStatement.fromConnection(con, query)) { ResultSet result = stmt.executeQuery(); Collection<Plant> plants = fromResultSet(result); DbUtils.closeQuietly(result); return plants; } } catch (SQLException e) { throw new DatabaseException(e); } } @Override public Plant findById(int id) throws DatabaseException, ElementNotFoundException { checkArgument(id >= 0, "Id must not be negative."); final String query = "SELECT Plant_ID, Plant_Inspection_Interval, " + "Plant_Manufacturer, Plant_Year_Of_Construction, Plant_Type " + "Plant_Airperformance, Plant_Motorpower, Plant_Motor_Rpm, Plant_Ventilatorperformance, " + "Plant_Current, Plant_Voltage, Plant_Note, Plant_Description FROM Plant " + "WHERE Plant_ID =:id;"; ; try (Connection con = DatabaseFactory.getConnection()) { try (NamedParameterStatement stmt = NamedParameterStatement.fromConnection(con, query)) { stmt.setParameter("id", id); ResultSet result = stmt.executeQuery(); Collection<Plant> plants = fromResultSet(result); DbUtils.closeQuietly(result); if (plants.size() < 1) { throw new ElementNotFoundException(); } else if (plants.size() > 1) { throw new DatabaseException("ID '" + id + "' is not unique."); } return plants.iterator().next(); } } catch (SQLException e) { throw new DatabaseException(e); } } /** * @see {@link IPlantDao#insert(Plant)} */ @Override public Plant insert(Plant plant) throws SaveException { final String query = "INSERT INTO Plant (Plant_Place_FK, Plant_Inspection_Interval, " - + "Plant_Manufacturer, Plant_Year_Of_Construction, Plant_Type " + + "Plant_Manufacturer, Plant_Year_Of_Construction, Plant_Type, " + "Plant_Airperformance, Plant_Motorpower, Plant_Motor_Rpm, Plant_Ventilatorperformance, " + "Plant_Current, Plant_Voltage, Plant_Note, Plant_Description) " + "VALUES (:plantPlaceFk, :inspectionInterval, :manufactor, :constructionYear, :type, " + ":airPerformance, :motorPower, :motorRpm, :ventilatorPerformance, :current, :voltage, " + ":note, :description);"; try (Connection con = DatabaseFactory.getConnection()) { try (NamedParameterStatement stmt = NamedParameterStatement.fromConnection(con, query)) { stmt.setParameter("description", plant.getDescription()); stmt.setParameter("inspectionInterval", plant.getInspectionInterval()); stmt.setParameter("plantPlaceFk", plant.getPlace().get().getId()); stmt.setParameter("constructionYear", plant.getConstructionYear().orNull()); stmt.setParameter("manufactor", plant.getManufactor().orNull()); stmt.setParameter("type", plant.getType().orNull()); stmt.setParameter("airPerformance", plant.getAirPerformance().orNull()); stmt.setParameter("motorPower", plant.getMotorPower().orNull()); stmt.setParameter("motorRpm", plant.getMotorRpm().orNull()); stmt.setParameter("ventilatorPerformance", plant.getVentilatorPerformance() .orNull()); stmt.setParameter("current", plant.getCurrent().orNull()); stmt.setParameter("voltage", plant.getVoltage().orNull()); stmt.setParameter("note", plant.getNote().orNull()); int affectedRows = stmt.executeUpdate(); if (affectedRows != 1) { throw new SaveException(); } try (ResultSet generatedKeys = stmt.getGeneratedKeys()) { if (generatedKeys.next()) { int id = generatedKeys.getInt(1); // Create new plant with id Plant inserted = new Plant(id, plant.getInspectionInterval(), plant.getDescription()); inserted.setConstructionYear(plant.getConstructionYear().orNull()); inserted.setManufactor(plant.getManufactor().orNull()); inserted.setType(plant.getType().orNull()); inserted.setAirPerformance(plant.getAirPerformance().orNull()); inserted.setMotorPower(plant.getMotorPower().orNull()); inserted.setMotorRpm(plant.getMotorRpm().orNull()); inserted.setVentilatorPerformance(plant.getVentilatorPerformance().orNull()); inserted.setCurrent(plant.getCurrent().orNull()); inserted.setVoltage(plant.getVoltage().orNull()); inserted.setNote(plant.getNote().orNull()); inserted.setPlace(plant.getPlace().orNull()); return inserted; } else { throw new SaveException("Could not retrieve generated ID."); } } } } catch (SQLException | DatabaseException e) { throw new SaveException(e); } } @Override public void update(Plant plant) throws ElementNotFoundException, SaveException { checkNotNull(plant, "Plant must not be null."); if (plant.getId() < 0) { throw new ElementNotFoundException("Element has no valid ID."); } final String query = "UPDATE Plant SET " + "Plant_Place_FK = :plantPlaceFk, " + "Plant_Inspection_Interval = :inspectionInterval, " + "Plant_Manufacturer = :manufactor, " + "Plant_Year_Of_Construction = :constructionYear, " + "Plant_Type = :type, " + "Plant_Airperformance = :airPerformance, " + "Plant_Motorpower = :motorPower, " + "Plant_Motor_Rpm = :motorRpm, " + "Plant_Ventilatorperformance = :ventilatorPerformance, " + "Plant_Current = :current, " + "Plant_Voltage = :voltage " + "Plant_Note = :note, " + "Plant_Description = :description " + "WHERE Plant_ID = :id;"; try (Connection con = DatabaseFactory.getConnection()) { try (NamedParameterStatement stmt = NamedParameterStatement.fromConnection(con, query)) { stmt.setParameter("description", plant.getDescription()); stmt.setParameter("inspectionInterval", plant.getInspectionInterval()); stmt.setParameter("plantPlaceFk", plant.getPlace().get().getId()); stmt.setParameter("constructionYear", plant.getConstructionYear().orNull()); stmt.setParameter("manufactor", plant.getManufactor().orNull()); stmt.setParameter("type", plant.getType().orNull()); stmt.setParameter("airPerformance", plant.getAirPerformance().orNull()); stmt.setParameter("motorPower", plant.getMotorPower().orNull()); stmt.setParameter("motorRpm", plant.getMotorRpm().orNull()); stmt.setParameter("ventilatorPerformance", plant.getVentilatorPerformance() .orNull()); stmt.setParameter("current", plant.getCurrent().orNull()); stmt.setParameter("voltage", plant.getVoltage().orNull()); stmt.setParameter("note", plant.getNote().orNull()); int affectedRows = stmt.executeUpdate(); if (affectedRows != 1) { throw new SaveException(); } } } catch (SQLException | DatabaseException e) { throw new SaveException(e); } } private Collection<Plant> fromResultSet(ResultSet rs) throws SQLException { checkNotNull(rs, "Result must not be null."); Collection<Plant> plantList = new ArrayList<>(); while (rs.next()) { // "SELECT Plant_ID, Plant_Place_FK, Plant_Inspection_Interval, " // + "Plant_Manufacturer, Plant_Year_Of_Construction, Plant_Type" // + // "Plant_Airperformance, Plant_Motorpower, Plant_Motor_Rpm, Plant_Ventilatorperformance, " // + "Plant_Current, Plant_Voltage, Plant_Note, Plant_Description FROM Plant ;"; int id = rs.getInt("plant_ID"); int inspectionInterval = rs.getInt("Plant_Inspection_Interval"); String description = rs.getString("Plant_Description"); Plant plant = new Plant(id, inspectionInterval, description); plant.setConstructionYear(rs.getInt("Plant_Year_Of_Construction")); plant.setManufactor(rs.getString("Plant_Manufacturer")); plant.setType(rs.getString("Plant_Type")); plant.setAirPerformance(rs.getString("Plant_Airperformance")); plant.setMotorPower(rs.getString("Plant_Motorpower")); plant.setMotorRpm(rs.getString("Plant_Motor_Rpm")); plant.setVentilatorPerformance(rs.getString("Plant_Ventilatorperformance")); plant.setCurrent(rs.getString("Plant_Current")); plant.setVoltage(rs.getString("Plant_Voltage")); plant.setNote(rs.getString("Plant_Note")); plantList.add(plant); } return plantList; } }
true
true
public Plant insert(Plant plant) throws SaveException { final String query = "INSERT INTO Plant (Plant_Place_FK, Plant_Inspection_Interval, " + "Plant_Manufacturer, Plant_Year_Of_Construction, Plant_Type " + "Plant_Airperformance, Plant_Motorpower, Plant_Motor_Rpm, Plant_Ventilatorperformance, " + "Plant_Current, Plant_Voltage, Plant_Note, Plant_Description) " + "VALUES (:plantPlaceFk, :inspectionInterval, :manufactor, :constructionYear, :type, " + ":airPerformance, :motorPower, :motorRpm, :ventilatorPerformance, :current, :voltage, " + ":note, :description);"; try (Connection con = DatabaseFactory.getConnection()) { try (NamedParameterStatement stmt = NamedParameterStatement.fromConnection(con, query)) { stmt.setParameter("description", plant.getDescription()); stmt.setParameter("inspectionInterval", plant.getInspectionInterval()); stmt.setParameter("plantPlaceFk", plant.getPlace().get().getId()); stmt.setParameter("constructionYear", plant.getConstructionYear().orNull()); stmt.setParameter("manufactor", plant.getManufactor().orNull()); stmt.setParameter("type", plant.getType().orNull()); stmt.setParameter("airPerformance", plant.getAirPerformance().orNull()); stmt.setParameter("motorPower", plant.getMotorPower().orNull()); stmt.setParameter("motorRpm", plant.getMotorRpm().orNull()); stmt.setParameter("ventilatorPerformance", plant.getVentilatorPerformance() .orNull()); stmt.setParameter("current", plant.getCurrent().orNull()); stmt.setParameter("voltage", plant.getVoltage().orNull()); stmt.setParameter("note", plant.getNote().orNull()); int affectedRows = stmt.executeUpdate(); if (affectedRows != 1) { throw new SaveException(); } try (ResultSet generatedKeys = stmt.getGeneratedKeys()) { if (generatedKeys.next()) { int id = generatedKeys.getInt(1); // Create new plant with id Plant inserted = new Plant(id, plant.getInspectionInterval(), plant.getDescription()); inserted.setConstructionYear(plant.getConstructionYear().orNull()); inserted.setManufactor(plant.getManufactor().orNull()); inserted.setType(plant.getType().orNull()); inserted.setAirPerformance(plant.getAirPerformance().orNull()); inserted.setMotorPower(plant.getMotorPower().orNull()); inserted.setMotorRpm(plant.getMotorRpm().orNull()); inserted.setVentilatorPerformance(plant.getVentilatorPerformance().orNull()); inserted.setCurrent(plant.getCurrent().orNull()); inserted.setVoltage(plant.getVoltage().orNull()); inserted.setNote(plant.getNote().orNull()); inserted.setPlace(plant.getPlace().orNull()); return inserted; } else { throw new SaveException("Could not retrieve generated ID."); } } } } catch (SQLException | DatabaseException e) { throw new SaveException(e); } }
public Plant insert(Plant plant) throws SaveException { final String query = "INSERT INTO Plant (Plant_Place_FK, Plant_Inspection_Interval, " + "Plant_Manufacturer, Plant_Year_Of_Construction, Plant_Type, " + "Plant_Airperformance, Plant_Motorpower, Plant_Motor_Rpm, Plant_Ventilatorperformance, " + "Plant_Current, Plant_Voltage, Plant_Note, Plant_Description) " + "VALUES (:plantPlaceFk, :inspectionInterval, :manufactor, :constructionYear, :type, " + ":airPerformance, :motorPower, :motorRpm, :ventilatorPerformance, :current, :voltage, " + ":note, :description);"; try (Connection con = DatabaseFactory.getConnection()) { try (NamedParameterStatement stmt = NamedParameterStatement.fromConnection(con, query)) { stmt.setParameter("description", plant.getDescription()); stmt.setParameter("inspectionInterval", plant.getInspectionInterval()); stmt.setParameter("plantPlaceFk", plant.getPlace().get().getId()); stmt.setParameter("constructionYear", plant.getConstructionYear().orNull()); stmt.setParameter("manufactor", plant.getManufactor().orNull()); stmt.setParameter("type", plant.getType().orNull()); stmt.setParameter("airPerformance", plant.getAirPerformance().orNull()); stmt.setParameter("motorPower", plant.getMotorPower().orNull()); stmt.setParameter("motorRpm", plant.getMotorRpm().orNull()); stmt.setParameter("ventilatorPerformance", plant.getVentilatorPerformance() .orNull()); stmt.setParameter("current", plant.getCurrent().orNull()); stmt.setParameter("voltage", plant.getVoltage().orNull()); stmt.setParameter("note", plant.getNote().orNull()); int affectedRows = stmt.executeUpdate(); if (affectedRows != 1) { throw new SaveException(); } try (ResultSet generatedKeys = stmt.getGeneratedKeys()) { if (generatedKeys.next()) { int id = generatedKeys.getInt(1); // Create new plant with id Plant inserted = new Plant(id, plant.getInspectionInterval(), plant.getDescription()); inserted.setConstructionYear(plant.getConstructionYear().orNull()); inserted.setManufactor(plant.getManufactor().orNull()); inserted.setType(plant.getType().orNull()); inserted.setAirPerformance(plant.getAirPerformance().orNull()); inserted.setMotorPower(plant.getMotorPower().orNull()); inserted.setMotorRpm(plant.getMotorRpm().orNull()); inserted.setVentilatorPerformance(plant.getVentilatorPerformance().orNull()); inserted.setCurrent(plant.getCurrent().orNull()); inserted.setVoltage(plant.getVoltage().orNull()); inserted.setNote(plant.getNote().orNull()); inserted.setPlace(plant.getPlace().orNull()); return inserted; } else { throw new SaveException("Could not retrieve generated ID."); } } } } catch (SQLException | DatabaseException e) { throw new SaveException(e); } }
diff --git a/src/main/java/ee/ignorance/transformiceapi/event/EventService.java b/src/main/java/ee/ignorance/transformiceapi/event/EventService.java index ba7392b..fe69c72 100644 --- a/src/main/java/ee/ignorance/transformiceapi/event/EventService.java +++ b/src/main/java/ee/ignorance/transformiceapi/event/EventService.java @@ -1,36 +1,36 @@ package ee.ignorance.transformiceapi.event; import java.util.ArrayList; import java.util.List; public class EventService { private List<EventListener> listeners; public EventService() { listeners = new ArrayList<EventListener>(); } public synchronized void registerEventListener(EventListener listener) { synchronized(listeners){ listeners.add(listener); } } public synchronized void unregisterEventListener(EventListener listener) { synchronized(listeners){ listeners.remove(listener); } } - public void notifyListeners(Event e) { + public synchronized void notifyListeners(Event e) { synchronized(listeners){ for (EventListener listener : listeners) { if (listener.matches(e)) { listener.actionPerformed(e); } } } } }
true
true
public void notifyListeners(Event e) { synchronized(listeners){ for (EventListener listener : listeners) { if (listener.matches(e)) { listener.actionPerformed(e); } } } }
public synchronized void notifyListeners(Event e) { synchronized(listeners){ for (EventListener listener : listeners) { if (listener.matches(e)) { listener.actionPerformed(e); } } } }
diff --git a/luni/src/test/java/tests/xml/AllTests.java b/luni/src/test/java/tests/xml/AllTests.java index 2e12a59c5..8fd809670 100644 --- a/luni/src/test/java/tests/xml/AllTests.java +++ b/luni/src/test/java/tests/xml/AllTests.java @@ -1,49 +1,48 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tests.xml; import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { public static Test suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(DeclarationTest.class); suite.addTestSuite(DomTest.class); suite.addTestSuite(SimpleParserTest.class); suite.addTestSuite(SimpleBuilderTest.class); suite.addTestSuite(NodeTest.class); suite.addTestSuite(NormalizeTest.class); suite.addTestSuite(SaxTest.class); //suite.addTest(tests.org.w3c.dom.AllTests.suite()); suite.addTest(tests.api.javax.xml.parsers.AllTests.suite()); suite.addTest(tests.api.org.xml.sax.AllTests.suite()); // BEGIN android-changed: this is in the dom module! // suite.addTest(tests.api.org.w3c.dom.AllTests.suite()); // END android-changed suite.addTest(tests.org.w3c.dom.AllTests.suite()); - suite.addTest(org.apache.harmony.xml.AllTests.suite()); suite.addTest(org.kxml2.io.AllTests.suite()); return suite; } }
true
true
public static Test suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(DeclarationTest.class); suite.addTestSuite(DomTest.class); suite.addTestSuite(SimpleParserTest.class); suite.addTestSuite(SimpleBuilderTest.class); suite.addTestSuite(NodeTest.class); suite.addTestSuite(NormalizeTest.class); suite.addTestSuite(SaxTest.class); //suite.addTest(tests.org.w3c.dom.AllTests.suite()); suite.addTest(tests.api.javax.xml.parsers.AllTests.suite()); suite.addTest(tests.api.org.xml.sax.AllTests.suite()); // BEGIN android-changed: this is in the dom module! // suite.addTest(tests.api.org.w3c.dom.AllTests.suite()); // END android-changed suite.addTest(tests.org.w3c.dom.AllTests.suite()); suite.addTest(org.apache.harmony.xml.AllTests.suite()); suite.addTest(org.kxml2.io.AllTests.suite()); return suite; }
public static Test suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(DeclarationTest.class); suite.addTestSuite(DomTest.class); suite.addTestSuite(SimpleParserTest.class); suite.addTestSuite(SimpleBuilderTest.class); suite.addTestSuite(NodeTest.class); suite.addTestSuite(NormalizeTest.class); suite.addTestSuite(SaxTest.class); //suite.addTest(tests.org.w3c.dom.AllTests.suite()); suite.addTest(tests.api.javax.xml.parsers.AllTests.suite()); suite.addTest(tests.api.org.xml.sax.AllTests.suite()); // BEGIN android-changed: this is in the dom module! // suite.addTest(tests.api.org.w3c.dom.AllTests.suite()); // END android-changed suite.addTest(tests.org.w3c.dom.AllTests.suite()); suite.addTest(org.kxml2.io.AllTests.suite()); return suite; }
diff --git a/Alkitab/src/yuku/alkitab/base/IsiActivity.java b/Alkitab/src/yuku/alkitab/base/IsiActivity.java index cd4000a0..cfb1fe0d 100644 --- a/Alkitab/src/yuku/alkitab/base/IsiActivity.java +++ b/Alkitab/src/yuku/alkitab/base/IsiActivity.java @@ -1,2080 +1,2082 @@ package yuku.alkitab.base; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.PendingIntent; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentFilter.MalformedMimeTypeException; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.NfcAdapter.CreateNdefMessageCallback; import android.nfc.NfcEvent; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.FragmentManager; import android.support.v4.app.ShareCompat; import android.support.v7.view.ActionMode; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.style.ForegroundColorSpan; import android.text.style.RelativeSizeSpan; import android.util.Log; import android.util.Pair; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AbsListView; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ListAdapter; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import yuku.afw.V; import yuku.afw.storage.Preferences; import yuku.afw.widget.EasyAdapter; import yuku.alkitab.base.ac.AboutActivity; import yuku.alkitab.base.ac.BookmarkActivity; import yuku.alkitab.base.ac.DevotionActivity; import yuku.alkitab.base.ac.GotoActivity; import yuku.alkitab.base.ac.HelpActivity; import yuku.alkitab.base.ac.ReadingPlanActivity; import yuku.alkitab.base.ac.Search2Activity; import yuku.alkitab.base.ac.SettingsActivity; import yuku.alkitab.base.ac.ShareActivity; import yuku.alkitab.base.ac.SongViewActivity; import yuku.alkitab.base.ac.VersionsActivity; import yuku.alkitab.base.ac.VersionsActivity.MVersion; import yuku.alkitab.base.ac.VersionsActivity.MVersionInternal; import yuku.alkitab.base.ac.VersionsActivity.MVersionPreset; import yuku.alkitab.base.ac.VersionsActivity.MVersionYes; import yuku.alkitab.base.ac.base.BaseActivity; import yuku.alkitab.base.config.AppConfig; import yuku.alkitab.base.dialog.ProgressMarkDialog; import yuku.alkitab.base.dialog.TypeBookmarkDialog; import yuku.alkitab.base.dialog.TypeHighlightDialog; import yuku.alkitab.base.dialog.TypeNoteDialog; import yuku.alkitab.base.dialog.XrefDialog; import yuku.alkitab.base.model.Ari; import yuku.alkitab.base.model.Book; import yuku.alkitab.base.model.FootnoteEntry; import yuku.alkitab.base.model.PericopeBlock; import yuku.alkitab.base.model.ProgressMark; import yuku.alkitab.base.model.SingleChapterVerses; import yuku.alkitab.base.model.Version; import yuku.alkitab.base.storage.Prefkey; import yuku.alkitab.base.util.BackupManager; import yuku.alkitab.base.util.History; import yuku.alkitab.base.util.IntArrayList; import yuku.alkitab.base.util.Jumper; import yuku.alkitab.base.util.LidToAri; import yuku.alkitab.base.util.Search2Engine.Query; import yuku.alkitab.base.util.Sqlitil; import yuku.alkitab.base.widget.AttributeView; import yuku.alkitab.base.widget.CallbackSpan; import yuku.alkitab.base.widget.Floater; import yuku.alkitab.base.widget.FormattedTextRenderer; import yuku.alkitab.base.widget.GotoButton; import yuku.alkitab.base.widget.LabeledSplitHandleButton; import yuku.alkitab.base.widget.ReadingPlanFloatMenu; import yuku.alkitab.base.widget.SplitHandleButton; import yuku.alkitab.base.widget.TextAppearancePanel; import yuku.alkitab.base.widget.VerseInlineLinkSpan; import yuku.alkitab.base.widget.VerseRenderer; import yuku.alkitab.base.widget.VersesView; import yuku.alkitab.base.widget.VersesView.PressResult; import yuku.alkitab.debug.R; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; public class IsiActivity extends BaseActivity implements XrefDialog.XrefDialogListener, ProgressMarkDialog.ProgressMarkDialogListener { public static final String TAG = IsiActivity.class.getSimpleName(); // The followings are for instant_pref private static final String PREFKEY_lastBook = "kitabTerakhir"; //$NON-NLS-1$ private static final String PREFKEY_lastChapter = "pasalTerakhir"; //$NON-NLS-1$ private static final String PREFKEY_lastVerse = "ayatTerakhir"; //$NON-NLS-1$ private static final String PREFKEY_lastVersion = "edisiTerakhir"; //$NON-NLS-1$ private static final String PREFKEY_devotion_name = "renungan_nama"; //$NON-NLS-1$ private static final int REQCODE_goto = 1; private static final int REQCODE_bookmark = 2; private static final int REQCODE_devotion = 3; private static final int REQCODE_settings = 4; private static final int REQCODE_version = 5; private static final int REQCODE_search = 6; private static final int REQCODE_share = 7; private static final int REQCODE_songs = 8; private static final int REQCODE_textAppearanceGetFonts = 9; private static final int REQCODE_textAppearanceCustomColors = 10; private static final int REQCODE_readingPlan = 11; private static final String EXTRA_verseUrl = "verseUrl"; //$NON-NLS-1$ private boolean uncheckVersesWhenActionModeDestroyed = true; private GotoButton.FloaterDragListener bGoto_floaterDrag = new GotoButton.FloaterDragListener() { final int[] floaterLocationOnScreen = {0, 0}; @Override public void onFloaterDragStart(final float screenX, final float screenY) { floater.setVisibility(View.VISIBLE); floater.onDragStart(S.activeVersion); } @Override public void onFloaterDragMove(final float screenX, final float screenY) { floater.getLocationOnScreen(floaterLocationOnScreen); floater.onDragMove(screenX - floaterLocationOnScreen[0], screenY - floaterLocationOnScreen[1]); } @Override public void onFloaterDragComplete(final float screenX, final float screenY) { floater.setVisibility(View.GONE); floater.onDragComplete(screenX - floaterLocationOnScreen[0], screenY - floaterLocationOnScreen[1]); } }; private Floater.Listener floater_listener = new Floater.Listener() { @Override public void onSelectComplete(final int ari) { jumpToAri(ari); history.add(ari); } }; @Override public void onProgressMarkSelected(final int ari) { jumpToAri(ari); history.add(ari); } @Override public void onProgressMarkDeleted(final int ari) { reloadVerse(); } class FullScreenController { void hidePermanently() { getSupportActionBar().hide(); panelNavigation.setVisibility(View.GONE); } void showPermanently() { getSupportActionBar().show(); panelNavigation.setVisibility(View.VISIBLE); } } FrameLayout overlayContainer; View root; VersesView lsText; VersesView lsSplit1; TextView tSplitEmpty; View splitRoot; View splitHandle; LabeledSplitHandleButton splitHandleButton; FrameLayout panelNavigation; GotoButton bGoto; ImageButton bLeft; ImageButton bRight; Floater floater; ReadingPlanFloatMenu readingPlanFloatMenu; Book activeBook; int chapter_1 = 0; SharedPreferences instant_pref; boolean fullScreen; FullScreenController fullScreenController = new FullScreenController(); Toast fullScreenDismissHint; History history; NfcAdapter nfcAdapter; ActionMode actionMode; TextAppearancePanel textAppearancePanel; //# state storage for search2 Query search2_query = null; IntArrayList search2_results = null; int search2_selectedPosition = -1; // temporary states Boolean hasEsvsbAsal; Version activeSplitVersion; String activeSplitVersionId; CallbackSpan.OnClickListener parallelListener = new CallbackSpan.OnClickListener() { @Override public void onClick(View widget, Object data) { if (data instanceof String) { final int ari = jumpTo((String) data); if (ari != 0) { history.add(ari); } } else if (data instanceof Integer) { final int ari = (Integer) data; jumpToAri(ari); history.add(ari); } } }; public static Intent createIntent(int ari) { Intent res = new Intent(App.context, IsiActivity.class); res.setAction("yuku.alkitab.action.VIEW"); res.putExtra("ari", ari); return res; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState, false); setContentView(R.layout.activity_isi); overlayContainer = V.get(this, R.id.overlayContainer); root = V.get(this, R.id.root); lsText = V.get(this, R.id.lsSplit0); lsSplit1 = V.get(this, R.id.lsSplit1); tSplitEmpty = V.get(this, R.id.tSplitEmpty); splitRoot = V.get(this, R.id.splitRoot); splitHandle = V.get(this, R.id.splitHandle); splitHandleButton = V.get(this, R.id.splitHandleButton); panelNavigation = V.get(this, R.id.panelNavigation); bGoto = V.get(this, R.id.bGoto); bLeft = V.get(this, R.id.bLeft); bRight = V.get(this, R.id.bRight); floater = V.get(this, R.id.floater); readingPlanFloatMenu = V.get(this, R.id.readingPlanFloatMenu); applyPreferences(false); bGoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bGoto_click(); } }); bGoto.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { bGoto_longClick(); return true; } }); bGoto.setFloaterDragListener(bGoto_floaterDrag); bLeft.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bLeft_click(); } }); bRight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bRight_click(); } }); floater.setListener(floater_listener); lsText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { int action = event.getAction(); if (action == KeyEvent.ACTION_DOWN) { return press(keyCode); } else if (action == KeyEvent.ACTION_MULTIPLE) { return press(keyCode); } return false; } }); // listeners lsText.setParallelListener(parallelListener); lsText.setAttributeListener(attributeListener); lsText.setInlineLinkSpanFactory(new VerseInlineLinkSpanFactory(lsText)); lsText.setSelectedVersesListener(lsText_selectedVerses); lsText.setOnVerseScrollListener(lsText_verseScroll); lsText.setOnVerseScrollStateChangeListener(lsText_verseScrollState); // additional setup for split1 lsSplit1.setVerseSelectionMode(VersesView.VerseSelectionMode.multiple); lsSplit1.setEmptyView(tSplitEmpty); lsSplit1.setParallelListener(parallelListener); lsSplit1.setAttributeListener(attributeListener); lsSplit1.setInlineLinkSpanFactory(new VerseInlineLinkSpanFactory(lsSplit1)); lsSplit1.setSelectedVersesListener(lsSplit1_selectedVerses); lsSplit1.setOnVerseScrollListener(lsSplit1_verseScroll); // for splitting splitHandleButton.setListener(splitHandleButton_listener); history = History.getInstance(); // configure devotion instant_pref = App.getInstantPreferences(); { String devotion_name = instant_pref.getString(PREFKEY_devotion_name, null); if (devotion_name != null) { for (String nama: DevotionActivity.AVAILABLE_NAMES) { if (devotion_name.equals(nama)) { DevotionActivity.Temporaries.devotion_name = devotion_name; } } } } // restore the last (version; book; chapter and verse). String lastVersion = instant_pref.getString(PREFKEY_lastVersion, null); int lastBook = instant_pref.getInt(PREFKEY_lastBook, 0); int lastChapter = instant_pref.getInt(PREFKEY_lastChapter, 0); int lastVerse = instant_pref.getInt(PREFKEY_lastVerse, 0); Log.d(TAG, "Going to the last: version=" + lastVersion + " book=" + lastBook + " chapter=" + lastBook + " verse=" + lastVerse); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ loadLastVersion(lastVersion); { // load book Book book = S.activeVersion.getBook(lastBook); if (book != null) { this.activeBook = book; } else { // can't load last book or bookId 0 this.activeBook = S.activeVersion.getFirstBook(); } } // load chapter and verse display(lastChapter, lastVerse); if (Build.VERSION.SDK_INT >= 14) { initNfcIfAvailable(); } if (S.getDb().countAllBookmarks() != 0) { BackupManager.startAutoBackup(); } processIntent(getIntent(), "onCreate"); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); processIntent(intent, "onNewIntent"); } private void processIntent(Intent intent, String via) { Log.d(TAG, "Got intent via " + via); Log.d(TAG, " action: " + intent.getAction()); Log.d(TAG, " data uri: " + intent.getData()); Log.d(TAG, " component: " + intent.getComponent()); Log.d(TAG, " flags: 0x" + Integer.toHexString(intent.getFlags())); Log.d(TAG, " mime: " + intent.getType()); Bundle extras = intent.getExtras(); Log.d(TAG, " extras: " + (extras == null? "null": extras.size())); if (extras != null) { for (String key: extras.keySet()) { Log.d(TAG, " " + key + " = " + extras.get(key)); } } if (Build.VERSION.SDK_INT >= 14) { checkAndProcessBeamIntent(intent); } checkAndProcessViewIntent(intent); } /** did we get here from VIEW intent? */ private void checkAndProcessViewIntent(Intent intent) { if (!U.equals(intent.getAction(), "yuku.alkitab.action.VIEW")) return; if (intent.hasExtra("ari")) { int ari = intent.getIntExtra("ari", 0); if (ari != 0) { jumpToAri(ari); history.add(ari); } else { new AlertDialog.Builder(this) .setMessage("Invalid ari: " + ari) .setPositiveButton(R.string.ok, null) .show(); } } else if (intent.hasExtra("lid")) { int lid = intent.getIntExtra("lid", 0); int ari = LidToAri.lidToAri(lid); if (ari != 0) { jumpToAri(ari); history.add(ari); } else { new AlertDialog.Builder(this) .setMessage("Invalid lid: " + lid) .setPositiveButton(R.string.ok, null) .show(); } } } @TargetApi(14) private void initNfcIfAvailable() { nfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext()); if (nfcAdapter != null) { nfcAdapter.setNdefPushMessageCallback(new CreateNdefMessageCallback() { @Override public NdefMessage createNdefMessage(NfcEvent event) { JSONObject obj = new JSONObject(); try { obj.put("ari", Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, lsText.getVerseBasedOnScroll())); //$NON-NLS-1$ } catch (JSONException e) { // won't happen } byte[] payload = obj.toString().getBytes(); NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "application/vnd.yuku.alkitab.nfc.beam".getBytes(), new byte[0], payload); //$NON-NLS-1$ return new NdefMessage(new NdefRecord[] { record, NdefRecord.createApplicationRecord(getPackageName()), }); } }, this); } } @Override protected void onPause() { super.onPause(); if (Build.VERSION.SDK_INT >= 14) { disableNfcForegroundDispatchIfAvailable(); } } @TargetApi(14) private void disableNfcForegroundDispatchIfAvailable() { if (nfcAdapter != null) nfcAdapter.disableForegroundDispatch(this); } @Override protected void onResume() { super.onResume(); if (Build.VERSION.SDK_INT >= 14) { enableNfcForegroundDispatchIfAvailable(); } } @TargetApi(14) private void enableNfcForegroundDispatchIfAvailable() { if (nfcAdapter != null) { PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, IsiActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); try { ndef.addDataType("application/vnd.yuku.alkitab.nfc.beam"); //$NON-NLS-1$ } catch (MalformedMimeTypeException e) { throw new RuntimeException("fail mime type", e); //$NON-NLS-1$ } IntentFilter[] intentFiltersArray = new IntentFilter[] {ndef, }; nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, null); } } @TargetApi(14) private void checkAndProcessBeamIntent(Intent intent) { String action = intent.getAction(); if (U.equals(action, NfcAdapter.ACTION_NDEF_DISCOVERED)) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); // only one message sent during the beam if (rawMsgs != null && rawMsgs.length > 0) { NdefMessage msg = (NdefMessage) rawMsgs[0]; // record 0 contains the MIME type, record 1 is the AAR, if present NdefRecord[] records = msg.getRecords(); if (records != null && records.length > 0) { String json = new String(records[0].getPayload()); try { JSONObject obj = new JSONObject(json); int ari = obj.optInt("ari", -1); //$NON-NLS-1$ if (ari != -1) { jumpToAri(ari); history.add(ari); } } catch (JSONException e) { Log.e(TAG, "Malformed json from nfc", e); //$NON-NLS-1$ } } } } } private void loadLastVersion(String lastVersion) { AppConfig c = AppConfig.get(); if (lastVersion == null || MVersionInternal.getVersionInternalId().equals(lastVersion)) { // we are now already on internal splitHandleButton.setLabel1("\u25b2 " + c.internalShortName); return; } // coba preset dulu! for (MVersionPreset preset: c.presets) { // 2. preset if (preset.getVersionId().equals(lastVersion)) { if (preset.hasDataFile()) { if (loadVersion(preset, false)) return; } else { return; // this is the one that should have been chosen, but the data file is not available, so let's fallback. } } } // masih belum cocok, mari kita cari di daftar yes List<MVersionYes> yeses = S.getDb().listAllVersions(); for (MVersionYes yes: yeses) { if (yes.getVersionId().equals(lastVersion)) { if (yes.hasDataFile()) { if (loadVersion(yes, false)) return; } else { return; // this is the one that should have been chosen, but the data file is not available, so let's fallback. } } } } boolean loadVersion(final MVersion mv, boolean display) { try { Version version = mv.getVersion(); if (version != null) { if (this.activeBook != null) { // we already have some other version loaded, so make the new version open the same book int bookId = this.activeBook.bookId; Book book = version.getBook(bookId); if (book != null) { // we load the new book succesfully this.activeBook = book; } else { // too bad, this book was not found, get any book this.activeBook = version.getFirstBook(); } } S.activeVersion = version; S.activeVersionId = mv.getVersionId(); splitHandleButton.setLabel1("\u25b2 " + getSplitHandleVersionName(mv, version)); if (display) { display(chapter_1, lsText.getVerseBasedOnScroll(), false); } return true; } else { throw new RuntimeException(getString(R.string.ada_kegagalan_membuka_edisiid, mv.getVersionId())); } } catch (Throwable e) { // so we don't crash on the beginning of the app Log.e(TAG, "Error opening main version", e); new AlertDialog.Builder(IsiActivity.this) .setMessage(getString(R.string.ada_kegagalan_membuka_edisiid, mv.getVersionId())) .setPositiveButton(R.string.ok, null) .show(); return false; } } boolean loadSplitVersion(final MVersion mv) { try { Version version = mv.getVersion(); if (version != null) { activeSplitVersion = version; activeSplitVersionId = mv.getVersionId(); splitHandleButton.setLabel2(getSplitHandleVersionName(mv, version) + " \u25bc"); return true; } else { throw new RuntimeException(getString(R.string.ada_kegagalan_membuka_edisiid, mv.getVersionId())); } } catch (Throwable e) { // so we don't crash on the beginning of the app Log.e(TAG, "Error opening split version", e); new AlertDialog.Builder(IsiActivity.this) .setMessage(getString(R.string.ada_kegagalan_membuka_edisiid, mv.getVersionId())) .setPositiveButton(R.string.ok, null) .show(); return false; } } String getSplitHandleVersionName(MVersion mv, Version version) { String shortName = version.getShortName(); if (shortName != null) { return shortName; } else { // try to get it from the model if (mv.shortName != null) { return mv.shortName; } return version.getLongName(); // this will not be null } } boolean press(int keyCode) { if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { bLeft_click(); return true; } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { bRight_click(); return true; } PressResult pressResult = lsText.press(keyCode); switch (pressResult) { case left: bLeft_click(); return true; case right: bRight_click(); return true; case consumed: return true; default: return false; } } /** * Jump to a given verse reference in string format. * @return ari of the parsed reference */ int jumpTo(String reference) { if (reference.trim().length() == 0) { return 0; } Log.d(TAG, "going to jump to " + reference); //$NON-NLS-1$ Jumper jumper = new Jumper(reference); if (! jumper.getParseSucceeded()) { Toast.makeText(this, getString(R.string.alamat_tidak_sah_alamat, reference), Toast.LENGTH_SHORT).show(); return 0; } int bookId = jumper.getBookId(S.activeVersion.getConsecutiveBooks()); Book selected; if (bookId != -1) { Book book = S.activeVersion.getBook(bookId); if (book != null) { selected = book; } else { // not avail, just fallback selected = this.activeBook; } } else { selected = this.activeBook; } // set book this.activeBook = selected; int chapter = jumper.getChapter(); int verse = jumper.getVerse(); int ari_cv; if (chapter == -1 && verse == -1) { ari_cv = display(1, 1); } else { ari_cv = display(chapter, verse); } return Ari.encode(selected.bookId, ari_cv); } /** * Jump to a given ari */ void jumpToAri(int ari) { if (ari == 0) return; Log.d(TAG, "will jump to ari 0x" + Integer.toHexString(ari)); //$NON-NLS-1$ int bookId = Ari.toBook(ari); Book book = S.activeVersion.getBook(bookId); if (book != null) { this.activeBook = book; } else { Log.w(TAG, "bookId=" + bookId + " not found for ari=" + ari); //$NON-NLS-1$ //$NON-NLS-2$ return; } display(Ari.toChapter(ari), Ari.toVerse(ari)); } private CharSequence referenceFromSelectedVerses(IntArrayList selectedVerses, Book book) { if (selectedVerses.size() == 0) { // should not be possible. So we don't do anything. return book.reference(this.chapter_1); } else if (selectedVerses.size() == 1) { return book.reference(this.chapter_1, selectedVerses.get(0)); } else { return book.reference(this.chapter_1, selectedVerses); } } CharSequence prepareTextForCopyShare(IntArrayList selectedVerses_1, CharSequence reference, boolean isSplitVersion) { StringBuilder res = new StringBuilder(); res.append(reference); if (Preferences.getBoolean(getString(R.string.pref_copyWithVerseNumbers_key), false) && selectedVerses_1.size() > 1) { res.append('\n'); // append each selected verse with verse number prepended for (int i = 0; i < selectedVerses_1.size(); i++) { int verse_1 = selectedVerses_1.get(i); res.append(verse_1); res.append(' '); if (isSplitVersion) { res.append(U.removeSpecialCodes(lsSplit1.getVerse(verse_1))); } else { res.append(U.removeSpecialCodes(lsText.getVerse(verse_1))); } res.append('\n'); } } else { res.append(" "); //$NON-NLS-1$ // append each selected verse without verse number prepended for (int i = 0; i < selectedVerses_1.size(); i++) { int verse_1 = selectedVerses_1.get(i); if (i != 0) res.append('\n'); if (isSplitVersion) { res.append(U.removeSpecialCodes(lsSplit1.getVerse(verse_1))); } else { res.append(U.removeSpecialCodes(lsText.getVerse(verse_1))); } } } return res; } private void applyPreferences(boolean languageToo) { // appliance of background color { root.setBackgroundColor(S.applied.backgroundColor); lsText.setCacheColorHint(S.applied.backgroundColor); lsSplit1.setCacheColorHint(S.applied.backgroundColor); } if (languageToo) { App.updateConfigurationWithPreferencesLocale(); } // necessary lsText.invalidateViews(); lsSplit1.invalidateViews(); } @Override protected void onStop() { super.onStop(); final Editor editor = instant_pref.edit(); editor.putInt(PREFKEY_lastBook, this.activeBook.bookId); editor.putInt(PREFKEY_lastChapter, chapter_1); editor.putInt(PREFKEY_lastVerse, lsText.getVerseBasedOnScroll()); editor.putString(PREFKEY_devotion_name, DevotionActivity.Temporaries.devotion_name); editor.putString(PREFKEY_lastVersion, S.activeVersionId); if (Build.VERSION.SDK_INT >= 9) { editor.apply(); } else { editor.commit(); } history.save(); lsText.setKeepScreenOn(false); } @Override protected void onStart() { super.onStart(); if (Preferences.getBoolean(getString(R.string.pref_keepScreenOn_key), getResources().getBoolean(R.bool.pref_nyalakanTerusLayar_default))) { lsText.setKeepScreenOn(true); } } @Override public void onBackPressed() { if (fullScreen) { setFullScreen(false); } else if (textAppearancePanel != null) { textAppearancePanel.hide(); textAppearancePanel = null; } else { super.onBackPressed(); } } void bGoto_click() { startActivityForResult(GotoActivity.createIntent(this.activeBook.bookId, this.chapter_1, lsText.getVerseBasedOnScroll()), REQCODE_goto); } void bGoto_longClick() { if (history.getSize() > 0) { new AlertDialog.Builder(this) .setAdapter(historyAdapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int ari = history.getAri(which); jumpToAri(ari); history.add(ari); Preferences.setBoolean(Prefkey.history_button_understood, true); } }) .setNegativeButton(R.string.cancel, null) .show(); } else { Toast.makeText(this, R.string.recentverses_not_available, Toast.LENGTH_SHORT).show(); } } private ListAdapter historyAdapter = new EasyAdapter() { private final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(App.context); private final java.text.DateFormat mediumDateFormat = DateFormat.getMediumDateFormat(App.context); @Override public View newView(final int position, final ViewGroup parent) { return getLayoutInflater().inflate(android.R.layout.simple_list_item_1, parent, false); } @Override public void bindView(final View view, final int position, final ViewGroup parent) { TextView textView = (TextView) view; int ari = history.getAri(position); SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(S.activeVersion.reference(ari)); sb.append(" "); int sb_len = sb.length(); sb.append(formatTimestamp(history.getTimestamp(position))); sb.setSpan(new ForegroundColorSpan(0xff666666), sb_len, sb.length(), 0); sb.setSpan(new RelativeSizeSpan(0.7f), sb_len, sb.length(), 0); textView.setText(sb); } private CharSequence formatTimestamp(final long timestamp) { { long now = System.currentTimeMillis(); long delta = now - timestamp; if (delta <= 200000) { return getString(R.string.recentverses_just_now); } else if (delta <= 3600000) { return getString(R.string.recentverses_min_plural_ago, Math.round(delta / 60000.0)); } } { Calendar now = GregorianCalendar.getInstance(); Calendar that = GregorianCalendar.getInstance(); that.setTimeInMillis(timestamp); if (now.get(Calendar.YEAR) == that.get(Calendar.YEAR)) { if (now.get(Calendar.DAY_OF_YEAR) == that.get(Calendar.DAY_OF_YEAR)) { return getString(R.string.recentverses_today_time, timeFormat.format(that.getTime())); } else if (now.get(Calendar.DAY_OF_YEAR) == that.get(Calendar.DAY_OF_YEAR) + 1) { return getString(R.string.recentverses_yesterday_time, timeFormat.format(that.getTime())); } } return mediumDateFormat.format(that.getTime()); } } @Override public int getCount() { return history.getSize(); } }; public void openDonationDialog() { new AlertDialog.Builder(this) .setMessage(R.string.donasi_keterangan) .setPositiveButton(R.string.donasi_tombol_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String donation_url = getString(R.string.alamat_donasi); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(donation_url)); startActivity(intent); } }) .setNegativeButton(R.string.donasi_tombol_gamau, null) .show(); } public void buildMenu(Menu menu) { menu.clear(); getMenuInflater().inflate(R.menu.activity_isi, menu); AppConfig c = AppConfig.get(); //# build config menu.findItem(R.id.menuDevotion).setVisible(c.menuDevotion); menu.findItem(R.id.menuVersions).setVisible(c.menuVersions); menu.findItem(R.id.menuHelp).setVisible(c.menuHelp); menu.findItem(R.id.menuDonation).setVisible(c.menuDonation); menu.findItem(R.id.menuSongs).setVisible(c.menuSongs); // checkable menu items menu.findItem(R.id.menuTextAppearance).setChecked(textAppearancePanel != null); menu.findItem(R.id.menuFullScreen).setChecked(fullScreen); } @Override public boolean onCreateOptionsMenu(Menu menu) { buildMenu(menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (menu != null) { buildMenu(menu); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuBookmark: startActivityForResult(new Intent(this, BookmarkActivity.class), REQCODE_bookmark); return true; case R.id.menuListProgressMark: openProgressMarkDialog(); return true; case R.id.menuSearch: menuSearch_click(); return true; case R.id.menuVersions: openVersionsDialog(); return true; case R.id.menuSplitVersion: openSplitVersionsDialog(); return true; case R.id.menuDevotion: startActivityForResult(new Intent(this, DevotionActivity.class), REQCODE_devotion); return true; case R.id.menuSongs: startActivityForResult(SongViewActivity.createIntent(), REQCODE_songs); return true; case R.id.menuReadingPlan: startActivityForResult(new Intent(this, ReadingPlanActivity.class), REQCODE_readingPlan); return true; case R.id.menuAbout: startActivity(new Intent(this, AboutActivity.class)); return true; case R.id.menuFullScreen: setFullScreen(!item.isChecked()); return true; case R.id.menuTextAppearance: setShowTextAppearancePanel(!item.isChecked()); return true; case R.id.menuSettings: startActivityForResult(new Intent(this, SettingsActivity.class), REQCODE_settings); return true; case R.id.menuHelp: startActivity(HelpActivity.createIntent(false)); return true; case R.id.menuSendMessage: startActivity(HelpActivity.createIntent(true)); return true; case R.id.menuDonation: openDonationDialog(); return true; } return super.onOptionsItemSelected(item); } void setFullScreen(boolean yes) { if (yes) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); fullScreenController.hidePermanently(); fullScreen = true; if (fullScreenDismissHint == null) { fullScreenDismissHint = Toast.makeText(this, R.string.full_screen_dismiss_hint, Toast.LENGTH_SHORT); } fullScreenDismissHint.show(); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); fullScreenController.showPermanently(); fullScreen = false; } } void setShowTextAppearancePanel(boolean yes) { if (yes) { if (textAppearancePanel == null) { // not showing yet textAppearancePanel = new TextAppearancePanel(this, getLayoutInflater(), overlayContainer, new TextAppearancePanel.Listener() { @Override public void onValueChanged() { S.calculateAppliedValuesBasedOnPreferences(); applyPreferences(false); } }, REQCODE_textAppearanceGetFonts, REQCODE_textAppearanceCustomColors); textAppearancePanel.show(); } } else { if (textAppearancePanel != null) { textAppearancePanel.hide(); textAppearancePanel = null; } } } private Pair<List<String>, List<MVersion>> getAvailableVersions() { // populate with // 1. internal // 2. presets that have been DOWNLOADED and ACTIVE // 3. yeses that are ACTIVE AppConfig c = AppConfig.get(); final List<String> options = new ArrayList<String>(); // sync with below line final List<MVersion> data = new ArrayList<MVersion>(); // sync with above line options.add(c.internalLongName); // 1. internal data.add(new MVersionInternal()); for (MVersionPreset preset: c.presets) { // 2. preset if (preset.hasDataFile() && preset.getActive()) { options.add(preset.longName); data.add(preset); } } // 3. active yeses List<MVersionYes> yeses = S.getDb().listAllVersions(); for (MVersionYes yes: yeses) { if (yes.hasDataFile() && yes.getActive()) { options.add(yes.longName); data.add(yes); } } return Pair.create(options, data); } void openVersionsDialog() { Pair<List<String>, List<MVersion>> versions = getAvailableVersions(); final List<String> options = versions.first; final List<MVersion> data = versions.second; int selected = -1; if (S.activeVersionId == null) { selected = 0; } else { for (int i = 0; i < data.size(); i++) { MVersion mv = data.get(i); if (mv.getVersionId().equals(S.activeVersionId)) { selected = i; break; } } } new AlertDialog.Builder(this) .setSingleChoiceItems(options.toArray(new String[options.size()]), selected, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final MVersion mv = data.get(which); loadVersion(mv, true); dialog.dismiss(); } }) .setPositiveButton(R.string.versi_lainnya, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivityForResult(VersionsActivity.createIntent(), REQCODE_version); } }) .setNegativeButton(R.string.cancel, null) .show(); } private void openProgressMarkDialog() { FragmentManager fm = getSupportFragmentManager(); ProgressMarkDialog dialog = new ProgressMarkDialog(); dialog.show(fm, "progress_mark_dialog"); } void openSplitVersionsDialog() { Pair<List<String>, List<MVersion>> versions = getAvailableVersions(); final List<String> options = versions.first; final List<MVersion> data = versions.second; options.add(0, getString(R.string.split_version_none)); data.add(0, null); int selected = -1; if (this.activeSplitVersionId == null) { selected = 0; } else { for (int i = 1 /* because 0 is null */; i < data.size(); i++) { MVersion mv = data.get(i); if (mv.getVersionId().equals(this.activeSplitVersionId)) { selected = i; break; } } } new AlertDialog.Builder(this) .setSingleChoiceItems(options.toArray(new String[options.size()]), selected, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final MVersion mv = data.get(which); if (mv == null) { // closing split version activeSplitVersion = null; activeSplitVersionId = null; closeSplit(); } else { boolean ok = loadSplitVersion(mv); if (ok) { openSplit(); displaySplitFollowingMaster(); } else { activeSplitVersion = null; activeSplitVersionId = null; closeSplit(); } } dialog.dismiss(); } void openSplit() { if (splitHandle.getVisibility() == View.VISIBLE) { return; // it's already split, no need to do anything } // measure split handle splitHandle.setVisibility(View.VISIBLE); splitHandle.measure(MeasureSpec.makeMeasureSpec(lsText.getWidth(), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int splitHandleHeight = splitHandle.getMeasuredHeight(); int totalHeight = splitRoot.getHeight(); int masterHeight = totalHeight / 2 - splitHandleHeight / 2; // divide by 2 the screen space ViewGroup.LayoutParams lp = lsText.getLayoutParams(); lp.height = masterHeight; lsText.setLayoutParams(lp); // no need to set height, because it has been set to match_parent, so it takes // the remaining space. lsSplit1.setVisibility(View.VISIBLE); } void closeSplit() { if (splitHandle.getVisibility() == View.GONE) { return; // it's already not split, no need to do anything } splitHandle.setVisibility(View.GONE); lsSplit1.setVisibility(View.GONE); ViewGroup.LayoutParams lp = lsText.getLayoutParams(); lp.height = ViewGroup.LayoutParams.MATCH_PARENT; lsText.setLayoutParams(lp); } }) .setPositiveButton(R.string.versi_lainnya, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivityForResult(VersionsActivity.createIntent(), REQCODE_version); } }) .setNegativeButton(R.string.cancel, null) .show(); } private void menuSearch_click() { startActivityForResult(Search2Activity.createIntent(search2_query, search2_results, search2_selectedPosition, this.activeBook.bookId), REQCODE_search); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQCODE_goto) { if (resultCode == RESULT_OK) { GotoActivity.Result result = GotoActivity.obtainResult(data); if (result != null) { // change book Book book = S.activeVersion.getBook(result.bookId); if (book != null) { this.activeBook = book; } else { // no book, just chapter and verse. result.bookId = this.activeBook.bookId; } int ari_cv = display(result.chapter_1, result.verse_1); history.add(Ari.encode(result.bookId, ari_cv)); } } } else if (requestCode == REQCODE_bookmark) { lsText.reloadAttributeMap(); if (activeSplitVersion != null) { lsSplit1.reloadAttributeMap(); } } else if (requestCode == REQCODE_search) { if (resultCode == RESULT_OK) { Search2Activity.Result result = Search2Activity.obtainResult(data); if (result != null) { if (result.selectedAri != -1) { jumpToAri(result.selectedAri); history.add(result.selectedAri); } search2_query = result.query; search2_results = result.searchResults; search2_selectedPosition = result.selectedPosition; } } } else if (requestCode == REQCODE_devotion) { if (resultCode == RESULT_OK) { DevotionActivity.Result result = DevotionActivity.obtainResult(data); if (result != null && result.ari != 0) { jumpToAri(result.ari); history.add(result.ari); } } } else if (requestCode == REQCODE_songs) { if (resultCode == SongViewActivity.RESULT_gotoScripture && data != null) { String ref = data.getStringExtra(SongViewActivity.EXTRA_ref); if (ref != null) { // TODO int ari = jumpTo(ref); if (ari != 0) { history.add(ari); } } } } else if (requestCode == REQCODE_settings) { // MUST reload preferences S.calculateAppliedValuesBasedOnPreferences(); applyPreferences(true); if (resultCode == SettingsActivity.RESULT_openTextAppearance) { setShowTextAppearancePanel(true); } } else if (requestCode == REQCODE_share) { if (resultCode == RESULT_OK) { ShareActivity.Result result = ShareActivity.obtainResult(data); if (result != null && result.chosenIntent != null) { Intent chosenIntent = result.chosenIntent; if (U.equals(chosenIntent.getComponent().getPackageName(), "com.facebook.katana")) { //$NON-NLS-1$ String verseUrl = chosenIntent.getStringExtra(EXTRA_verseUrl); if (verseUrl != null) { chosenIntent.putExtra(Intent.EXTRA_TEXT, verseUrl); // change text to url } } startActivity(chosenIntent); } } } else if (requestCode == REQCODE_textAppearanceGetFonts) { if (textAppearancePanel != null) textAppearancePanel.onActivityResult(requestCode, resultCode, data); } else if (requestCode == REQCODE_textAppearanceCustomColors) { if (textAppearancePanel != null) textAppearancePanel.onActivityResult(requestCode, resultCode, data); // MUST reload preferences S.calculateAppliedValuesBasedOnPreferences(); applyPreferences(true); } else if (requestCode == REQCODE_readingPlan) { if (data == null && !readingPlanFloatMenu.isActive) { return; } else if (data == null) { if (readingPlanFloatMenu.getReadingPlanId() != Preferences.getLong(Prefkey.active_reading_plan, 0)) { readingPlanFloatMenu.setVisibility(View.GONE); + readingPlanFloatMenu.isActive = false; return; } readingPlanFloatMenu.setVisibility(View.VISIBLE); + readingPlanFloatMenu.fadeoutAnimation(5000); readingPlanFloatMenu.updateProgress(); readingPlanFloatMenu.updateLayout(); return; } readingPlanFloatMenu.setVisibility(View.VISIBLE); readingPlanFloatMenu.isActive = true; final int ari = data.getIntExtra("ari", 0); final long id = data.getLongExtra(ReadingPlanActivity.READING_PLAN_ID, 0L); final int dayNumber = data.getIntExtra(ReadingPlanActivity.READING_PLAN_DAY_NUMBER, 0); final int[] ariRanges = data.getIntArrayExtra(ReadingPlanActivity.READING_PLAN_ARI_RANGES); if (ari != 0 && ariRanges != null) { for (int i = 0; i < ariRanges.length; i++) { if (ariRanges[i] == ari) { jumpToAri(ari); history.add(ari); int[] ariRangesInThisSequence = new int[2]; ariRangesInThisSequence[0] = ariRanges[i]; ariRangesInThisSequence[1] = ariRanges[i + 1]; lsText.setAriRangesReadingPlan(ariRangesInThisSequence); lsText.updateAdapter(); readingPlanFloatMenu.load(id, dayNumber, ariRanges, i); readingPlanFloatMenu.setLeftNavigationClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { readingPlanFloatMenu.clearAnimation(); jumpToAri(ari_0); history.add(ari_0); lsText.setAriRangesReadingPlan(new int[] {ari_0, ari_1}); lsText.updateAdapter(); readingPlanFloatMenu.fadeoutAnimation(5000); } }); readingPlanFloatMenu.setRightNavigationClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { readingPlanFloatMenu.clearAnimation(); jumpToAri(ari_0); history.add(ari_0); lsText.setAriRangesReadingPlan(new int[] {ari_0, ari_1}); lsText.updateAdapter(); readingPlanFloatMenu.fadeoutAnimation(5000); } }); readingPlanFloatMenu.setDescriptionListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { startActivityForResult(ReadingPlanActivity.createIntent(dayNumber), REQCODE_readingPlan); } }); readingPlanFloatMenu.setReadMarkClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { readingPlanFloatMenu.clearAnimation(); readingPlanFloatMenu.fadeoutAnimation(5000); } }); readingPlanFloatMenu.setCloseReadingModeClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { readingPlanFloatMenu.clearAnimation(); readingPlanFloatMenu.setVisibility(View.GONE); readingPlanFloatMenu.isActive = false; lsText.setAriRangesReadingPlan(null); lsText.updateAdapter(); } }); readingPlanFloatMenu.fadeoutAnimation(5000); break; } } } } } /** * Display specified chapter and verse of the active book. By default all checked verses will be unchecked. * @return Ari that contains only chapter and verse. Book always set to 0. */ int display(int chapter_1, int verse_1) { return display(chapter_1, verse_1, true); } /** * Display specified chapter and verse of the active book. * @param uncheckAllVerses whether we want to always make all verses unchecked after this operation. * @return Ari that contains only chapter and verse. Book always set to 0. */ int display(int chapter_1, int verse_1, boolean uncheckAllVerses) { int current_chapter_1 = this.chapter_1; if (chapter_1 < 1) chapter_1 = 1; if (chapter_1 > this.activeBook.chapter_count) chapter_1 = this.activeBook.chapter_count; if (verse_1 < 1) verse_1 = 1; if (verse_1 > this.activeBook.verse_counts[chapter_1 - 1]) verse_1 = this.activeBook.verse_counts[chapter_1 - 1]; { // main this.uncheckVersesWhenActionModeDestroyed = false; try { boolean ok = loadChapterToVersesView(lsText, S.activeVersion, this.activeBook, chapter_1, current_chapter_1, uncheckAllVerses); if (!ok) return 0; } finally { this.uncheckVersesWhenActionModeDestroyed = true; } // tell activity this.chapter_1 = chapter_1; lsText.scrollToVerse(verse_1); } displaySplitFollowingMaster(verse_1); // set goto button text String reference = this.activeBook.reference(chapter_1); if (Preferences.getBoolean(Prefkey.history_button_understood, false) || history.getSize() == 0) { bGoto.setText(reference); } else { SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(reference).append("\n"); int sb_len = sb.length(); sb.append(getString(R.string.recentverses_button_hint)); sb.setSpan(new RelativeSizeSpan(0.6f), sb_len, sb.length(), 0); bGoto.setText(sb); } return Ari.encode(0, chapter_1, verse_1); } void displaySplitFollowingMaster() { displaySplitFollowingMaster(lsText.getVerseBasedOnScroll()); } private void displaySplitFollowingMaster(int verse_1) { if (activeSplitVersion != null) { // split1 Book splitBook = activeSplitVersion.getBook(this.activeBook.bookId); if (splitBook == null) { tSplitEmpty.setText(getString(R.string.split_version_cant_display_verse, this.activeBook.reference(this.chapter_1), activeSplitVersion.getLongName())); tSplitEmpty.setTextColor(S.applied.fontColor); lsSplit1.setDataEmpty(); } else { this.uncheckVersesWhenActionModeDestroyed = false; try { loadChapterToVersesView(lsSplit1, activeSplitVersion, splitBook, this.chapter_1, this.chapter_1, true); } finally { this.uncheckVersesWhenActionModeDestroyed = true; } lsSplit1.scrollToVerse(verse_1); } } } static boolean loadChapterToVersesView(VersesView versesView, Version version, Book book, int chapter_1, int current_chapter_1, boolean uncheckAllVerses) { SingleChapterVerses verses = version.loadChapterText(book, chapter_1); if (verses == null) { return false; } //# max is set to 30 (one chapter has max of 30 blocks. Already almost impossible) int max = 30; int[] pericope_aris = new int[max]; PericopeBlock[] pericope_blocks = new PericopeBlock[max]; int nblock = version.loadPericope(book.bookId, chapter_1, pericope_aris, pericope_blocks, max); boolean retainSelectedVerses = (!uncheckAllVerses && chapter_1 == current_chapter_1); versesView.setDataWithRetainSelectedVerses(retainSelectedVerses, book, chapter_1, pericope_aris, pericope_blocks, nblock, verses); return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (press(keyCode)) return true; return super.onKeyDown(keyCode, event); } @Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { if (press(keyCode)) return true; return super.onKeyMultiple(keyCode, repeatCount, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { String volumeButtonsForNavigation = Preferences.getString(getString(R.string.pref_volumeButtonNavigation_key), getString(R.string.pref_tombolVolumeBuatPindah_default)); if (! U.equals(volumeButtonsForNavigation, "default")) { // consume here //$NON-NLS-1$ if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) return true; if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) return true; } return super.onKeyUp(keyCode, event); } void bLeft_click() { Book currentBook = this.activeBook; if (chapter_1 == 1) { // we are in the beginning of the book, so go to prev book int tryBookId = currentBook.bookId - 1; while (tryBookId >= 0) { Book newBook = S.activeVersion.getBook(tryBookId); if (newBook != null) { this.activeBook = newBook; int newChapter_1 = newBook.chapter_count; // to the last chapter display(newChapter_1, 1); break; } tryBookId--; } // whileelse: now is already Genesis 1. No need to do anything } else { int newChapter = chapter_1 - 1; display(newChapter, 1); } } void bRight_click() { Book currentBook = this.activeBook; if (chapter_1 >= currentBook.chapter_count) { int maxBookId = S.activeVersion.getMaxBookIdPlusOne(); int tryBookId = currentBook.bookId + 1; while (tryBookId < maxBookId) { Book newBook = S.activeVersion.getBook(tryBookId); if (newBook != null) { this.activeBook = newBook; display(1, 1); break; } tryBookId++; } // whileelse: now is already Revelation (or the last book) at the last chapter. No need to do anything } else { int newChapter = chapter_1 + 1; display(newChapter, 1); } } @Override public boolean onSearchRequested() { menuSearch_click(); return true; } @Override public void onVerseSelected(XrefDialog dialog, int arif_source, int ari_target) { final int ari_source = arif_source >>> 8; dialog.dismiss(); jumpToAri(ari_target); // add both xref source and target, so user can go back to source easily history.add(ari_source); history.add(ari_target); } /** * If verse_1_ranges is null, verses will be ignored. */ public static String createVerseUrl(final String versionShortName, Book book, int chapter_1, String verse_1_ranges) { AppConfig c = AppConfig.get(); if (book.bookId >= c.url_standardBookNames.length) { return null; } String tobeBook = c.url_standardBookNames[book.bookId]; String tobeChapter = String.valueOf(chapter_1); String tobeVerse = verse_1_ranges; String tobeVersion = ""; for (String format: c.url_format.split(" ")) { //$NON-NLS-1$ if ("slash1".equals(format)) tobeChapter = "/" + tobeChapter; //$NON-NLS-1$ //$NON-NLS-2$ if ("slash2".equals(format)) tobeVerse = "/" + tobeVerse; //$NON-NLS-1$ //$NON-NLS-2$ if ("dot1".equals(format)) tobeChapter = "." + tobeChapter; //$NON-NLS-1$ //$NON-NLS-2$ if ("dot2".equals(format)) tobeVerse = "." + tobeVerse; //$NON-NLS-1$ //$NON-NLS-2$ if ("nospace0".equals(format)) tobeBook = tobeBook.replaceAll("\\s+", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if ("version_refly".equals(format)) { if (Arrays.asList("ESV KJV NIV DARBY ASV DRA YLT".split(" ")).contains(versionShortName)) { if (versionShortName.equals("DRA")) { tobeVersion = ";DOUAYRHEIMS"; } else { tobeVersion = ";" + versionShortName; } } } } return c.url_prefix + tobeBook + tobeChapter + (verse_1_ranges == null? "": tobeVerse) + tobeVersion; //$NON-NLS-1$ } VersesView.AttributeListener attributeListener = new VersesView.AttributeListener() { @Override public void onBookmarkAttributeClick(final Book book, final int chapter_1, final int verse_1) { final int ari = Ari.encode(book.bookId, chapter_1, verse_1); String reference = book.reference(chapter_1, verse_1); TypeBookmarkDialog dialog = new TypeBookmarkDialog(IsiActivity.this, reference, ari); dialog.setListener(new TypeBookmarkDialog.Listener() { @Override public void onOk() { lsText.reloadAttributeMap(); if (activeSplitVersion != null) { lsSplit1.reloadAttributeMap(); } } }); dialog.show(); } @Override public void onNoteAttributeClick(final Book book, final int chapter_1, final int verse_1) { TypeNoteDialog dialog = new TypeNoteDialog(IsiActivity.this, book, chapter_1, verse_1, new TypeNoteDialog.Listener() { @Override public void onDone() { lsText.reloadAttributeMap(); if (activeSplitVersion != null) { lsSplit1.reloadAttributeMap(); } } }); dialog.show(); } @Override public void onProgressMarkAttributeClick(final int preset_id) { ProgressMark progressMark = S.getDb().getProgressMarkByPresetId(preset_id); int iconRes = AttributeView.getProgressMarkIconResource(preset_id); String title; if (progressMark.ari == 0 || TextUtils.isEmpty(progressMark.caption)) { title = getString(AttributeView.getDefaultProgressMarkStringResource(preset_id)); } else { title = progressMark.caption; } String verseText = ""; int ari = progressMark.ari; if (ari != 0) { String date = Sqlitil.toLocaleDateMedium(progressMark.modifyTime); String reference = S.activeVersion.reference(ari); verseText = getString(R.string.pm_icon_click_message, reference, date) ; } new AlertDialog.Builder(IsiActivity.this) .setPositiveButton(getString(R.string.ok), null) .setIcon(iconRes) .setTitle(title) .setMessage(verseText) .show(); } }; class VerseInlineLinkSpanFactory implements VerseInlineLinkSpan.Factory { private final Object source; VerseInlineLinkSpanFactory(final Object source) { this.source = source; } @Override public VerseInlineLinkSpan create(final VerseInlineLinkSpan.Type type, final int arif) { return new VerseInlineLinkSpan(type, arif, source) { @Override public void onClick(final Type type, final int arif, final Object source) { if (type == Type.xref) { final XrefDialog dialog = XrefDialog.newInstance(arif); // TODO setSourceVersion here is not restored when dialog is restored if (source == lsText) { // use activeVersion dialog.setSourceVersion(S.activeVersion); } else if (source == lsSplit1) { // use activeSplitVersion dialog.setSourceVersion(activeSplitVersion); } FragmentManager fm = getSupportFragmentManager(); dialog.show(fm, XrefDialog.class.getSimpleName()); } else if (type == Type.footnote) { FootnoteEntry fe = null; if (source == lsText) { // use activeVersion fe = S.activeVersion.getFootnoteEntry(arif); } else if (source == lsSplit1) { // use activeSplitVersion fe = activeSplitVersion.getFootnoteEntry(arif); } if (fe != null) { final SpannableStringBuilder footnoteText = new SpannableStringBuilder(); VerseRenderer.appendSuperscriptNumber(footnoteText, arif & 0xff); footnoteText.append(" "); new AlertDialog.Builder(IsiActivity.this) .setMessage(FormattedTextRenderer.render(fe.content, footnoteText)) .setPositiveButton("OK", null) .show(); } else { new AlertDialog.Builder(IsiActivity.this) .setMessage(String.format(Locale.US, "Error: footnote arif 0x%08x couldn't be loaded", arif)) .setPositiveButton("OK", null) .show(); } } else { new AlertDialog.Builder(IsiActivity.this) .setMessage("Error: Unknown inline link type: " + type) .setPositiveButton("OK", null) .show(); } } }; } } VersesView.SelectedVersesListener lsText_selectedVerses = new VersesView.SelectedVersesListener() { @Override public void onSomeVersesSelected(VersesView v) { if (activeSplitVersion != null) { // synchronize the selection with the split view IntArrayList selectedVerses = v.getSelectedVerses_1(); lsSplit1.checkVerses(selectedVerses, false); } if (actionMode == null) { actionMode = startSupportActionMode(actionMode_callback); } if (actionMode != null) { actionMode.invalidate(); } } @Override public void onNoVersesSelected(VersesView v) { if (activeSplitVersion != null) { // synchronize the selection with the split view lsSplit1.uncheckAllVerses(false); } if (actionMode != null) { actionMode.finish(); actionMode = null; } } @Override public void onVerseSingleClick(VersesView v, int verse_1) {} }; VersesView.SelectedVersesListener lsSplit1_selectedVerses = new VersesView.SelectedVersesListener() { @Override public void onSomeVersesSelected(VersesView v) { // synchronize the selection with the main view IntArrayList selectedVerses = v.getSelectedVerses_1(); lsText.checkVerses(selectedVerses, true); } @Override public void onNoVersesSelected(VersesView v) { lsText.uncheckAllVerses(true); } @Override public void onVerseSingleClick(VersesView v, int verse_1) {} }; VersesView.OnVerseScrollStateChangeListener lsText_verseScrollState = new VersesView.OnVerseScrollStateChangeListener() { @Override public void onVerseScrollStateChange(final VersesView versesView, final int scrollState) { if (!readingPlanFloatMenu.isActive) { return; } if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { readingPlanFloatMenu.isAnimating = false; readingPlanFloatMenu.clearAnimation(); readingPlanFloatMenu.setVisibility(View.VISIBLE); } else if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) { readingPlanFloatMenu.setVisibility(View.VISIBLE); } else if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && readingPlanFloatMenu.getVisibility() != View.GONE) { readingPlanFloatMenu.fadeoutAnimation(3000); } } }; VersesView.OnVerseScrollListener lsText_verseScroll = new VersesView.OnVerseScrollListener() { @Override public void onVerseScroll(VersesView v, boolean isPericope, int verse_1, float prop) { if (!isPericope && activeSplitVersion != null) { lsSplit1.scrollToVerse(verse_1, prop); } } @Override public void onScrollToTop(VersesView v) { if (activeSplitVersion != null) { lsSplit1.scrollToTop(); } } }; VersesView.OnVerseScrollListener lsSplit1_verseScroll = new VersesView.OnVerseScrollListener() { @Override public void onVerseScroll(VersesView v, boolean isPericope, int verse_1, float prop) { if (!isPericope) { lsText.scrollToVerse(verse_1, prop); } } @Override public void onScrollToTop(VersesView v) { lsText.scrollToTop(); } }; ActionMode.Callback actionMode_callback = new ActionMode.Callback() { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(R.menu.context_isi, menu); /* The following "esvsbasal" thing is a personal thing by yuku that doesn't matter to anyone else. * Please ignore it and leave it intact. */ if (hasEsvsbAsal == null) { try { getPackageManager().getApplicationInfo("yuku.esvsbasal", 0); //$NON-NLS-1$ hasEsvsbAsal = true; } catch (NameNotFoundException e) { hasEsvsbAsal = false; } } if (hasEsvsbAsal) { MenuItem esvsb = menu.findItem(R.id.menuEsvsb); if (esvsb != null) esvsb.setVisible(true); } List<ProgressMark> progressMarks = S.getDb().listAllProgressMarks(); MenuItem item1 = menu.findItem(R.id.menuProgress1); setProgressMarkMenuItemTitle(progressMarks, item1, 0); MenuItem item2 = menu.findItem(R.id.menuProgress2); setProgressMarkMenuItemTitle(progressMarks, item2, 1); MenuItem item3 = menu.findItem(R.id.menuProgress3); setProgressMarkMenuItemTitle(progressMarks, item3, 2); MenuItem item4 = menu.findItem(R.id.menuProgress4); setProgressMarkMenuItemTitle(progressMarks, item4, 3); MenuItem item5 = menu.findItem(R.id.menuProgress5); setProgressMarkMenuItemTitle(progressMarks, item5, 4); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { MenuItem menuAddBookmark = menu.findItem(R.id.menuAddBookmark); MenuItem menuAddNote = menu.findItem(R.id.menuAddNote); MenuItem menuProgressMark = menu.findItem(R.id.menuProgressMark); IntArrayList selected = lsText.getSelectedVerses_1(); boolean single = selected.size() == 1; boolean changed1 = menuAddBookmark.isVisible() != single; boolean changed2 = menuAddNote.isVisible() != single; boolean changed3 = menuProgressMark.isVisible() != single; boolean changed = changed1 || changed2 || changed3; if (changed) { menuAddBookmark.setVisible(single); menuAddNote.setVisible(single); menuProgressMark.setVisible(single); } return changed; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { IntArrayList selected = lsText.getSelectedVerses_1(); if (selected.size() == 0) return true; CharSequence reference = referenceFromSelectedVerses(selected, activeBook); IntArrayList selectedSplit = null; CharSequence referenceSplit = null; if (activeSplitVersion != null) { selectedSplit = lsSplit1.getSelectedVerses_1(); referenceSplit = referenceFromSelectedVerses(selectedSplit, activeSplitVersion.getBook(activeBook.bookId)); } // the main verse (0 if not exist), which is only when only one verse is selected int mainVerse_1 = 0; if (selected.size() == 1) { mainVerse_1 = selected.get(0); } int itemId = item.getItemId(); switch (itemId) { case R.id.menuCopy: { // copy, can be multiple CharSequence textToCopy = prepareTextForCopyShare(selected, reference, false); if (activeSplitVersion != null) { textToCopy = textToCopy + "\n\n" + prepareTextForCopyShare(selectedSplit, referenceSplit, true); } U.copyToClipboard(textToCopy); lsText.uncheckAllVerses(true); Toast.makeText(App.context, getString(R.string.alamat_sudah_disalin, reference), Toast.LENGTH_SHORT).show(); mode.finish(); } return true; case R.id.menuShare: { CharSequence textToShare = prepareTextForCopyShare(selected, reference, false); if (activeSplitVersion != null) { textToShare = textToShare + "\n\n" + prepareTextForCopyShare(selectedSplit, referenceSplit, true); } String verseUrl; if (selected.size() == 1) { verseUrl = createVerseUrl(S.activeVersion.getShortName(), IsiActivity.this.activeBook, IsiActivity.this.chapter_1, String.valueOf(selected.get(0))); } else { StringBuilder sb = new StringBuilder(); Book.writeVerseRange(selected, sb); verseUrl = createVerseUrl(S.activeVersion.getShortName(), IsiActivity.this.activeBook, IsiActivity.this.chapter_1, sb.toString()); // use verse range } Intent intent = ShareCompat.IntentBuilder.from(IsiActivity.this) .setType("text/plain") //$NON-NLS-1$ .setSubject(reference.toString()) .setText(textToShare.toString()) .getIntent(); intent.putExtra(EXTRA_verseUrl, verseUrl); startActivityForResult(ShareActivity.createIntent(intent, getString(R.string.bagikan_alamat, reference)), REQCODE_share); lsText.uncheckAllVerses(true); mode.finish(); } return true; case R.id.menuVersions: { openVersionsDialog(); } return true; case R.id.menuAddBookmark: { if (mainVerse_1 == 0) { // no main verse, scroll to show the relevant one! mainVerse_1 = selected.get(0); lsText.scrollToShowVerse(mainVerse_1); } final int ari = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, mainVerse_1); TypeBookmarkDialog dialog = new TypeBookmarkDialog(IsiActivity.this, IsiActivity.this.activeBook.reference(IsiActivity.this.chapter_1, mainVerse_1), ari); dialog.setListener(new TypeBookmarkDialog.Listener() { @Override public void onOk() { reloadVerse(); } }); dialog.show(); mode.finish(); } return true; case R.id.menuAddNote: { if (mainVerse_1 == 0) { // no main verse, scroll to show the relevant one! mainVerse_1 = selected.get(0); lsText.scrollToShowVerse(mainVerse_1); } TypeNoteDialog dialog = new TypeNoteDialog(IsiActivity.this, IsiActivity.this.activeBook, IsiActivity.this.chapter_1, mainVerse_1, new TypeNoteDialog.Listener() { @Override public void onDone() { reloadVerse(); } }); dialog.show(); mode.finish(); } return true; case R.id.menuAddHighlight: { final int ariKp = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, 0); int colorRgb = S.getDb().getHighlightColorRgb(ariKp, selected); new TypeHighlightDialog(IsiActivity.this, ariKp, selected, new TypeHighlightDialog.Listener() { @Override public void onOk(int colorRgb) { reloadVerse(); } }, colorRgb, reference).show(); mode.finish(); } return true; case R.id.menuEsvsb: { final int ari = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, mainVerse_1); try { Intent intent = new Intent("yuku.esvsbasal.action.GOTO"); //$NON-NLS-1$ intent.putExtra("ari", ari); //$NON-NLS-1$ startActivity(intent); } catch (Exception e) { Log.e(TAG, "ESVSB starting", e); //$NON-NLS-1$ } } return true; case R.id.menuProgress1: { updateProgressMark(mainVerse_1, 0); } return true; case R.id.menuProgress2: { updateProgressMark(mainVerse_1, 1); } return true; case R.id.menuProgress3: { updateProgressMark(mainVerse_1, 2); } return true; case R.id.menuProgress4: { updateProgressMark(mainVerse_1, 3); } return true; case R.id.menuProgress5: { updateProgressMark(mainVerse_1, 4); } return true; } return false; } @Override public void onDestroyActionMode(ActionMode mode) { actionMode = null; // FIXME even with this guard, verses are still unchecked when switching version while both Fullscreen and Split is active. // This guard only fixes unchecking of verses when in fullscreen mode. if (uncheckVersesWhenActionModeDestroyed) { lsText.uncheckAllVerses(true); } } private void setProgressMarkMenuItemTitle(final List<ProgressMark> progressMarks, final MenuItem item, int position) { String title = (progressMarks.get(position).ari == 0 || TextUtils.isEmpty(progressMarks.get(position).caption)) ? getString(AttributeView.getDefaultProgressMarkStringResource(position)): progressMarks.get(position).caption; item.setTitle(getString(R.string.pm_menu_save_progress, title)); } }; private void reloadVerse() { lsText.uncheckAllVerses(true); lsText.reloadAttributeMap(); if (activeSplitVersion != null) { lsSplit1.reloadAttributeMap(); } } private void updateProgressMark(final int mainVerse_1, final int position) { final int ari = Ari.encode(this.activeBook.bookId, this.chapter_1, mainVerse_1); List<ProgressMark> progressMarks = S.getDb().listAllProgressMarks(); final ProgressMark progressMark = progressMarks.get(position); if (progressMark.ari == ari) { int icon = AttributeView.getProgressMarkIconResource(position); String title = progressMark.caption; if (TextUtils.isEmpty(title)) { title = getString(AttributeView.getDefaultProgressMarkStringResource(position)); } new AlertDialog.Builder(IsiActivity.this) .setIcon(icon) .setTitle(title) .setMessage(getString(R.string.pm_delete_progress_confirm, title)) .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { progressMark.ari = 0; progressMark.caption = null; S.getDb().updateProgressMark(progressMark); reloadVerse(); } }) .setNegativeButton(getString(R.string.cancel), null) .show(); } else { if (progressMark.caption == null) { ProgressMarkDialog.showRenameProgressDialog(this, progressMark, new ProgressMarkDialog.OnRenameListener() { @Override public void okClick() { saveProgress(progressMark, ari, position); } }); } else { saveProgress(progressMark, ari, position); } } } public void saveProgress(final ProgressMark progressMark, final int ari, final int position) { progressMark.ari = ari; progressMark.modifyTime = new Date(); S.getDb().updateProgressMark(progressMark); AttributeView.startAnimationForProgressMark(position); reloadVerse(); } SplitHandleButton.SplitHandleButtonListener splitHandleButton_listener = new SplitHandleButton.SplitHandleButtonListener() { int aboveH; int handleH; int rootH; @Override public void onHandleDragStart() { aboveH = lsText.getHeight(); handleH = splitHandle.getHeight(); rootH = splitRoot.getHeight(); } @Override public void onHandleDragMove(float dySinceLast, float dySinceStart) { int newH = (int) (aboveH + dySinceStart); int maxH = rootH - handleH; ViewGroup.LayoutParams lp = lsText.getLayoutParams(); lp.height = newH < 0? 0: newH > maxH? maxH: newH; lsText.setLayoutParams(lp); } @Override public void onHandleDragStop() { } }; }
false
true
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQCODE_goto) { if (resultCode == RESULT_OK) { GotoActivity.Result result = GotoActivity.obtainResult(data); if (result != null) { // change book Book book = S.activeVersion.getBook(result.bookId); if (book != null) { this.activeBook = book; } else { // no book, just chapter and verse. result.bookId = this.activeBook.bookId; } int ari_cv = display(result.chapter_1, result.verse_1); history.add(Ari.encode(result.bookId, ari_cv)); } } } else if (requestCode == REQCODE_bookmark) { lsText.reloadAttributeMap(); if (activeSplitVersion != null) { lsSplit1.reloadAttributeMap(); } } else if (requestCode == REQCODE_search) { if (resultCode == RESULT_OK) { Search2Activity.Result result = Search2Activity.obtainResult(data); if (result != null) { if (result.selectedAri != -1) { jumpToAri(result.selectedAri); history.add(result.selectedAri); } search2_query = result.query; search2_results = result.searchResults; search2_selectedPosition = result.selectedPosition; } } } else if (requestCode == REQCODE_devotion) { if (resultCode == RESULT_OK) { DevotionActivity.Result result = DevotionActivity.obtainResult(data); if (result != null && result.ari != 0) { jumpToAri(result.ari); history.add(result.ari); } } } else if (requestCode == REQCODE_songs) { if (resultCode == SongViewActivity.RESULT_gotoScripture && data != null) { String ref = data.getStringExtra(SongViewActivity.EXTRA_ref); if (ref != null) { // TODO int ari = jumpTo(ref); if (ari != 0) { history.add(ari); } } } } else if (requestCode == REQCODE_settings) { // MUST reload preferences S.calculateAppliedValuesBasedOnPreferences(); applyPreferences(true); if (resultCode == SettingsActivity.RESULT_openTextAppearance) { setShowTextAppearancePanel(true); } } else if (requestCode == REQCODE_share) { if (resultCode == RESULT_OK) { ShareActivity.Result result = ShareActivity.obtainResult(data); if (result != null && result.chosenIntent != null) { Intent chosenIntent = result.chosenIntent; if (U.equals(chosenIntent.getComponent().getPackageName(), "com.facebook.katana")) { //$NON-NLS-1$ String verseUrl = chosenIntent.getStringExtra(EXTRA_verseUrl); if (verseUrl != null) { chosenIntent.putExtra(Intent.EXTRA_TEXT, verseUrl); // change text to url } } startActivity(chosenIntent); } } } else if (requestCode == REQCODE_textAppearanceGetFonts) { if (textAppearancePanel != null) textAppearancePanel.onActivityResult(requestCode, resultCode, data); } else if (requestCode == REQCODE_textAppearanceCustomColors) { if (textAppearancePanel != null) textAppearancePanel.onActivityResult(requestCode, resultCode, data); // MUST reload preferences S.calculateAppliedValuesBasedOnPreferences(); applyPreferences(true); } else if (requestCode == REQCODE_readingPlan) { if (data == null && !readingPlanFloatMenu.isActive) { return; } else if (data == null) { if (readingPlanFloatMenu.getReadingPlanId() != Preferences.getLong(Prefkey.active_reading_plan, 0)) { readingPlanFloatMenu.setVisibility(View.GONE); return; } readingPlanFloatMenu.setVisibility(View.VISIBLE); readingPlanFloatMenu.updateProgress(); readingPlanFloatMenu.updateLayout(); return; } readingPlanFloatMenu.setVisibility(View.VISIBLE); readingPlanFloatMenu.isActive = true; final int ari = data.getIntExtra("ari", 0); final long id = data.getLongExtra(ReadingPlanActivity.READING_PLAN_ID, 0L); final int dayNumber = data.getIntExtra(ReadingPlanActivity.READING_PLAN_DAY_NUMBER, 0); final int[] ariRanges = data.getIntArrayExtra(ReadingPlanActivity.READING_PLAN_ARI_RANGES); if (ari != 0 && ariRanges != null) { for (int i = 0; i < ariRanges.length; i++) { if (ariRanges[i] == ari) { jumpToAri(ari); history.add(ari); int[] ariRangesInThisSequence = new int[2]; ariRangesInThisSequence[0] = ariRanges[i]; ariRangesInThisSequence[1] = ariRanges[i + 1]; lsText.setAriRangesReadingPlan(ariRangesInThisSequence); lsText.updateAdapter(); readingPlanFloatMenu.load(id, dayNumber, ariRanges, i); readingPlanFloatMenu.setLeftNavigationClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { readingPlanFloatMenu.clearAnimation(); jumpToAri(ari_0); history.add(ari_0); lsText.setAriRangesReadingPlan(new int[] {ari_0, ari_1}); lsText.updateAdapter(); readingPlanFloatMenu.fadeoutAnimation(5000); } }); readingPlanFloatMenu.setRightNavigationClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { readingPlanFloatMenu.clearAnimation(); jumpToAri(ari_0); history.add(ari_0); lsText.setAriRangesReadingPlan(new int[] {ari_0, ari_1}); lsText.updateAdapter(); readingPlanFloatMenu.fadeoutAnimation(5000); } }); readingPlanFloatMenu.setDescriptionListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { startActivityForResult(ReadingPlanActivity.createIntent(dayNumber), REQCODE_readingPlan); } }); readingPlanFloatMenu.setReadMarkClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { readingPlanFloatMenu.clearAnimation(); readingPlanFloatMenu.fadeoutAnimation(5000); } }); readingPlanFloatMenu.setCloseReadingModeClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { readingPlanFloatMenu.clearAnimation(); readingPlanFloatMenu.setVisibility(View.GONE); readingPlanFloatMenu.isActive = false; lsText.setAriRangesReadingPlan(null); lsText.updateAdapter(); } }); readingPlanFloatMenu.fadeoutAnimation(5000); break; } } } } }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQCODE_goto) { if (resultCode == RESULT_OK) { GotoActivity.Result result = GotoActivity.obtainResult(data); if (result != null) { // change book Book book = S.activeVersion.getBook(result.bookId); if (book != null) { this.activeBook = book; } else { // no book, just chapter and verse. result.bookId = this.activeBook.bookId; } int ari_cv = display(result.chapter_1, result.verse_1); history.add(Ari.encode(result.bookId, ari_cv)); } } } else if (requestCode == REQCODE_bookmark) { lsText.reloadAttributeMap(); if (activeSplitVersion != null) { lsSplit1.reloadAttributeMap(); } } else if (requestCode == REQCODE_search) { if (resultCode == RESULT_OK) { Search2Activity.Result result = Search2Activity.obtainResult(data); if (result != null) { if (result.selectedAri != -1) { jumpToAri(result.selectedAri); history.add(result.selectedAri); } search2_query = result.query; search2_results = result.searchResults; search2_selectedPosition = result.selectedPosition; } } } else if (requestCode == REQCODE_devotion) { if (resultCode == RESULT_OK) { DevotionActivity.Result result = DevotionActivity.obtainResult(data); if (result != null && result.ari != 0) { jumpToAri(result.ari); history.add(result.ari); } } } else if (requestCode == REQCODE_songs) { if (resultCode == SongViewActivity.RESULT_gotoScripture && data != null) { String ref = data.getStringExtra(SongViewActivity.EXTRA_ref); if (ref != null) { // TODO int ari = jumpTo(ref); if (ari != 0) { history.add(ari); } } } } else if (requestCode == REQCODE_settings) { // MUST reload preferences S.calculateAppliedValuesBasedOnPreferences(); applyPreferences(true); if (resultCode == SettingsActivity.RESULT_openTextAppearance) { setShowTextAppearancePanel(true); } } else if (requestCode == REQCODE_share) { if (resultCode == RESULT_OK) { ShareActivity.Result result = ShareActivity.obtainResult(data); if (result != null && result.chosenIntent != null) { Intent chosenIntent = result.chosenIntent; if (U.equals(chosenIntent.getComponent().getPackageName(), "com.facebook.katana")) { //$NON-NLS-1$ String verseUrl = chosenIntent.getStringExtra(EXTRA_verseUrl); if (verseUrl != null) { chosenIntent.putExtra(Intent.EXTRA_TEXT, verseUrl); // change text to url } } startActivity(chosenIntent); } } } else if (requestCode == REQCODE_textAppearanceGetFonts) { if (textAppearancePanel != null) textAppearancePanel.onActivityResult(requestCode, resultCode, data); } else if (requestCode == REQCODE_textAppearanceCustomColors) { if (textAppearancePanel != null) textAppearancePanel.onActivityResult(requestCode, resultCode, data); // MUST reload preferences S.calculateAppliedValuesBasedOnPreferences(); applyPreferences(true); } else if (requestCode == REQCODE_readingPlan) { if (data == null && !readingPlanFloatMenu.isActive) { return; } else if (data == null) { if (readingPlanFloatMenu.getReadingPlanId() != Preferences.getLong(Prefkey.active_reading_plan, 0)) { readingPlanFloatMenu.setVisibility(View.GONE); readingPlanFloatMenu.isActive = false; return; } readingPlanFloatMenu.setVisibility(View.VISIBLE); readingPlanFloatMenu.fadeoutAnimation(5000); readingPlanFloatMenu.updateProgress(); readingPlanFloatMenu.updateLayout(); return; } readingPlanFloatMenu.setVisibility(View.VISIBLE); readingPlanFloatMenu.isActive = true; final int ari = data.getIntExtra("ari", 0); final long id = data.getLongExtra(ReadingPlanActivity.READING_PLAN_ID, 0L); final int dayNumber = data.getIntExtra(ReadingPlanActivity.READING_PLAN_DAY_NUMBER, 0); final int[] ariRanges = data.getIntArrayExtra(ReadingPlanActivity.READING_PLAN_ARI_RANGES); if (ari != 0 && ariRanges != null) { for (int i = 0; i < ariRanges.length; i++) { if (ariRanges[i] == ari) { jumpToAri(ari); history.add(ari); int[] ariRangesInThisSequence = new int[2]; ariRangesInThisSequence[0] = ariRanges[i]; ariRangesInThisSequence[1] = ariRanges[i + 1]; lsText.setAriRangesReadingPlan(ariRangesInThisSequence); lsText.updateAdapter(); readingPlanFloatMenu.load(id, dayNumber, ariRanges, i); readingPlanFloatMenu.setLeftNavigationClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { readingPlanFloatMenu.clearAnimation(); jumpToAri(ari_0); history.add(ari_0); lsText.setAriRangesReadingPlan(new int[] {ari_0, ari_1}); lsText.updateAdapter(); readingPlanFloatMenu.fadeoutAnimation(5000); } }); readingPlanFloatMenu.setRightNavigationClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { readingPlanFloatMenu.clearAnimation(); jumpToAri(ari_0); history.add(ari_0); lsText.setAriRangesReadingPlan(new int[] {ari_0, ari_1}); lsText.updateAdapter(); readingPlanFloatMenu.fadeoutAnimation(5000); } }); readingPlanFloatMenu.setDescriptionListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { startActivityForResult(ReadingPlanActivity.createIntent(dayNumber), REQCODE_readingPlan); } }); readingPlanFloatMenu.setReadMarkClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { readingPlanFloatMenu.clearAnimation(); readingPlanFloatMenu.fadeoutAnimation(5000); } }); readingPlanFloatMenu.setCloseReadingModeClickListener(new ReadingPlanFloatMenu.ReadingPlanFloatMenuClickListener() { @Override public void onClick(final int ari_0, final int ari_1) { readingPlanFloatMenu.clearAnimation(); readingPlanFloatMenu.setVisibility(View.GONE); readingPlanFloatMenu.isActive = false; lsText.setAriRangesReadingPlan(null); lsText.updateAdapter(); } }); readingPlanFloatMenu.fadeoutAnimation(5000); break; } } } } }
diff --git a/Operator/DecOp.java b/Operator/DecOp.java index bef1166..88d5b3c 100644 --- a/Operator/DecOp.java +++ b/Operator/DecOp.java @@ -1,48 +1,52 @@ //--------------------------------------------------------------------- // //--------------------------------------------------------------------- class DecOp extends UnaryOp { //--------------------------------------------------------------------- // Constructors //--------------------------------------------------------------------- public DecOp(String strName) { super(strName); } //--------------------------------------------------------------------- // Methods //--------------------------------------------------------------------- public STO checkOperand(STO operand) { STO resultSTO; // Check #2 - increment, decrement - operand numeric if((!operand.getType().isNumeric()) && (!operand.getType().isPointer())) { return (new ErrorSTO(Formatter.toString(ErrorMsg.error2_Type, operand.getType().getName(), this.getName()))); } // Check #2 - increment, decrement - operand not modifiable L-value if(!operand.isModLValue()) { return (new ErrorSTO(Formatter.toString(ErrorMsg.error2_Lval, this.getName()))); } // Passed checks, determine result type if(operand.getType().isInt()) { resultSTO = new ExprSTO("IncOp.checkOperand() Result", new IntType()); } else if(operand.getType().isFloat()) { resultSTO = new ExprSTO("IncOp.checkOperand() Result", new FloatType()); } + else + { + return (new ErrorSTO("This will never happen, making compiler happy")); + } return resultSTO; } }
true
true
public STO checkOperand(STO operand) { STO resultSTO; // Check #2 - increment, decrement - operand numeric if((!operand.getType().isNumeric()) && (!operand.getType().isPointer())) { return (new ErrorSTO(Formatter.toString(ErrorMsg.error2_Type, operand.getType().getName(), this.getName()))); } // Check #2 - increment, decrement - operand not modifiable L-value if(!operand.isModLValue()) { return (new ErrorSTO(Formatter.toString(ErrorMsg.error2_Lval, this.getName()))); } // Passed checks, determine result type if(operand.getType().isInt()) { resultSTO = new ExprSTO("IncOp.checkOperand() Result", new IntType()); } else if(operand.getType().isFloat()) { resultSTO = new ExprSTO("IncOp.checkOperand() Result", new FloatType()); } return resultSTO; }
public STO checkOperand(STO operand) { STO resultSTO; // Check #2 - increment, decrement - operand numeric if((!operand.getType().isNumeric()) && (!operand.getType().isPointer())) { return (new ErrorSTO(Formatter.toString(ErrorMsg.error2_Type, operand.getType().getName(), this.getName()))); } // Check #2 - increment, decrement - operand not modifiable L-value if(!operand.isModLValue()) { return (new ErrorSTO(Formatter.toString(ErrorMsg.error2_Lval, this.getName()))); } // Passed checks, determine result type if(operand.getType().isInt()) { resultSTO = new ExprSTO("IncOp.checkOperand() Result", new IntType()); } else if(operand.getType().isFloat()) { resultSTO = new ExprSTO("IncOp.checkOperand() Result", new FloatType()); } else { return (new ErrorSTO("This will never happen, making compiler happy")); } return resultSTO; }
diff --git a/src/main/java/com/mulesoft/util/ObjectNamesHTMLTransformer.java b/src/main/java/com/mulesoft/util/ObjectNamesHTMLTransformer.java index 794c5af..40baa26 100644 --- a/src/main/java/com/mulesoft/util/ObjectNamesHTMLTransformer.java +++ b/src/main/java/com/mulesoft/util/ObjectNamesHTMLTransformer.java @@ -1,59 +1,61 @@ package com.mulesoft.util; import java.util.ArrayList; import java.util.StringTokenizer; import org.mule.api.MuleMessage; import org.mule.api.transformer.TransformerException; import org.mule.transformer.AbstractMessageTransformer; public class ObjectNamesHTMLTransformer extends AbstractMessageTransformer{ @Override public Object transformMessage(MuleMessage msg, String encoding) throws TransformerException{ String lPrices = (String)msg.getPayload().toString(); lPrices = lPrices.substring(1,lPrices.length()-1); String sHTML = "<html>" + "<head>" + + "<title>iON - Salesforce Initializer</title>"+ "<link rel=stylesheet href=http://twitter.github.com/bootstrap/1.4.0/bootstrap.min.css >" + "<script language=javascript> " + "function combofunction(sel){var value = sel.options[sel.selectedIndex].value;}" + "</script>" + "</head>" + "<style type=text/css>" + "body { padding-top: 60px;}" + "</style>" + "<body>" + - "<div class=container>" + - "<div class=row>" + - "<div class=span12>" + - "<form action=http://localhost:65082/results method=post>" + - "<h1>Results for Account</h1>"; + "<div class=\"topbar\"><div class=\"fill\"><div class=\"container\"><a class=\"brand\" href=\"#\">iON - Salesforce Initializer</a></div></div></div>"+ + "<div class=\"container\">" + + "<div class=\"row\">" + + "<div class=\"span16\">" + + "<form action=\"http://localhost:65082/results\" method=\"post\">" + + "<h1>Available Objects</h1>"; StringTokenizer stringtokenizer = new StringTokenizer(lPrices, ","); - sHTML += "<select size=10 name=objectsCombo>"; + sHTML += "<select size=\"20\" name=\"objectsCombo\" style=\"height:75%;width:100%;font-size:160%; \">"; while (stringtokenizer.hasMoreElements()) { // System.out.println(stringtokenizer.nextToken()); sHTML+="<option>"+stringtokenizer.nextToken()+"</option>"; } sHTML+="</select><br/>" + - "<input type=submit value=Initialize! onclick=combofunction(objectsCombo.value) />" + - "<input type=hidden name=userOrig value=" + msg.getSessionProperty("userOrig") + " />" + - "<input type=hidden name=passOrig value=" + msg.getSessionProperty("passOrig") + " />" + - "<input type=hidden name=tokenOrig value=" + msg.getSessionProperty("tokenOrig") + " />" + - "<input type=hidden name=userDest value=" + msg.getSessionProperty("userDest") + " />" + - "<input type=hidden name=passDest value=" + msg.getSessionProperty("passDest") + " />" + - "<input type=hidden name=tokenDest value=" + msg.getSessionProperty("tokenDest") + " />" + + "<div style=\"padding:10px 0;\"><input type=\"submit\" class=\" btn primary\" value=\"Initialize!\" onclick=\"combofunction(objectsCombo.value)\" /></div>" + + "<input type=\"hidden\" name=\"userOrig\" value=\"" + msg.getSessionProperty("userOrig") + "\" />" + + "<input type=\"hidden\" name=\"passOrig\" value=\"" + msg.getSessionProperty("passOrig") + "\" />" + + "<input type=\"hidden\" name=\"tokenOrig\" value=\"" + msg.getSessionProperty("tokenOrig") + "\" />" + + "<input type=\"hidden\" name=\"userDest\" value=\"" + msg.getSessionProperty("userDest") + "\" />" + + "<input type=\"hidden\" name=\"passDest\" value=\"" + msg.getSessionProperty("passDest") + "\" />" + + "<input type=\"hidden\" name=\"tokenDest\" value=\"" + msg.getSessionProperty("tokenDest") + "\" />" + "</form>" + "</div>" + "</div>" + "<footer>" + "<p>&copy; Mulesoft 2011</p>" + "</footer>" + "</div>" + "</body>" + "</html>"; return sHTML; } }
false
true
public Object transformMessage(MuleMessage msg, String encoding) throws TransformerException{ String lPrices = (String)msg.getPayload().toString(); lPrices = lPrices.substring(1,lPrices.length()-1); String sHTML = "<html>" + "<head>" + "<link rel=stylesheet href=http://twitter.github.com/bootstrap/1.4.0/bootstrap.min.css >" + "<script language=javascript> " + "function combofunction(sel){var value = sel.options[sel.selectedIndex].value;}" + "</script>" + "</head>" + "<style type=text/css>" + "body { padding-top: 60px;}" + "</style>" + "<body>" + "<div class=container>" + "<div class=row>" + "<div class=span12>" + "<form action=http://localhost:65082/results method=post>" + "<h1>Results for Account</h1>"; StringTokenizer stringtokenizer = new StringTokenizer(lPrices, ","); sHTML += "<select size=10 name=objectsCombo>"; while (stringtokenizer.hasMoreElements()) { // System.out.println(stringtokenizer.nextToken()); sHTML+="<option>"+stringtokenizer.nextToken()+"</option>"; } sHTML+="</select><br/>" + "<input type=submit value=Initialize! onclick=combofunction(objectsCombo.value) />" + "<input type=hidden name=userOrig value=" + msg.getSessionProperty("userOrig") + " />" + "<input type=hidden name=passOrig value=" + msg.getSessionProperty("passOrig") + " />" + "<input type=hidden name=tokenOrig value=" + msg.getSessionProperty("tokenOrig") + " />" + "<input type=hidden name=userDest value=" + msg.getSessionProperty("userDest") + " />" + "<input type=hidden name=passDest value=" + msg.getSessionProperty("passDest") + " />" + "<input type=hidden name=tokenDest value=" + msg.getSessionProperty("tokenDest") + " />" + "</form>" + "</div>" + "</div>" + "<footer>" + "<p>&copy; Mulesoft 2011</p>" + "</footer>" + "</div>" + "</body>" + "</html>"; return sHTML; }
public Object transformMessage(MuleMessage msg, String encoding) throws TransformerException{ String lPrices = (String)msg.getPayload().toString(); lPrices = lPrices.substring(1,lPrices.length()-1); String sHTML = "<html>" + "<head>" + "<title>iON - Salesforce Initializer</title>"+ "<link rel=stylesheet href=http://twitter.github.com/bootstrap/1.4.0/bootstrap.min.css >" + "<script language=javascript> " + "function combofunction(sel){var value = sel.options[sel.selectedIndex].value;}" + "</script>" + "</head>" + "<style type=text/css>" + "body { padding-top: 60px;}" + "</style>" + "<body>" + "<div class=\"topbar\"><div class=\"fill\"><div class=\"container\"><a class=\"brand\" href=\"#\">iON - Salesforce Initializer</a></div></div></div>"+ "<div class=\"container\">" + "<div class=\"row\">" + "<div class=\"span16\">" + "<form action=\"http://localhost:65082/results\" method=\"post\">" + "<h1>Available Objects</h1>"; StringTokenizer stringtokenizer = new StringTokenizer(lPrices, ","); sHTML += "<select size=\"20\" name=\"objectsCombo\" style=\"height:75%;width:100%;font-size:160%; \">"; while (stringtokenizer.hasMoreElements()) { // System.out.println(stringtokenizer.nextToken()); sHTML+="<option>"+stringtokenizer.nextToken()+"</option>"; } sHTML+="</select><br/>" + "<div style=\"padding:10px 0;\"><input type=\"submit\" class=\" btn primary\" value=\"Initialize!\" onclick=\"combofunction(objectsCombo.value)\" /></div>" + "<input type=\"hidden\" name=\"userOrig\" value=\"" + msg.getSessionProperty("userOrig") + "\" />" + "<input type=\"hidden\" name=\"passOrig\" value=\"" + msg.getSessionProperty("passOrig") + "\" />" + "<input type=\"hidden\" name=\"tokenOrig\" value=\"" + msg.getSessionProperty("tokenOrig") + "\" />" + "<input type=\"hidden\" name=\"userDest\" value=\"" + msg.getSessionProperty("userDest") + "\" />" + "<input type=\"hidden\" name=\"passDest\" value=\"" + msg.getSessionProperty("passDest") + "\" />" + "<input type=\"hidden\" name=\"tokenDest\" value=\"" + msg.getSessionProperty("tokenDest") + "\" />" + "</form>" + "</div>" + "</div>" + "<footer>" + "<p>&copy; Mulesoft 2011</p>" + "</footer>" + "</div>" + "</body>" + "</html>"; return sHTML; }
diff --git a/core/src/main/java/hudson/scm/SubversionChangeLogBuilder.java b/core/src/main/java/hudson/scm/SubversionChangeLogBuilder.java index 5ecee3f8c..39eef34a8 100644 --- a/core/src/main/java/hudson/scm/SubversionChangeLogBuilder.java +++ b/core/src/main/java/hudson/scm/SubversionChangeLogBuilder.java @@ -1,196 +1,200 @@ package hudson.scm; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.scm.SubversionSCM.ModuleLocation; import hudson.FilePath; import hudson.remoting.VirtualChannel; import hudson.FilePath.FileCallable; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.ISVNLogEntryHandler; import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider; import org.tmatesoft.svn.core.wc.SVNClientManager; import org.tmatesoft.svn.core.wc.SVNLogClient; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNWCClient; import org.tmatesoft.svn.core.wc.SVNInfo; import org.tmatesoft.svn.core.wc.xml.SVNXMLLogHandler; import org.xml.sax.helpers.LocatorImpl; import javax.xml.transform.Result; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import java.io.IOException; import java.io.PrintStream; import java.io.File; import java.util.Map; import java.util.Collection; /** * Builds <tt>changelog.xml</tt> for {@link SubversionSCM}. * * @author Kohsuke Kawaguchi */ public final class SubversionChangeLogBuilder { /** * Revisions of the workspace before the update/checkout. */ private final Map<String,Long> previousRevisions; /** * Revisions of the workspace after the update/checkout. */ private final Map<String,Long> thisRevisions; private final BuildListener listener; private final SubversionSCM scm; private final AbstractBuild<?,?> build; public SubversionChangeLogBuilder(AbstractBuild<?,?> build, BuildListener listener, SubversionSCM scm) throws IOException { previousRevisions = SubversionSCM.parseRevisionFile(build.getPreviousBuild()); thisRevisions = SubversionSCM.parseRevisionFile(build); this.listener = listener; this.scm = scm; this.build = build; } public boolean run(Collection<String> externals, Result changeLog) throws IOException, InterruptedException { boolean changelogFileCreated = false; final SVNClientManager manager = SubversionSCM.createSvnClientManager(createAuthenticationProvider()); try { SVNLogClient svnlc = manager.getLogClient(); TransformerHandler th = createTransformerHandler(); th.setResult(changeLog); SVNXMLLogHandler logHandler = new SVNXMLLogHandler(th); // work around for http://svnkit.com/tracker/view.php?id=175 th.setDocumentLocator(DUMMY_LOCATOR); logHandler.startDocument(); for (ModuleLocation l : scm.getLocations()) { changelogFileCreated |= buildModule(l.remote, svnlc, logHandler); } for(String path : externals) { changelogFileCreated |= buildModule( getUrlForPath(build.getProject().getWorkspace().child(path)), svnlc, logHandler); } if(changelogFileCreated) { logHandler.endDocument(); } return changelogFileCreated; } finally { manager.dispose(); } } private String getUrlForPath(FilePath path) throws IOException, InterruptedException { return path.act(new GetUrlForPath(createAuthenticationProvider())); } private ISVNAuthenticationProvider createAuthenticationProvider() { return SubversionSCM.DescriptorImpl.DESCRIPTOR.createAuthenticationProvider(); } private boolean buildModule(String url, SVNLogClient svnlc, SVNXMLLogHandler logHandler) { PrintStream logger = listener.getLogger(); Long prevRev = previousRevisions.get(url); if(prevRev==null) { logger.println("no revision recorded for "+url+" in the previous build"); return false; } Long thisRev = thisRevisions.get(url); if (thisRev == null) { listener.error("No revision found for URL: " + url + " in " + SubversionSCM.getRevisionFile(build) + ". Revision file contains: " + thisRevisions.keySet()); return true; } if(thisRev.equals(prevRev)) { logger.println("no change for "+url+" since the previous build"); return false; } try { if(debug) listener.getLogger().printf("Computing changelog of %1s from %2s to %3s\n", SVNURL.parseURIEncoded(url), prevRev+1, thisRev); - svnlc.doLog(SVNURL.parseURIEncoded(url),null, - SVNRevision.UNDEFINED, SVNRevision.create(prevRev+1), - SVNRevision.create(thisRev), - false, true, Long.MAX_VALUE, - debug ? new DebugSVNLogHandler(logHandler) : logHandler); + svnlc.doLog(SVNURL.parseURIEncoded(url), + null, + SVNRevision.UNDEFINED, + SVNRevision.create(prevRev+1), + SVNRevision.create(thisRev), + false, // Don't stop on copy. + true, // Report paths. + 0, // Retrieve log entries for unlimited number of revisions. + debug ? new DebugSVNLogHandler(logHandler) : logHandler); if(debug) listener.getLogger().println("done"); } catch (SVNException e) { e.printStackTrace(listener.error("revision check failed on "+url)); } return true; } /** * Filter {@link ISVNLogEntryHandler} that dumps information. Used only for debugging. */ private class DebugSVNLogHandler implements ISVNLogEntryHandler { private final ISVNLogEntryHandler core; private DebugSVNLogHandler(ISVNLogEntryHandler core) { this.core = core; } public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { listener.getLogger().println("SVNLogEntry="+logEntry); core.handleLogEntry(logEntry); } } /** * Creates an identity transformer. */ private static TransformerHandler createTransformerHandler() { try { return ((SAXTransformerFactory) SAXTransformerFactory.newInstance()).newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new Error(e); // impossible } } private static final LocatorImpl DUMMY_LOCATOR = new LocatorImpl(); public static boolean debug = false; static { DUMMY_LOCATOR.setLineNumber(-1); DUMMY_LOCATOR.setColumnNumber(-1); } private static class GetUrlForPath implements FileCallable<String> { private final ISVNAuthenticationProvider authProvider; public GetUrlForPath(ISVNAuthenticationProvider authProvider) { this.authProvider = authProvider; } public String invoke(File p, VirtualChannel channel) throws IOException { final SVNClientManager manager = SubversionSCM.createSvnClientManager(authProvider); try { final SVNWCClient svnwc = manager.getWCClient(); SVNInfo info; try { info = svnwc.doInfo(p, SVNRevision.WORKING); return info.getURL().toDecodedString(); } catch (SVNException e) { e.printStackTrace(); return null; } } finally { manager.dispose(); } } private static final long serialVersionUID = 1L; } }
true
true
private boolean buildModule(String url, SVNLogClient svnlc, SVNXMLLogHandler logHandler) { PrintStream logger = listener.getLogger(); Long prevRev = previousRevisions.get(url); if(prevRev==null) { logger.println("no revision recorded for "+url+" in the previous build"); return false; } Long thisRev = thisRevisions.get(url); if (thisRev == null) { listener.error("No revision found for URL: " + url + " in " + SubversionSCM.getRevisionFile(build) + ". Revision file contains: " + thisRevisions.keySet()); return true; } if(thisRev.equals(prevRev)) { logger.println("no change for "+url+" since the previous build"); return false; } try { if(debug) listener.getLogger().printf("Computing changelog of %1s from %2s to %3s\n", SVNURL.parseURIEncoded(url), prevRev+1, thisRev); svnlc.doLog(SVNURL.parseURIEncoded(url),null, SVNRevision.UNDEFINED, SVNRevision.create(prevRev+1), SVNRevision.create(thisRev), false, true, Long.MAX_VALUE, debug ? new DebugSVNLogHandler(logHandler) : logHandler); if(debug) listener.getLogger().println("done"); } catch (SVNException e) { e.printStackTrace(listener.error("revision check failed on "+url)); } return true; }
private boolean buildModule(String url, SVNLogClient svnlc, SVNXMLLogHandler logHandler) { PrintStream logger = listener.getLogger(); Long prevRev = previousRevisions.get(url); if(prevRev==null) { logger.println("no revision recorded for "+url+" in the previous build"); return false; } Long thisRev = thisRevisions.get(url); if (thisRev == null) { listener.error("No revision found for URL: " + url + " in " + SubversionSCM.getRevisionFile(build) + ". Revision file contains: " + thisRevisions.keySet()); return true; } if(thisRev.equals(prevRev)) { logger.println("no change for "+url+" since the previous build"); return false; } try { if(debug) listener.getLogger().printf("Computing changelog of %1s from %2s to %3s\n", SVNURL.parseURIEncoded(url), prevRev+1, thisRev); svnlc.doLog(SVNURL.parseURIEncoded(url), null, SVNRevision.UNDEFINED, SVNRevision.create(prevRev+1), SVNRevision.create(thisRev), false, // Don't stop on copy. true, // Report paths. 0, // Retrieve log entries for unlimited number of revisions. debug ? new DebugSVNLogHandler(logHandler) : logHandler); if(debug) listener.getLogger().println("done"); } catch (SVNException e) { e.printStackTrace(listener.error("revision check failed on "+url)); } return true; }
diff --git a/src/com/android/mms/ui/SlideView.java b/src/com/android/mms/ui/SlideView.java index 4d3710b6..5b36b3c7 100644 --- a/src/com/android/mms/ui/SlideView.java +++ b/src/com/android/mms/ui/SlideView.java @@ -1,543 +1,544 @@ /* * Copyright (C) 2008 Esmertec AG. * 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.mms.ui; import com.android.mms.R; import com.android.mms.layout.LayoutManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaPlayer; import android.net.Uri; import android.text.method.HideReturnsTransformationMethod; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.AbsoluteLayout; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.MediaController; import android.widget.ScrollView; import android.widget.TextView; import android.widget.VideoView; import java.io.IOException; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; /** * A basic view to show the contents of a slide. */ public class SlideView extends AbsoluteLayout implements AdaptableSlideViewInterface { private static final String TAG = "SlideView"; private static final boolean DEBUG = false; private static final boolean LOCAL_LOGV = false; // FIXME: Need getHeight from mAudioInfoView instead of constant AUDIO_INFO_HEIGHT. private static final int AUDIO_INFO_HEIGHT = 82; private View mAudioInfoView; private ImageView mImageView; private VideoView mVideoView; private ScrollView mScrollText; private TextView mTextView; private OnSizeChangedListener mSizeChangedListener; private MediaPlayer mAudioPlayer; private boolean mIsPrepared; private boolean mStartWhenPrepared; private int mSeekWhenPrepared; private boolean mStopWhenPrepared; private ScrollView mScrollViewPort; private LinearLayout mViewPort; // Indicates whether the view is in MMS conformance mode. private boolean mConformanceMode; private MediaController mMediaController; MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() { public void onPrepared(MediaPlayer mp) { mIsPrepared = true; if (mSeekWhenPrepared > 0) { mAudioPlayer.seekTo(mSeekWhenPrepared); mSeekWhenPrepared = 0; } if (mStartWhenPrepared) { mAudioPlayer.start(); mStartWhenPrepared = false; displayAudioInfo(); } if (mStopWhenPrepared) { mAudioPlayer.stop(); mAudioPlayer.release(); mAudioPlayer = null; mStopWhenPrepared = false; hideAudioInfo(); } } }; public SlideView(Context context) { super(context); } public SlideView(Context context, AttributeSet attrs) { super(context, attrs); } public void setImage(String name, Bitmap bitmap) { if (mImageView == null) { mImageView = new ImageView(mContext); mImageView.setPadding(0, 5, 0, 5); addView(mImageView, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0)); if (DEBUG) { mImageView.setBackgroundColor(0xFFFF0000); } } try { if (null == bitmap) { bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_missing_thumbnail_picture); } mImageView.setVisibility(View.VISIBLE); mImageView.setImageBitmap(bitmap); } catch (java.lang.OutOfMemoryError e) { Log.e(TAG, "setImage: out of memory: ", e); } } public void setImageRegion(int left, int top, int width, int height) { // Ignore any requirement of layout change once we are in MMS conformance mode. if (mImageView != null && !mConformanceMode) { mImageView.setLayoutParams(new LayoutParams(width, height, left, top)); } } public void setImageRegionFit(String fit) { // TODO Auto-generated method stub } public void setVideo(String name, Uri video) { if (mVideoView == null) { mVideoView = new VideoView(mContext); addView(mVideoView, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0)); if (DEBUG) { mVideoView.setBackgroundColor(0xFFFF0000); } } if (LOCAL_LOGV) { Log.v(TAG, "Changing video source to " + video); } mVideoView.setVisibility(View.VISIBLE); mVideoView.setVideoURI(video); } public void setMediaController(MediaController mediaController) { mMediaController = mediaController; } private void initAudioInfoView(String name) { if (null == mAudioInfoView) { LayoutInflater factory = LayoutInflater.from(getContext()); mAudioInfoView = factory.inflate(R.layout.playing_audio_info, null); int height = mAudioInfoView.getHeight(); if (mConformanceMode) { mViewPort.addView(mAudioInfoView, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, AUDIO_INFO_HEIGHT)); } else { addView(mAudioInfoView, new LayoutParams( LayoutParams.MATCH_PARENT, AUDIO_INFO_HEIGHT, 0, getHeight() - AUDIO_INFO_HEIGHT)); if (DEBUG) { mAudioInfoView.setBackgroundColor(0xFFFF0000); } } } TextView audioName = (TextView) mAudioInfoView.findViewById(R.id.name); audioName.setText(name); mAudioInfoView.setVisibility(View.GONE); } private void displayAudioInfo() { if (null != mAudioInfoView) { mAudioInfoView.setVisibility(View.VISIBLE); } } private void hideAudioInfo() { if (null != mAudioInfoView) { mAudioInfoView.setVisibility(View.GONE); } } public void setAudio(Uri audio, String name, Map<String, ?> extras) { if (audio == null) { throw new IllegalArgumentException("Audio URI may not be null."); } if (LOCAL_LOGV) { Log.v(TAG, "Changing audio source to " + audio); } if (mAudioPlayer != null) { mAudioPlayer.reset(); mAudioPlayer.release(); mAudioPlayer = null; } // Reset state variables mIsPrepared = false; mStartWhenPrepared = false; mSeekWhenPrepared = 0; mStopWhenPrepared = false; try { mAudioPlayer = new MediaPlayer(); mAudioPlayer.setOnPreparedListener(mPreparedListener); mAudioPlayer.setDataSource(mContext, audio); mAudioPlayer.prepareAsync(); } catch (IOException e) { Log.e(TAG, "Unexpected IOException.", e); mAudioPlayer.release(); mAudioPlayer = null; } initAudioInfoView(name); } public void setText(String name, String text) { if (!mConformanceMode) { if (null == mScrollText) { mScrollText = new ScrollView(mContext); mScrollText.setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET); addView(mScrollText, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0)); if (DEBUG) { mScrollText.setBackgroundColor(0xFF00FF00); } } if (null == mTextView) { mTextView = new TextView(mContext); mTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); mScrollText.addView(mTextView); } mScrollText.requestFocus(); } mTextView.setVisibility(View.VISIBLE); mTextView.setText(text); } public void setTextRegion(int left, int top, int width, int height) { // Ignore any requirement of layout change once we are in MMS conformance mode. if (mScrollText != null && !mConformanceMode) { mScrollText.setLayoutParams(new LayoutParams(width, height, left, top)); } } public void setVideoRegion(int left, int top, int width, int height) { if (mVideoView != null && !mConformanceMode) { mVideoView.setLayoutParams(new LayoutParams(width, height, left, top)); } } public void setImageVisibility(boolean visible) { if (mImageView != null) { if (mConformanceMode) { mImageView.setVisibility(visible ? View.VISIBLE : View.GONE); } else { mImageView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); } } } public void setTextVisibility(boolean visible) { if (mConformanceMode) { if (mTextView != null) { mTextView.setVisibility(visible ? View.VISIBLE : View.GONE); } } else if (mScrollText != null) { mScrollText.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); } } public void setVideoVisibility(boolean visible) { if (mVideoView != null) { if (mConformanceMode) { mVideoView.setVisibility(visible ? View.VISIBLE : View.GONE); } else { mVideoView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); } } } public void startAudio() { if ((mAudioPlayer != null) && mIsPrepared) { mAudioPlayer.start(); mStartWhenPrepared = false; displayAudioInfo(); } else { mStartWhenPrepared = true; } } public void stopAudio() { if ((mAudioPlayer != null) && mIsPrepared) { mAudioPlayer.stop(); mAudioPlayer.release(); mAudioPlayer = null; hideAudioInfo(); } else { mStopWhenPrepared = true; } } public void pauseAudio() { if ((mAudioPlayer != null) && mIsPrepared) { if (mAudioPlayer.isPlaying()) { mAudioPlayer.pause(); } } mStartWhenPrepared = false; } public void seekAudio(int seekTo) { if ((mAudioPlayer != null) && mIsPrepared) { mAudioPlayer.seekTo(seekTo); } else { mSeekWhenPrepared = seekTo; } } public void startVideo() { if (mVideoView != null) { if (LOCAL_LOGV) { Log.v(TAG, "Starting video playback."); } mVideoView.start(); } } public void stopVideo() { if ((mVideoView != null)) { if (LOCAL_LOGV) { Log.v(TAG, "Stopping video playback."); } mVideoView.stopPlayback(); } } public void pauseVideo() { if (mVideoView != null) { if (LOCAL_LOGV) { Log.v(TAG, "Pausing video playback."); } mVideoView.pause(); } } public void seekVideo(int seekTo) { if (mVideoView != null) { if (seekTo > 0) { if (LOCAL_LOGV) { Log.v(TAG, "Seeking video playback to " + seekTo); } mVideoView.seekTo(seekTo); } } } public void reset() { if (null != mScrollText) { mScrollText.setVisibility(View.GONE); } if (null != mImageView) { mImageView.setVisibility(View.GONE); } if (null != mAudioPlayer) { stopAudio(); } if (null != mVideoView) { stopVideo(); mVideoView.setVisibility(View.GONE); } if (null != mTextView) { mTextView.setVisibility(View.GONE); } if (mScrollViewPort != null) { mScrollViewPort.scrollTo(0, 0); mScrollViewPort.setLayoutParams( new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 0, 0)); } } public void setVisibility(boolean visible) { // TODO Auto-generated method stub } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (mSizeChangedListener != null) { if (LOCAL_LOGV) { Log.v(TAG, "new size=" + w + "x" + h); } mSizeChangedListener.onSizeChanged(w, h - AUDIO_INFO_HEIGHT); } } public void setOnSizeChangedListener(OnSizeChangedListener l) { mSizeChangedListener = l; } private class Position { public Position(int left, int top) { mTop = top; mLeft = left; } public int mTop; public int mLeft; } /** * Makes the SlideView working on MMSConformance Mode. The view will be * re-layout to the linear view. * <p> * This is Chinese requirement about mms conformance. * The most popular Mms service in China is newspaper which is MMS conformance, * normally it mixes the image and text and has a number of slides. The * AbsoluteLayout doesn't have good user experience for this kind of message, * for example, * * 1. AbsoluteLayout exactly follows the smil's layout which is not optimized, * and actually, no other MMS applications follow the smil's layout, they adjust * the layout according their screen size. MMS conformance doc also allows the * implementation to adjust the layout. * * 2. The TextView is fixed in the small area of screen, and other part of screen * is empty once there is no image in the current slide. * * 3. The TextView is scrollable in a small area of screen and the font size is * small which make the user experience bad. * * The better UI for the MMS conformance message could be putting the image/video * and text in a linear layout view and making them scrollable together. * * Another reason for only applying the LinearLayout to the MMS conformance message * is that the AbsoluteLayout has ability to play image and video in a same screen. * which shouldn't be broken. */ public void enableMMSConformanceMode(int textLeft, int textTop, int imageLeft, int imageTop) { mConformanceMode = true; if (mScrollViewPort == null) { mScrollViewPort = new ScrollView(mContext) { private int mBottomY; @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (getChildCount() > 0) { int childHeight = getChildAt(0).getHeight(); int height = getHeight(); mBottomY = height < childHeight ? childHeight - height : 0; } } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { // Shows MediaController when the view is scrolled to the top/bottom of itself. if (t == 0 || t >= mBottomY){ - if (mMediaController != null) { + if (mMediaController != null + && !((SlideshowActivity) mContext).isFinishing()) { mMediaController.show(); } } } }; mScrollViewPort.setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET); mViewPort = new LinearLayout(mContext); mViewPort.setOrientation(LinearLayout.VERTICAL); mViewPort.setGravity(Gravity.CENTER); mViewPort.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mMediaController != null) { mMediaController.show(); } } }); mScrollViewPort.addView(mViewPort, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); addView(mScrollViewPort); } // Layout views to fit the LinearLayout from left to right, then top to // bottom. TreeMap<Position, View> viewsByPosition = new TreeMap<Position, View>(new Comparator<Position>() { public int compare(Position p1, Position p2) { int l1 = p1.mLeft; int t1 = p1.mTop; int l2 = p2.mLeft; int t2 = p2.mTop; int res = t1 - t2; if (res == 0) { res = l1 - l2; } if (res == 0) { // A view will be lost if return 0. return -1; } return res; } }); if (textLeft >=0 && textTop >=0) { mTextView = new TextView(mContext); mTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); mTextView.setTextSize(18); mTextView.setPadding(5, 5, 5, 5); viewsByPosition.put(new Position(textLeft, textTop), mTextView); } if (imageLeft >=0 && imageTop >=0) { mImageView = new ImageView(mContext); mImageView.setPadding(0, 5, 0, 5); viewsByPosition.put(new Position(imageLeft, imageTop), mImageView); // According MMS Conformance Document, the image and video should use the same // region. So, put the VideoView below the ImageView. mVideoView = new VideoView(mContext); viewsByPosition.put(new Position(imageLeft + 1, imageTop), mVideoView); } for (View view : viewsByPosition.values()) { if (view instanceof VideoView) { mViewPort.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutManager.getInstance().getLayoutParameters().getHeight())); } else { mViewPort.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); } view.setVisibility(View.GONE); } } }
true
true
public void enableMMSConformanceMode(int textLeft, int textTop, int imageLeft, int imageTop) { mConformanceMode = true; if (mScrollViewPort == null) { mScrollViewPort = new ScrollView(mContext) { private int mBottomY; @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (getChildCount() > 0) { int childHeight = getChildAt(0).getHeight(); int height = getHeight(); mBottomY = height < childHeight ? childHeight - height : 0; } } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { // Shows MediaController when the view is scrolled to the top/bottom of itself. if (t == 0 || t >= mBottomY){ if (mMediaController != null) { mMediaController.show(); } } } }; mScrollViewPort.setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET); mViewPort = new LinearLayout(mContext); mViewPort.setOrientation(LinearLayout.VERTICAL); mViewPort.setGravity(Gravity.CENTER); mViewPort.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mMediaController != null) { mMediaController.show(); } } }); mScrollViewPort.addView(mViewPort, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); addView(mScrollViewPort); } // Layout views to fit the LinearLayout from left to right, then top to // bottom. TreeMap<Position, View> viewsByPosition = new TreeMap<Position, View>(new Comparator<Position>() { public int compare(Position p1, Position p2) { int l1 = p1.mLeft; int t1 = p1.mTop; int l2 = p2.mLeft; int t2 = p2.mTop; int res = t1 - t2; if (res == 0) { res = l1 - l2; } if (res == 0) { // A view will be lost if return 0. return -1; } return res; } }); if (textLeft >=0 && textTop >=0) { mTextView = new TextView(mContext); mTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); mTextView.setTextSize(18); mTextView.setPadding(5, 5, 5, 5); viewsByPosition.put(new Position(textLeft, textTop), mTextView); } if (imageLeft >=0 && imageTop >=0) { mImageView = new ImageView(mContext); mImageView.setPadding(0, 5, 0, 5); viewsByPosition.put(new Position(imageLeft, imageTop), mImageView); // According MMS Conformance Document, the image and video should use the same // region. So, put the VideoView below the ImageView. mVideoView = new VideoView(mContext); viewsByPosition.put(new Position(imageLeft + 1, imageTop), mVideoView); } for (View view : viewsByPosition.values()) { if (view instanceof VideoView) { mViewPort.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutManager.getInstance().getLayoutParameters().getHeight())); } else { mViewPort.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); } view.setVisibility(View.GONE); } }
public void enableMMSConformanceMode(int textLeft, int textTop, int imageLeft, int imageTop) { mConformanceMode = true; if (mScrollViewPort == null) { mScrollViewPort = new ScrollView(mContext) { private int mBottomY; @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (getChildCount() > 0) { int childHeight = getChildAt(0).getHeight(); int height = getHeight(); mBottomY = height < childHeight ? childHeight - height : 0; } } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { // Shows MediaController when the view is scrolled to the top/bottom of itself. if (t == 0 || t >= mBottomY){ if (mMediaController != null && !((SlideshowActivity) mContext).isFinishing()) { mMediaController.show(); } } } }; mScrollViewPort.setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET); mViewPort = new LinearLayout(mContext); mViewPort.setOrientation(LinearLayout.VERTICAL); mViewPort.setGravity(Gravity.CENTER); mViewPort.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mMediaController != null) { mMediaController.show(); } } }); mScrollViewPort.addView(mViewPort, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); addView(mScrollViewPort); } // Layout views to fit the LinearLayout from left to right, then top to // bottom. TreeMap<Position, View> viewsByPosition = new TreeMap<Position, View>(new Comparator<Position>() { public int compare(Position p1, Position p2) { int l1 = p1.mLeft; int t1 = p1.mTop; int l2 = p2.mLeft; int t2 = p2.mTop; int res = t1 - t2; if (res == 0) { res = l1 - l2; } if (res == 0) { // A view will be lost if return 0. return -1; } return res; } }); if (textLeft >=0 && textTop >=0) { mTextView = new TextView(mContext); mTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); mTextView.setTextSize(18); mTextView.setPadding(5, 5, 5, 5); viewsByPosition.put(new Position(textLeft, textTop), mTextView); } if (imageLeft >=0 && imageTop >=0) { mImageView = new ImageView(mContext); mImageView.setPadding(0, 5, 0, 5); viewsByPosition.put(new Position(imageLeft, imageTop), mImageView); // According MMS Conformance Document, the image and video should use the same // region. So, put the VideoView below the ImageView. mVideoView = new VideoView(mContext); viewsByPosition.put(new Position(imageLeft + 1, imageTop), mVideoView); } for (View view : viewsByPosition.values()) { if (view instanceof VideoView) { mViewPort.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutManager.getInstance().getLayoutParameters().getHeight())); } else { mViewPort.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); } view.setVisibility(View.GONE); } }
diff --git a/src/core/java/org/wyona/yanel/cmdl/YanelCommandLine.java b/src/core/java/org/wyona/yanel/cmdl/YanelCommandLine.java index e7b385a4e..911bb1d58 100644 --- a/src/core/java/org/wyona/yanel/cmdl/YanelCommandLine.java +++ b/src/core/java/org/wyona/yanel/cmdl/YanelCommandLine.java @@ -1,263 +1,263 @@ /* * Copyright 2006 Wyona * * 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.wyona.org/licenses/APACHE-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.wyona.yanel.cmdl; import org.wyona.yanel.cmdl.communication.CommandLineRequest; import org.wyona.yanel.cmdl.communication.CommandLineResponse; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceTypeDefinition; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.Yanel; import org.wyona.yanel.core.api.attributes.CreatableV1; import org.wyona.yanel.core.api.attributes.CreatableV2; import org.wyona.yanel.core.api.attributes.ModifiableV1; import org.wyona.yanel.core.api.attributes.ViewableV1; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.map.Realm; import org.wyona.yanel.core.util.ResourceAttributeHelper; import org.wyona.security.core.api.Identity; import org.wyona.security.core.api.PolicyManager; import org.wyona.security.core.api.Role; import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.log4j.Category; /** * */ public class YanelCommandLine { private static Category log = Category.getInstance(YanelCommandLine.class); /** * */ static public void main(String[] args) throws Exception { System.out.println("Welcome to the Yanel command line interface!\n"); Yanel yanel = Yanel.getInstance(); yanel.init(); Map map = yanel.getMapImpl("map"); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); System.out.println("The following realms have been configured:"); Realm[] realms = yanel.getRealmConfiguration().getRealms(); for (int i = 0; i < realms.length; i++) { System.out.println("Realm: " + realms[i]); } System.out.println("\nThe following resource types have been configured:"); ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions(); for (int i = 0; i < rtds.length; i++) { System.out.println("Resource Type: " + rtds[i].getResourceTypeUniversalName()); } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String url = null; if (args.length != 1 || args[0].length() == 0) { System.out.println("\nPlease enter a path (e.g. /index.html):"); try { String value = br.readLine(); if (value.equals("")) { System.out.println("No path has been specified!"); return; } System.out.println("The following value has been entered: " + value); url = value; } catch (Exception e) { System.err.println(e); } } Realm realm = map.getRealm(url); String path = map.getPath(realm, url); //PolicyManager pm = (PolicyManager) yanel.getBeanFactory().getBean("policyManager"); PolicyManager pm = realm.getPolicyManager(); String[] groupnames = {"admin", "accounting"}; - if (pm.authorize(path, new Identity("lenya", groupnames), new Role("view"))) { + if (pm.authorize(path, new Identity("lenya", groupnames, "lenya"), new Role("view"))) { System.out.println("Access granted: " + path); } else { // TODO: Deny access resp. start login process! System.out.println("Access denied: " + path); } String rti = yanel.getResourceManager().getResourceTypeIdentifier(realm, path).getUniversalName(); //String rti = map.getResourceTypeIdentifier(path); System.out.println("Resource Type Identifier: " + rti); if (rti == null) { System.err.println("Abort, because resource type identifier is null!"); return; } ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti); if (rtd == null) { System.err.println("Abort, because no such resource type registered: " + rti); System.err.println("Make sure resource type is registered within " + rtr.getConfigurationFile()); return; } System.out.println("Local name: " + rtd.getResourceTypeLocalName()); System.out.println("Namespace: " + rtd.getResourceTypeNamespace()); Resource res = null; CommandLineRequest request = new CommandLineRequest(url); CommandLineResponse response = new CommandLineResponse(); try { res = rtr.newResource(rti); res.setYanel(yanel); res.setRequest(request); res.setResponse(response); } catch(Exception e) { System.err.println("Exception (also see log4j): " + e); log.error(e.getMessage(), e); return; } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Creatable", "1")) { System.out.println(((CreatableV1) res).getPropertyNames()); } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Creatable", "2")) { System.out.println(((CreatableV2) res).getPropertyType("name")); } else { System.out.println(res.getClass().getName() + " does not implement creatable interface, neither V1 nor V2!"); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { System.out.println("View Descriptors: " + ((ViewableV1) res).getViewDescriptors()); String viewId = null; try { View view = ((ViewableV1) res).getView(new Path(url), viewId); System.out.println("mime-type: " + view.getMimeType()); BufferedReader bReader = new BufferedReader(new java.io.InputStreamReader(view.getInputStream())); int k = 0; String line = null; while ((line = bReader.readLine()) != null) { k++; System.out.println("Line " + k + ": " + line); } } catch(Exception e) { System.err.println(e); } } else { System.out.println(res.getClass().getName() + " does not implement viewable V1 interface!"); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) { try { java.io.Reader reader = ((ModifiableV1) res).getReader(new Path(url)); } catch (Exception e) { System.err.println(e.getMessage()); } } else { System.out.println(res.getClass().getName() + " does not implement modifiable V1 interface!"); } /* Resource tapeRes = null; try { rti = "<{http://www.wyonapictures.com/yanel/resource/1.0}tape/>"; tapeRes = rtr.newResource(rti); rtd = rtr.getResourceTypeDefinition(rti); if (tapeRes != null) { tapeRes.setRTD(rtd); } else { System.err.println("No such resource registered for rti: " + rti); return; } } catch(Exception e) { System.err.println(e); return; } if (ResourceAttributeHelper.hasAttributeImplemented(tapeRes, "Creatable", "1")) { String[] names = ((CreatableV1) tapeRes).getPropertyNames(); String propNames = ""; for (int i = 0; i < names.length; i++) { if (i == names.length -1) { propNames = propNames + names[i]; } else { propNames = propNames + names[i] + ", "; } } System.out.println("Property Names: " + propNames); } else { System.out.println(tapeRes.getClass().getName() + " does not implement creatable interface!"); } Resource invoiceRes = null; try { rti = "<{http://www.wyona.com/yanel/resource/1.0}invoice/>"; invoiceRes = rtr.newResource(rti); rtd = rtr.getResourceTypeDefinition(rti); invoiceRes.setRTD(rtd); } catch(Exception e) { System.err.println(e); return; } if (ResourceAttributeHelper.hasAttributeImplemented(invoiceRes, "Creatable", "1")) { String[] names = ((CreatableV1) invoiceRes).getPropertyNames(); String propNames = ""; for (int i = 0; i < names.length; i++) { System.out.println("Please enter a value for property \"" + names[i] + "\":"); try { String value = br.readLine(); System.out.println("The following value has been entered: " + value); } catch (Exception e) { System.err.println(e); } if (i == names.length -1) { propNames = propNames + names[i]; } else { propNames = propNames + names[i] + ", "; } } System.out.println("Property Names: " + propNames); } else { System.out.println(invoiceRes.getClass().getName() + " does not implement creatable interface!"); } if (ResourceAttributeHelper.hasAttributeImplemented(invoiceRes, "Versionable", "1")) { System.out.println(invoiceRes.getClass().getName() + " does implement versionable interface!"); } else { System.out.println(invoiceRes.getClass().getName() + " does not implement versionable interface!"); } try { Resource websearchRes = rtr.newResource("<{http://www.wyona.org/yanel/resource/1.0}websearch/>"); websearchRes.setRTD(rtd); if (ResourceAttributeHelper.hasAttributeImplemented(websearchRes, "Continuable", "1")) System.out.println("yeah"); } catch(Exception e) { System.err.println(e); return; } */ } }
true
true
static public void main(String[] args) throws Exception { System.out.println("Welcome to the Yanel command line interface!\n"); Yanel yanel = Yanel.getInstance(); yanel.init(); Map map = yanel.getMapImpl("map"); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); System.out.println("The following realms have been configured:"); Realm[] realms = yanel.getRealmConfiguration().getRealms(); for (int i = 0; i < realms.length; i++) { System.out.println("Realm: " + realms[i]); } System.out.println("\nThe following resource types have been configured:"); ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions(); for (int i = 0; i < rtds.length; i++) { System.out.println("Resource Type: " + rtds[i].getResourceTypeUniversalName()); } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String url = null; if (args.length != 1 || args[0].length() == 0) { System.out.println("\nPlease enter a path (e.g. /index.html):"); try { String value = br.readLine(); if (value.equals("")) { System.out.println("No path has been specified!"); return; } System.out.println("The following value has been entered: " + value); url = value; } catch (Exception e) { System.err.println(e); } } Realm realm = map.getRealm(url); String path = map.getPath(realm, url); //PolicyManager pm = (PolicyManager) yanel.getBeanFactory().getBean("policyManager"); PolicyManager pm = realm.getPolicyManager(); String[] groupnames = {"admin", "accounting"}; if (pm.authorize(path, new Identity("lenya", groupnames), new Role("view"))) { System.out.println("Access granted: " + path); } else { // TODO: Deny access resp. start login process! System.out.println("Access denied: " + path); } String rti = yanel.getResourceManager().getResourceTypeIdentifier(realm, path).getUniversalName(); //String rti = map.getResourceTypeIdentifier(path); System.out.println("Resource Type Identifier: " + rti); if (rti == null) { System.err.println("Abort, because resource type identifier is null!"); return; } ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti); if (rtd == null) { System.err.println("Abort, because no such resource type registered: " + rti); System.err.println("Make sure resource type is registered within " + rtr.getConfigurationFile()); return; } System.out.println("Local name: " + rtd.getResourceTypeLocalName()); System.out.println("Namespace: " + rtd.getResourceTypeNamespace()); Resource res = null; CommandLineRequest request = new CommandLineRequest(url); CommandLineResponse response = new CommandLineResponse(); try { res = rtr.newResource(rti); res.setYanel(yanel); res.setRequest(request); res.setResponse(response); } catch(Exception e) { System.err.println("Exception (also see log4j): " + e); log.error(e.getMessage(), e); return; } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Creatable", "1")) { System.out.println(((CreatableV1) res).getPropertyNames()); } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Creatable", "2")) { System.out.println(((CreatableV2) res).getPropertyType("name")); } else { System.out.println(res.getClass().getName() + " does not implement creatable interface, neither V1 nor V2!"); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { System.out.println("View Descriptors: " + ((ViewableV1) res).getViewDescriptors()); String viewId = null; try { View view = ((ViewableV1) res).getView(new Path(url), viewId); System.out.println("mime-type: " + view.getMimeType()); BufferedReader bReader = new BufferedReader(new java.io.InputStreamReader(view.getInputStream())); int k = 0; String line = null; while ((line = bReader.readLine()) != null) { k++; System.out.println("Line " + k + ": " + line); } } catch(Exception e) { System.err.println(e); } } else { System.out.println(res.getClass().getName() + " does not implement viewable V1 interface!"); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) { try { java.io.Reader reader = ((ModifiableV1) res).getReader(new Path(url)); } catch (Exception e) { System.err.println(e.getMessage()); } } else { System.out.println(res.getClass().getName() + " does not implement modifiable V1 interface!"); } /* Resource tapeRes = null; try { rti = "<{http://www.wyonapictures.com/yanel/resource/1.0}tape/>"; tapeRes = rtr.newResource(rti); rtd = rtr.getResourceTypeDefinition(rti); if (tapeRes != null) { tapeRes.setRTD(rtd); } else { System.err.println("No such resource registered for rti: " + rti); return; } } catch(Exception e) { System.err.println(e); return; } if (ResourceAttributeHelper.hasAttributeImplemented(tapeRes, "Creatable", "1")) { String[] names = ((CreatableV1) tapeRes).getPropertyNames(); String propNames = ""; for (int i = 0; i < names.length; i++) { if (i == names.length -1) { propNames = propNames + names[i]; } else { propNames = propNames + names[i] + ", "; } } System.out.println("Property Names: " + propNames); } else { System.out.println(tapeRes.getClass().getName() + " does not implement creatable interface!"); } Resource invoiceRes = null; try { rti = "<{http://www.wyona.com/yanel/resource/1.0}invoice/>"; invoiceRes = rtr.newResource(rti); rtd = rtr.getResourceTypeDefinition(rti); invoiceRes.setRTD(rtd); } catch(Exception e) { System.err.println(e); return; } if (ResourceAttributeHelper.hasAttributeImplemented(invoiceRes, "Creatable", "1")) { String[] names = ((CreatableV1) invoiceRes).getPropertyNames(); String propNames = ""; for (int i = 0; i < names.length; i++) { System.out.println("Please enter a value for property \"" + names[i] + "\":"); try { String value = br.readLine(); System.out.println("The following value has been entered: " + value); } catch (Exception e) { System.err.println(e); } if (i == names.length -1) { propNames = propNames + names[i]; } else { propNames = propNames + names[i] + ", "; } } System.out.println("Property Names: " + propNames); } else { System.out.println(invoiceRes.getClass().getName() + " does not implement creatable interface!"); } if (ResourceAttributeHelper.hasAttributeImplemented(invoiceRes, "Versionable", "1")) { System.out.println(invoiceRes.getClass().getName() + " does implement versionable interface!"); } else { System.out.println(invoiceRes.getClass().getName() + " does not implement versionable interface!"); } try { Resource websearchRes = rtr.newResource("<{http://www.wyona.org/yanel/resource/1.0}websearch/>"); websearchRes.setRTD(rtd); if (ResourceAttributeHelper.hasAttributeImplemented(websearchRes, "Continuable", "1")) System.out.println("yeah"); } catch(Exception e) { System.err.println(e); return; } */ }
static public void main(String[] args) throws Exception { System.out.println("Welcome to the Yanel command line interface!\n"); Yanel yanel = Yanel.getInstance(); yanel.init(); Map map = yanel.getMapImpl("map"); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); System.out.println("The following realms have been configured:"); Realm[] realms = yanel.getRealmConfiguration().getRealms(); for (int i = 0; i < realms.length; i++) { System.out.println("Realm: " + realms[i]); } System.out.println("\nThe following resource types have been configured:"); ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions(); for (int i = 0; i < rtds.length; i++) { System.out.println("Resource Type: " + rtds[i].getResourceTypeUniversalName()); } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String url = null; if (args.length != 1 || args[0].length() == 0) { System.out.println("\nPlease enter a path (e.g. /index.html):"); try { String value = br.readLine(); if (value.equals("")) { System.out.println("No path has been specified!"); return; } System.out.println("The following value has been entered: " + value); url = value; } catch (Exception e) { System.err.println(e); } } Realm realm = map.getRealm(url); String path = map.getPath(realm, url); //PolicyManager pm = (PolicyManager) yanel.getBeanFactory().getBean("policyManager"); PolicyManager pm = realm.getPolicyManager(); String[] groupnames = {"admin", "accounting"}; if (pm.authorize(path, new Identity("lenya", groupnames, "lenya"), new Role("view"))) { System.out.println("Access granted: " + path); } else { // TODO: Deny access resp. start login process! System.out.println("Access denied: " + path); } String rti = yanel.getResourceManager().getResourceTypeIdentifier(realm, path).getUniversalName(); //String rti = map.getResourceTypeIdentifier(path); System.out.println("Resource Type Identifier: " + rti); if (rti == null) { System.err.println("Abort, because resource type identifier is null!"); return; } ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti); if (rtd == null) { System.err.println("Abort, because no such resource type registered: " + rti); System.err.println("Make sure resource type is registered within " + rtr.getConfigurationFile()); return; } System.out.println("Local name: " + rtd.getResourceTypeLocalName()); System.out.println("Namespace: " + rtd.getResourceTypeNamespace()); Resource res = null; CommandLineRequest request = new CommandLineRequest(url); CommandLineResponse response = new CommandLineResponse(); try { res = rtr.newResource(rti); res.setYanel(yanel); res.setRequest(request); res.setResponse(response); } catch(Exception e) { System.err.println("Exception (also see log4j): " + e); log.error(e.getMessage(), e); return; } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Creatable", "1")) { System.out.println(((CreatableV1) res).getPropertyNames()); } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Creatable", "2")) { System.out.println(((CreatableV2) res).getPropertyType("name")); } else { System.out.println(res.getClass().getName() + " does not implement creatable interface, neither V1 nor V2!"); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { System.out.println("View Descriptors: " + ((ViewableV1) res).getViewDescriptors()); String viewId = null; try { View view = ((ViewableV1) res).getView(new Path(url), viewId); System.out.println("mime-type: " + view.getMimeType()); BufferedReader bReader = new BufferedReader(new java.io.InputStreamReader(view.getInputStream())); int k = 0; String line = null; while ((line = bReader.readLine()) != null) { k++; System.out.println("Line " + k + ": " + line); } } catch(Exception e) { System.err.println(e); } } else { System.out.println(res.getClass().getName() + " does not implement viewable V1 interface!"); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) { try { java.io.Reader reader = ((ModifiableV1) res).getReader(new Path(url)); } catch (Exception e) { System.err.println(e.getMessage()); } } else { System.out.println(res.getClass().getName() + " does not implement modifiable V1 interface!"); } /* Resource tapeRes = null; try { rti = "<{http://www.wyonapictures.com/yanel/resource/1.0}tape/>"; tapeRes = rtr.newResource(rti); rtd = rtr.getResourceTypeDefinition(rti); if (tapeRes != null) { tapeRes.setRTD(rtd); } else { System.err.println("No such resource registered for rti: " + rti); return; } } catch(Exception e) { System.err.println(e); return; } if (ResourceAttributeHelper.hasAttributeImplemented(tapeRes, "Creatable", "1")) { String[] names = ((CreatableV1) tapeRes).getPropertyNames(); String propNames = ""; for (int i = 0; i < names.length; i++) { if (i == names.length -1) { propNames = propNames + names[i]; } else { propNames = propNames + names[i] + ", "; } } System.out.println("Property Names: " + propNames); } else { System.out.println(tapeRes.getClass().getName() + " does not implement creatable interface!"); } Resource invoiceRes = null; try { rti = "<{http://www.wyona.com/yanel/resource/1.0}invoice/>"; invoiceRes = rtr.newResource(rti); rtd = rtr.getResourceTypeDefinition(rti); invoiceRes.setRTD(rtd); } catch(Exception e) { System.err.println(e); return; } if (ResourceAttributeHelper.hasAttributeImplemented(invoiceRes, "Creatable", "1")) { String[] names = ((CreatableV1) invoiceRes).getPropertyNames(); String propNames = ""; for (int i = 0; i < names.length; i++) { System.out.println("Please enter a value for property \"" + names[i] + "\":"); try { String value = br.readLine(); System.out.println("The following value has been entered: " + value); } catch (Exception e) { System.err.println(e); } if (i == names.length -1) { propNames = propNames + names[i]; } else { propNames = propNames + names[i] + ", "; } } System.out.println("Property Names: " + propNames); } else { System.out.println(invoiceRes.getClass().getName() + " does not implement creatable interface!"); } if (ResourceAttributeHelper.hasAttributeImplemented(invoiceRes, "Versionable", "1")) { System.out.println(invoiceRes.getClass().getName() + " does implement versionable interface!"); } else { System.out.println(invoiceRes.getClass().getName() + " does not implement versionable interface!"); } try { Resource websearchRes = rtr.newResource("<{http://www.wyona.org/yanel/resource/1.0}websearch/>"); websearchRes.setRTD(rtd); if (ResourceAttributeHelper.hasAttributeImplemented(websearchRes, "Continuable", "1")) System.out.println("yeah"); } catch(Exception e) { System.err.println(e); return; } */ }
diff --git a/src/html2windows/dom/AttrInter.java b/src/html2windows/dom/AttrInter.java index c84db98..b54be59 100644 --- a/src/html2windows/dom/AttrInter.java +++ b/src/html2windows/dom/AttrInter.java @@ -1,254 +1,259 @@ package html2windows.dom; import org.w3c.dom.DOMException; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventException; import org.w3c.dom.events.EventListener; import java.util.List; import java.util.ArrayList; class AttrInter implements Attr, NodeInter{ private String name; private boolean specified = false; private Document ownerDocument; private Element ownerElement; private List<Node> childNodes = new ArrayList<Node>(); public String name(){ return name; } public boolean specified(){ return specified; } /** * Return the value of attribute. * @return concatenation of children nodes of the attribute. */ public String value(){ String value = ""; for(Node child : childNodes){ value += child.nodeValue(); } return value; } public AttrInter(String name){ this.name = name; } public void setValue(String value){ this.specified = true; // Empty replace all children with value for(Node child : childNodes){ removeChild(child); } Text text = ownerDocument.createTextNode(value); appendChild(text); } public Element ownerElement(){ return this.ownerElement; } public void setOwnerElement(Element newOwnerElement){ this.ownerElement = newOwnerElement; } @Override public String nodeName() { return name(); } @Override public String nodeValue() { return value(); } @Override public short nodeType() { return ATTRIBUTE_NODE; } /** * Attribute nodes have no parent. * @return null */ @Override public Node parentNode() { return null; } @Override public void setParentNode(Node newParent) { } @Override public NodeList childNodes() { NodeList list = new NodeList(); for(Node node : childNodes){ list.add(node); } return list; } @Override public Node firstChild() { if(!childNodes.isEmpty()) return childNodes.get(0); else return null; } @Override public Node lastChild() { if(!childNodes.isEmpty()) return childNodes.get(childNodes.size() - 1); else return null; } /** * Attribute nodes have no previous sibling. * @return null */ @Override public Node previousSibling() { return null; } /** * Attribute nodes have no next sibling. * @return null */ @Override public Node nextSibling() { return null; } @Override public NamedNodeMap attributes() { return null; } @Override public Document ownerDocument() { return ownerDocument; } @Override public void setOwnerDocument(Document newOwnerDocument) { ownerDocument = newOwnerDocument; } @Override public Node insertBefore(Node newChild, Node refChild) throws DOMException { if(refChild != null){ if(!childNodes.contains(refChild)){ throw new DOMException(DOMException.NOT_FOUND_ERR, "refChild is not found"); } int index = childNodes.indexOf(refChild); add(index, newChild); } else{ appendChild(newChild); } return null; } @Override public Node replaceChild(Node newChild, Node oldChild) throws DOMException { if(!childNodes.contains(oldChild)){ throw new DOMException(DOMException.NOT_FOUND_ERR, "oldChild is not found"); } int index = childNodes.indexOf(oldChild); remove(oldChild); add(index, newChild); return oldChild; } @Override public Node removeChild(Node oldChild) throws DOMException { if(!childNodes.contains(oldChild)){ throw new DOMException(DOMException.NOT_FOUND_ERR, "oldChild is not found"); } remove(oldChild); return oldChild; } @Override public Node appendChild(Node newChild) throws DOMException { add(childNodes.size(), newChild); return newChild; } @Override public boolean hasChildNodes() { return !childNodes.isEmpty(); } @Override public boolean hasAttributes() { return false; } @Override public void addEventListener(String type, EventListener listener, boolean useCapture) { // TODO Auto-generated method stub } @Override public void removeEventListener(String type, EventListener listener, boolean useCapture) { // TODO Auto-generated method stub } @Override public boolean dispatchEvent(Event evt) throws EventException { // TODO Auto-generated method stub return false; } private void add(int index, Node newChild){ this.specified = true; if(newChild.ownerDocument() != this.ownerDocument()){ throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "Need import node first"); } switch(newChild.nodeType()){ case TEXT_NODE : { - if(newChild.parentNode() == this && childNodes.indexOf(newChild) > index) + /* + * If newChild is a child of this node, It need to be removed first + * and children after newChild will shift 1 position + * so insertion index need to subtract 1. + */ + if(newChild.parentNode() == this && childNodes.indexOf(newChild) < index) index--; newChild.parentNode().removeChild(newChild); childNodes.add(index, newChild); NodeInter newChildInternal = (NodeInter)newChild; newChildInternal.setParentNode(this); } break; default : throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Unacceptable node type"); } } private void remove(Node oldChild){ this.specified = true; childNodes.remove(oldChild); ((NodeInter)oldChild).setParentNode(null); } }
true
true
private void add(int index, Node newChild){ this.specified = true; if(newChild.ownerDocument() != this.ownerDocument()){ throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "Need import node first"); } switch(newChild.nodeType()){ case TEXT_NODE : { if(newChild.parentNode() == this && childNodes.indexOf(newChild) > index) index--; newChild.parentNode().removeChild(newChild); childNodes.add(index, newChild); NodeInter newChildInternal = (NodeInter)newChild; newChildInternal.setParentNode(this); } break; default : throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Unacceptable node type"); } }
private void add(int index, Node newChild){ this.specified = true; if(newChild.ownerDocument() != this.ownerDocument()){ throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "Need import node first"); } switch(newChild.nodeType()){ case TEXT_NODE : { /* * If newChild is a child of this node, It need to be removed first * and children after newChild will shift 1 position * so insertion index need to subtract 1. */ if(newChild.parentNode() == this && childNodes.indexOf(newChild) < index) index--; newChild.parentNode().removeChild(newChild); childNodes.add(index, newChild); NodeInter newChildInternal = (NodeInter)newChild; newChildInternal.setParentNode(this); } break; default : throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Unacceptable node type"); } }
diff --git a/flexodesktop/generators/flexogenerator/src/main/java/org/openflexo/velocity/FlexoVelocityIntrospector.java b/flexodesktop/generators/flexogenerator/src/main/java/org/openflexo/velocity/FlexoVelocityIntrospector.java index 37f63db38..1846e8e84 100644 --- a/flexodesktop/generators/flexogenerator/src/main/java/org/openflexo/velocity/FlexoVelocityIntrospector.java +++ b/flexodesktop/generators/flexogenerator/src/main/java/org/openflexo/velocity/FlexoVelocityIntrospector.java @@ -1,128 +1,128 @@ /* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo 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. * * OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.velocity; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.velocity.util.introspection.Info; import org.apache.velocity.util.introspection.UberspectImpl; import org.apache.velocity.util.introspection.VelMethod; import org.apache.velocity.util.introspection.VelPropertyGet; import org.openflexo.antar.binding.BindingDefinition; import org.openflexo.antar.binding.BindingDefinition.BindingDefinitionType; import org.openflexo.foundation.ontology.EditionPatternInstance; import org.openflexo.foundation.viewpoint.binding.ViewPointDataBinding; import org.openflexo.logging.FlexoLogger; public class FlexoVelocityIntrospector extends UberspectImpl { private static final Logger logger = FlexoLogger.getLogger(FlexoVelocityIntrospector.class.getPackage().getName()); @Override public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i) throws Exception { if (obj == null) { return null; } // Allow to use the 'magic' methods provided by Velocity on array (ex. get(x)) if (obj instanceof Object[]) { return super.getMethod(obj, methodName, args, i); } Class objClass = obj.getClass(); Method m = introspector.getMethod(objClass, methodName, args); if (m != null) { // Fix a bug in security manager of JDK1.5 where access to a public method of a non-visible inherited class is refused although // it // shouldn't (e.g, the method length() on StringBuilder is inherited from AbstractStringBuilder which has a package visibility) try { m.setAccessible(true); } catch (SecurityException e) { if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, "Security exception for method: " + objClass + "." + methodName, e); } } return m != null ? new VelMethodImpl(m) : null; } // if it's an array - if (objClass instanceof Class) { + if (obj instanceof Class) { m = introspector.getMethod((Class<?>) obj, methodName, args); if (m != null) { return new VelMethodImpl(m); } } if (obj instanceof EditionPatternInstance) { EditionPatternInstance epi = (EditionPatternInstance) obj; ViewPointDataBinding vpdb = VPBindingEvaluator.buildBindingForMethodAndParams(methodName, args); vpdb.setOwner(epi.getPattern()); vpdb.setBindingDefinition(new BindingDefinition(methodName, Object.class, BindingDefinitionType.GET, false)); if (vpdb.isValid()) { return new VPBindingEvaluator(vpdb, epi); } } if (logger.isLoggable(Level.INFO)) { logger.info("Method '" + methodName + "' could not be found on " + objClass.getName() + " called in " + i.getTemplateName() + " at line " + i.getLine() + " column " + i.getColumn()); } return null; } @Override public VelPropertyGet getPropertyGet(Object obj, String identifier, Info i) throws Exception { VelPropertyGet get = super.getPropertyGet(obj, identifier, i); if (get == null) { if (obj instanceof EditionPatternInstance) { EditionPatternInstance epi = (EditionPatternInstance) obj; ViewPointDataBinding vpdb = new ViewPointDataBinding(identifier); vpdb.setOwner(epi.getPattern()); vpdb.setBindingDefinition(new BindingDefinition(identifier, Object.class, BindingDefinitionType.GET, false)); if (vpdb.isValid()) { return new VPBindingEvaluator(vpdb, epi); } } get = getPropertyGetForClass(obj.getClass(), identifier, i); if (get == null && obj instanceof Class) { get = getPropertyGetForClass((Class<?>) obj, identifier, i); } } return get; } private VelPropertyGet getPropertyGetForClass(Class<?> klass, String identifier, Info i) { try { return new FlexoVelocityPropertyGet(klass, identifier); } catch (NoSuchFieldException e) { if (logger.isLoggable(Level.INFO)) { logger.info("Field '" + identifier + "' could not be found on " + klass.getName() + " called in " + i.getTemplateName() + " at line " + i.getLine() + " column " + i.getColumn()); } } catch (SecurityException e) { if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, "Security exception for field: " + klass + "." + identifier, e); } } return null; } }
true
true
public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i) throws Exception { if (obj == null) { return null; } // Allow to use the 'magic' methods provided by Velocity on array (ex. get(x)) if (obj instanceof Object[]) { return super.getMethod(obj, methodName, args, i); } Class objClass = obj.getClass(); Method m = introspector.getMethod(objClass, methodName, args); if (m != null) { // Fix a bug in security manager of JDK1.5 where access to a public method of a non-visible inherited class is refused although // it // shouldn't (e.g, the method length() on StringBuilder is inherited from AbstractStringBuilder which has a package visibility) try { m.setAccessible(true); } catch (SecurityException e) { if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, "Security exception for method: " + objClass + "." + methodName, e); } } return m != null ? new VelMethodImpl(m) : null; } // if it's an array if (objClass instanceof Class) { m = introspector.getMethod((Class<?>) obj, methodName, args); if (m != null) { return new VelMethodImpl(m); } } if (obj instanceof EditionPatternInstance) { EditionPatternInstance epi = (EditionPatternInstance) obj; ViewPointDataBinding vpdb = VPBindingEvaluator.buildBindingForMethodAndParams(methodName, args); vpdb.setOwner(epi.getPattern()); vpdb.setBindingDefinition(new BindingDefinition(methodName, Object.class, BindingDefinitionType.GET, false)); if (vpdb.isValid()) { return new VPBindingEvaluator(vpdb, epi); } } if (logger.isLoggable(Level.INFO)) { logger.info("Method '" + methodName + "' could not be found on " + objClass.getName() + " called in " + i.getTemplateName() + " at line " + i.getLine() + " column " + i.getColumn()); } return null; }
public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i) throws Exception { if (obj == null) { return null; } // Allow to use the 'magic' methods provided by Velocity on array (ex. get(x)) if (obj instanceof Object[]) { return super.getMethod(obj, methodName, args, i); } Class objClass = obj.getClass(); Method m = introspector.getMethod(objClass, methodName, args); if (m != null) { // Fix a bug in security manager of JDK1.5 where access to a public method of a non-visible inherited class is refused although // it // shouldn't (e.g, the method length() on StringBuilder is inherited from AbstractStringBuilder which has a package visibility) try { m.setAccessible(true); } catch (SecurityException e) { if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, "Security exception for method: " + objClass + "." + methodName, e); } } return m != null ? new VelMethodImpl(m) : null; } // if it's an array if (obj instanceof Class) { m = introspector.getMethod((Class<?>) obj, methodName, args); if (m != null) { return new VelMethodImpl(m); } } if (obj instanceof EditionPatternInstance) { EditionPatternInstance epi = (EditionPatternInstance) obj; ViewPointDataBinding vpdb = VPBindingEvaluator.buildBindingForMethodAndParams(methodName, args); vpdb.setOwner(epi.getPattern()); vpdb.setBindingDefinition(new BindingDefinition(methodName, Object.class, BindingDefinitionType.GET, false)); if (vpdb.isValid()) { return new VPBindingEvaluator(vpdb, epi); } } if (logger.isLoggable(Level.INFO)) { logger.info("Method '" + methodName + "' could not be found on " + objClass.getName() + " called in " + i.getTemplateName() + " at line " + i.getLine() + " column " + i.getColumn()); } return null; }
diff --git a/src/com/sonyericsson/chkbugreport/plugins/logs/LogPlugin.java b/src/com/sonyericsson/chkbugreport/plugins/logs/LogPlugin.java index cb6a589..e8dd524 100644 --- a/src/com/sonyericsson/chkbugreport/plugins/logs/LogPlugin.java +++ b/src/com/sonyericsson/chkbugreport/plugins/logs/LogPlugin.java @@ -1,694 +1,693 @@ /* * Copyright (C) 2011 Sony Ericsson Mobile Communications AB * * This file is part of ChkBugReport. * * ChkBugReport 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. * * ChkBugReport 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 ChkBugReport. If not, see <http://www.gnu.org/licenses/>. */ package com.sonyericsson.chkbugreport.plugins.logs; import com.sonyericsson.chkbugreport.BugReportModule; import com.sonyericsson.chkbugreport.Module; import com.sonyericsson.chkbugreport.Plugin; import com.sonyericsson.chkbugreport.ProcessRecord; import com.sonyericsson.chkbugreport.Section; import com.sonyericsson.chkbugreport.Util; import com.sonyericsson.chkbugreport.doc.Block; import com.sonyericsson.chkbugreport.doc.Bug; import com.sonyericsson.chkbugreport.doc.Chapter; import com.sonyericsson.chkbugreport.doc.DocNode; import com.sonyericsson.chkbugreport.doc.Img; import com.sonyericsson.chkbugreport.doc.Link; import com.sonyericsson.chkbugreport.doc.Para; import com.sonyericsson.chkbugreport.doc.ProcessLink; import com.sonyericsson.chkbugreport.doc.Table; import com.sonyericsson.chkbugreport.plugins.SysPropsPlugin; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Vector; import javax.imageio.ImageIO; public abstract class LogPlugin extends Plugin { public static final String TAG = "[LogPlugin]"; private static final long DAY = 24 * 60 * 60 * 1000; private HashMap<Integer,ProcessLog> mLogs = new HashMap<Integer, ProcessLog>(); private long mTsFirst = -1; private long mTsLast = -1; private String mWhich; private String mId; private String mSectionName; private HashMap<Integer,GCRecords> mGCs = new HashMap<Integer, GCRecords>(); private Vector<LogLine> mParsedLog = new Vector<LogLine>(); private Vector<ConfigChange> mConfigChanges = new Vector<ConfigChange>(); private boolean mLoaded = false; private Section mSection; private Chapter mCh; public LogPlugin(String which, String id, String sectionName) { mWhich = which; mId = id; mSectionName = sectionName; } public Chapter getChapter() { return mCh; } public Vector<LogLine> getLogs() { return mParsedLog; } @Override public void reset() { mTsFirst = -1; mTsLast = -1; mGCs.clear(); mParsedLog.clear(); mLogs.clear(); mLoaded = false; mSection = null; mCh = null; mConfigChanges.clear(); } @Override public void load(Module rep) { BugReportModule br = (BugReportModule)rep; mSection = br.findSection(mSectionName); if (mSection == null) { br.printErr(3, TAG + "Cannot find section " + mSectionName + " (aborting plugin)"); return; } // Load and parse the lines mCh = new Chapter(br, mWhich + " log"); int cnt = mSection.getLineCount(); int fmt = LogLine.FMT_UNKNOWN; LogLine prev = null; int skippedDueToTimeJump = 0; for (int i = 0; i < cnt; i++) { String line = mSection.getLine(i); LogLine sl = new LogLine(br, line, fmt, prev); if (sl.ok) { // Check for timejumps if (prev != null) { if (prev.ts + DAY < sl.ts) { // We got a huge timejump, ignore everything before this skippedDueToTimeJump += mParsedLog.size(); mParsedLog.clear(); prev = null; } } mParsedLog.add(sl); fmt = sl.fmt; prev = sl; } } cnt = mParsedLog.size(); if (cnt > 0) { mTsFirst = mParsedLog.get(0).ts; mTsLast = mParsedLog.get(cnt - 1).ts; } // Check for timestamp order int orderErrors = 0; Vector<LogLine> errLines = new Vector<LogLine>(); LogLine lastLine = null; for (int i = 0; i < cnt; i++) { LogLine sl = mParsedLog.get(i); if (sl.ok) { if (lastLine != null) { if (lastLine.ts > sl.ts) { orderErrors++; errLines.add(lastLine); errLines.add(sl); } } lastLine = sl; } } if (orderErrors > 0) { Bug bug = new Bug(Bug.PRIO_INCORRECT_LOG_ORDER, 0, "Incorrect timestamp order in " + mSectionName); bug.add(new Block() .add("Timestamps are not in correct order in the ") .add(new Link(getChapter().getAnchor(), mSectionName))); bug.add(new Block() .add("This could effect some plugins, which might produce wrong data! The following lines seems to be out of order:")); DocNode log = new Block(bug).addStyle("log"); boolean first = false; log.add("..."); for (LogLine ll : errLines) { first = !first; log.add(ll.copy()); if (!first) { log.add("..."); } } br.addBug(bug); } if (orderErrors > 0) { Bug bug = new Bug(Bug.PRIO_LOG_TIMEJUMP, 0, "Huge time gap in " + mSectionName); bug.add(new Block() .add("There was at least one huge time gap (at least one day) in the log. The lines before the last time gap (" + skippedDueToTimeJump + " lines) have been skipped in the ") .add(new Link(getChapter().getAnchor(), mSectionName))); br.addBug(bug); } // Analyze the log for (int i = 0; i < cnt; i++) { LogLine sl = mParsedLog.get(i); if (sl.ok) { // Analyze the log line analyze(sl, i, br, mSection); } } onLoaded(br); // Load successful mLoaded = true; } protected void onLoaded(BugReportModule br) { // NOP } @Override public void generate(Module rep) { BugReportModule br = (BugReportModule)rep; if (!mLoaded) { return; } mCh.addChapter(generateLog(br)); // Generate the log spammer top-list generateSpamTopList(br, mCh); // Generate the GC graphs Chapter chGC = new Chapter(br, "GC graphs"); if (generateGCGraphs(br, chGC) > 0) { mCh.addChapter(chGC); } // Generate other extra sections generateExtra(br, mCh); br.addChapter(mCh); } private Chapter generateLog(BugReportModule br) { Chapter ch = new Chapter(br, "Log"); DocNode log = new Block().addStyle("log"); ch.add(log); int cnt = mParsedLog.size(); for (int i = 0; i < cnt; i++) { LogLine sl = mParsedLog.get(i); if (sl.ok) { ProcessLog pl = getLogOf(br, sl.pid); pl.add(sl.copy()); } log.add(sl); } return ch; } private void generateSpamTopList(BugReportModule br, Chapter mainCh) { Chapter ch = new Chapter(br, "Spam top list"); mainCh.addChapter(ch); ch.add(new Para().add("Processes which produced most of the log:")); // Copy the process logs into a vector, so we can sort it later on Vector<ProcessLog> vec = new Vector<ProcessLog>(); for (ProcessLog pl : mLogs.values()) { vec.add(pl); } // Sort the list Collections.sort(vec, new Comparator<ProcessLog>() { @Override public int compare(ProcessLog o1, ProcessLog o2) { return o2.getLineCount() - o1.getLineCount(); } }); // Render the data Table t = new Table(Table.FLAG_NONE); ch.add(t); t.addColumn("Process", Table.FLAG_NONE); t.addColumn("Pid", Table.FLAG_ALIGN_RIGHT); t.addColumn("Nr. of lines", Table.FLAG_ALIGN_RIGHT); t.addColumn("% of all log", Table.FLAG_ALIGN_RIGHT); t.begin(); int cnt = Math.min(10, vec.size()); int totLines = mParsedLog.size(); for (int i = 0; i < cnt; i++) { ProcessLog pl = vec.get(i); int pid = pl.mPid; int count = pl.getLineCount(); t.addData(new ProcessLink(br, pid)); t.addData(pid); t.addData(count); t.addData(String.format("%.1f%%", (count * 100.0f / totLines))); } t.end(); } protected String getAnchorToLine(int i) { return mId + "log_" + i; } protected String getId() { return mId; } public int getParsedLineCount() { return mParsedLog.size(); } public LogLine getParsedLine(int i) { return mParsedLog.get(i); } protected void generateExtra(BugReportModule br, Chapter ch) { // NOP } protected void analyze(LogLine sl, int i, BugReportModule br, Section s) { // NOP } protected ProcessLog getLogOf(BugReportModule br, int pid) { ProcessLog log = mLogs.get(pid); if (log == null) { log = new ProcessLog(br, pid); mLogs.put(pid, log); // Add link from global process record ProcessRecord pr = br.getProcessRecord(pid, true, true); String text = mWhich + " log (filtered by this process) &gt;&gt;&gt;"; new Block(pr).add(new Link(log.getAnchor(), text)); br.addExtraFile(log); } return log; } public long getFirstTs() { return mTsFirst; } public long getLastTs() { return mTsLast; } private int generateGCGraphs(BugReportModule br, Chapter ch) { int cnt = 0; for (GCRecords gcs : mGCs.values()) { if (gcs.size() >= 2) { if (generateGCGraph(br, ch, gcs)) { cnt++; } } } return cnt; } private boolean generateGCGraph(BugReportModule br, Chapter ch, GCRecords gcs) { int w = 800; int h = 300; int cx = 100; int cy = 250; int gw = 600; int gh = 200; int pid = gcs.get(0).pid; long firstTs = getFirstTs(); long duration = (getLastTs() - firstTs); int heapLimit = 32; if (duration <= 0) return false; // Fetch the heap limit from system properties SysPropsPlugin props = (SysPropsPlugin)br.getPlugin("SysPropsPlugin"); if (props != null) { String s = props.getProp("dalvik.vm.heapsize"); if (s != null) { if (s.endsWith("m")) { s = s.substring(0, s.length() - 1); } try { heapLimit = Integer.parseInt(s); } catch (NumberFormatException nfe) { } } } // Avoid issue when duration is too long long firstGcTs = gcs.get(0).ts; long realDuration = getLastTs() - firstGcTs; if (realDuration * 3 < duration) { // Need to scale it down duration = realDuration; firstTs = firstGcTs; } // Check if external memory tracking is enabled boolean hasExternal = false; for (GCRecord gc : gcs) { if (gc.memExtAlloc >= 0 || gc.memExtSize >= 0) { hasExternal = true; break; } } // Create an empty image BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D)img.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.WHITE); g.fillRect(0, 0, w, h); g.setColor(Color.LIGHT_GRAY); g.drawRect(0, 0, w - 1, h - 1); // Draw the axis int as = 5; g.setColor(Color.BLACK); g.drawLine(cx, cy, cx, cy - gh); g.drawLine(cx, cy, cx + gw, cy); g.drawLine(cx - as, cy - gh + as, cx, cy - gh); g.drawLine(cx + as, cy - gh + as, cx, cy - gh); g.drawLine(cx + gw - as, cy - as, cx + gw, cy); g.drawLine(cx + gw - as, cy + as, cx + gw, cy); // Draw the title FontMetrics fm = g.getFontMetrics(); String procName = ""; ProcessRecord pr = br.getProcessRecord(pid, false, false); if (pr != null) { procName = pr.getName(); } else { procName = Integer.toString(pid); } g.drawString("Memory after GC in process " + procName, 10, 10 + fm.getAscent()); // Draw the duration String dur; if (duration < 5*1000) { dur = String.format("%dms", duration); } else if (duration < 5*60*1000) { dur = String.format("%.1fs", duration / 1000.0f); } else if (duration < 5*60*60*1000) { dur = String.format("%.1fmin", duration / 60000.0f); } else { dur = String.format("%.1fh", duration / 3600000.0f); } dur = "Log length: " + dur; g.drawString(dur, w - 10 - fm.stringWidth(dur), 10 + fm.getAscent()); // Collect the maximum value int max = 0; for (GCRecord gc : gcs) { int total = gc.memExtSize + gc.memFreeSize; if (total > max) { max = total; } } max = max * 110 / 100; // add 10% for better visibility // Draw some guide lines int count = 5; int step = max / count; step = (step + 249) / 250 * 250; Color colGuide = new Color(0xc0c0ff); for (int i = 1; i <= count; i++) { int value = i * step; if (value > max) break; int yv = cy - value * gh / max; g.setColor(colGuide); g.drawLine(cx + 1, yv, cx + gw, yv); g.setColor(Color.BLACK); String s = "" + value + "K"; g.drawString(s, cx - fm.stringWidth(s) - 1, yv); } // Draw the config changes (useful to see the correlation between config changes and memory usage) Color colConfigChange = Color.LIGHT_GRAY; g.setColor(colConfigChange); int ccCnt = 0; for (ConfigChange cc : mConfigChanges) { long ts = cc.ts; if (ts < firstTs) continue; // skip one, this doesn't count int x = cx + (int)((ts - firstTs) * (gw - 1) / (duration)); g.drawLine(x, cy - 1, x, cy - gh); ccCnt++; } // Draw the heap limit line (if visible) int ylimit = (heapLimit*1024) * gh / max; if (ylimit < gh) { int yv = cy - ylimit; g.setColor(Color.BLACK); g.drawLine(cx + 1, yv, cx + gw, yv); g.drawString("" + heapLimit + "MB", cx + gw + 5, yv); } // Plot the values (size) Color colFreeSize = new Color(0xc0c080); Color colTotalSize = new Color(0x8080d7); int lastX = -1, lastYF = -1, lastYT = -1; int r = 3; for (GCRecord gc : gcs) { int yf = cy - gc.memFreeSize * (gh - 1) / max; int x = cx + (int)((gc.ts - getFirstTs()) * (gw - 1) / duration); g.setColor(colFreeSize); if (lastX != -1) { g.drawLine(lastX, lastYF, x, yf); } g.fillArc(x - r, yf - r, 2*r+1, 2*r+1, 0, 360); lastYF = yf; if (hasExternal) { int yt = cy - (gc.memFreeSize + gc.memExtSize) * (gh - 1) / max; g.setColor(colTotalSize); if (lastX != -1) { g.drawLine(lastX, lastYT, x, yt); } g.fillArc(x - r, yt - r, 2*r+1, 2*r+1, 0, 360); lastYT = yt; } lastX = x; } // Plot the values (alloc) Color colFreeAlloc = new Color(0x808000); Color colTotalAlloc = new Color(0x0000c0); lastX = -1; lastYF = -1; lastYT = -1; for (GCRecord gc : gcs) { int yf = cy - gc.memFreeAlloc * (gh - 1) / max; int x = cx + (int)((gc.ts - firstTs) * (gw - 1) / (duration)); g.setColor(colFreeAlloc); if (lastX != -1) { g.drawLine(lastX, lastYF, x, yf); } g.fillArc(x - r, yf - r, 2*r+1, 2*r+1, 0, 360); lastYF = yf; if (hasExternal) { int yt = cy - (gc.memFreeAlloc + gc.memExtAlloc) * (gh - 1) / max; g.setColor(colTotalAlloc); if (lastX != -1) { g.drawLine(lastX, lastYT, x, yt); } g.fillArc(x - r, yt - r, 2*r+1, 2*r+1, 0, 360); lastYT = yt; } lastX = x; } // Plot the values (alloc) Color colTotalAllocO = new Color(0xff4040); if (hasExternal) { lastX = -1; lastYF = -1; lastYT = -1; for (GCRecord gc : gcs) { int yt = cy - (gc.memFreeSize + gc.memExtAlloc) * (gh - 1) / max; int x = cx + (int)((gc.ts - firstTs) * (gw - 1) / (duration)); g.setColor(colTotalAllocO); if (lastX != -1) { g.drawLine(lastX, lastYT, x, yt); } g.fillArc(x - r, yt - r, 2*r+1, 2*r+1, 0, 360); lastX = x; lastYT = yt; } } // Draw the legend int yl = h - 10 - fm.getDescent(); String s = "VM Heap (alloc)"; g.setColor(colFreeAlloc); g.drawString(s, w * 1 / 4 - fm.stringWidth(s)/2, yl); if (hasExternal) { s = "VM Heap + External (alloc)"; g.setColor(colTotalAlloc); g.drawString(s, w * 2 / 4 - fm.stringWidth(s)/2, yl); s = "Mem footprint"; g.setColor(colTotalAllocO); g.drawString(s, w * 3 / 4 - fm.stringWidth(s)/2, yl); } yl -= fm.getHeight(); s = "VM Heap (size)"; g.setColor(colFreeSize); g.drawString(s, w * 1 / 4 - fm.stringWidth(s)/2, yl); if (hasExternal) { s = "VM Heap + External (size)"; g.setColor(colTotalSize); g.drawString(s, w * 2 / 4 - fm.stringWidth(s)/2, yl); } if (ccCnt > 0) { // Draw legend for config changes s = "| Config changes"; g.setColor(colConfigChange); g.drawString(s, w * 3 / 4 - fm.stringWidth(s)/2, yl); } // Save the image String fn = "gc_" + mId + "_" + pid + ".png"; try { ImageIO.write(img, "png", new File(br.getBaseDir() + fn)); } catch (IOException e) { e.printStackTrace(); } // Append a link at the end of the system log ch.add(new Img(fn)); // Also insert a link at the beginning of the per-process log ProcessLog pl = getLogOf(br, pid); pl.add(new Img(fn)); // And also add it to the process record if (pr != null) { - new Para(pr) - .add("Memory usage from GC " + mId + " logs:") - .add(new Img(fn)); + new Para(pr).add("Memory usage from GC " + mId + " logs:"); + pr.add(new Img(fn)); } return true; } protected void addActivityLaunchMarker(LogLine sl, String activity) { String cmp[] = activity.split("/"); if (cmp.length == 2) { if (cmp[1].startsWith(cmp[0])) { cmp[1] = cmp[1].substring(cmp[0].length()); } sl.addMarker("log-float", cmp[0] + "<br/>" + cmp[1], null); } } protected void addGCRecord(int pid, GCRecord gc) { GCRecords gcs = mGCs.get(pid); if (gcs == null) { gcs = new GCRecords(); mGCs.put(pid, gcs); } gcs.add(gc); } protected void addConfigChange(ConfigChange cc) { mConfigChanges.add(cc); } public static class GCRecord { public long ts; public int pid; public int memFreeAlloc; public int memExtAlloc; public int memFreeSize; public int memExtSize; public GCRecord(long ts, int pid, int memFreeAlloc, int memFreeSize, int memExtAlloc, int memExtSize) { this.ts = ts; this.pid = pid; this.memFreeAlloc = memFreeAlloc; this.memExtAlloc = memExtAlloc; this.memFreeSize = memFreeSize; this.memExtSize = memExtSize; } } public static class GCRecords extends Vector<GCRecord> { private static final long serialVersionUID = 1L; } class ProcessLog extends Chapter { private int mPid; private int mLines; public ProcessLog(Module mod, int pid) { super(mod, String.format(mId + "log_%05d.html", pid)); mPid = pid; } public int getPid() { return mPid; } public void add(LogLineBase ll) { // LogLines should never be added directly here // or else the anchors will be mixed up! Util.assertTrue(false); } public void add(LogLineBase.LogLineProxy ll) { super.add(ll); mLines++; } public int getLineCount() { return mLines; } } public static class ConfigChange { public long ts; public ConfigChange(long ts) { this.ts = ts; } } }
true
true
private boolean generateGCGraph(BugReportModule br, Chapter ch, GCRecords gcs) { int w = 800; int h = 300; int cx = 100; int cy = 250; int gw = 600; int gh = 200; int pid = gcs.get(0).pid; long firstTs = getFirstTs(); long duration = (getLastTs() - firstTs); int heapLimit = 32; if (duration <= 0) return false; // Fetch the heap limit from system properties SysPropsPlugin props = (SysPropsPlugin)br.getPlugin("SysPropsPlugin"); if (props != null) { String s = props.getProp("dalvik.vm.heapsize"); if (s != null) { if (s.endsWith("m")) { s = s.substring(0, s.length() - 1); } try { heapLimit = Integer.parseInt(s); } catch (NumberFormatException nfe) { } } } // Avoid issue when duration is too long long firstGcTs = gcs.get(0).ts; long realDuration = getLastTs() - firstGcTs; if (realDuration * 3 < duration) { // Need to scale it down duration = realDuration; firstTs = firstGcTs; } // Check if external memory tracking is enabled boolean hasExternal = false; for (GCRecord gc : gcs) { if (gc.memExtAlloc >= 0 || gc.memExtSize >= 0) { hasExternal = true; break; } } // Create an empty image BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D)img.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.WHITE); g.fillRect(0, 0, w, h); g.setColor(Color.LIGHT_GRAY); g.drawRect(0, 0, w - 1, h - 1); // Draw the axis int as = 5; g.setColor(Color.BLACK); g.drawLine(cx, cy, cx, cy - gh); g.drawLine(cx, cy, cx + gw, cy); g.drawLine(cx - as, cy - gh + as, cx, cy - gh); g.drawLine(cx + as, cy - gh + as, cx, cy - gh); g.drawLine(cx + gw - as, cy - as, cx + gw, cy); g.drawLine(cx + gw - as, cy + as, cx + gw, cy); // Draw the title FontMetrics fm = g.getFontMetrics(); String procName = ""; ProcessRecord pr = br.getProcessRecord(pid, false, false); if (pr != null) { procName = pr.getName(); } else { procName = Integer.toString(pid); } g.drawString("Memory after GC in process " + procName, 10, 10 + fm.getAscent()); // Draw the duration String dur; if (duration < 5*1000) { dur = String.format("%dms", duration); } else if (duration < 5*60*1000) { dur = String.format("%.1fs", duration / 1000.0f); } else if (duration < 5*60*60*1000) { dur = String.format("%.1fmin", duration / 60000.0f); } else { dur = String.format("%.1fh", duration / 3600000.0f); } dur = "Log length: " + dur; g.drawString(dur, w - 10 - fm.stringWidth(dur), 10 + fm.getAscent()); // Collect the maximum value int max = 0; for (GCRecord gc : gcs) { int total = gc.memExtSize + gc.memFreeSize; if (total > max) { max = total; } } max = max * 110 / 100; // add 10% for better visibility // Draw some guide lines int count = 5; int step = max / count; step = (step + 249) / 250 * 250; Color colGuide = new Color(0xc0c0ff); for (int i = 1; i <= count; i++) { int value = i * step; if (value > max) break; int yv = cy - value * gh / max; g.setColor(colGuide); g.drawLine(cx + 1, yv, cx + gw, yv); g.setColor(Color.BLACK); String s = "" + value + "K"; g.drawString(s, cx - fm.stringWidth(s) - 1, yv); } // Draw the config changes (useful to see the correlation between config changes and memory usage) Color colConfigChange = Color.LIGHT_GRAY; g.setColor(colConfigChange); int ccCnt = 0; for (ConfigChange cc : mConfigChanges) { long ts = cc.ts; if (ts < firstTs) continue; // skip one, this doesn't count int x = cx + (int)((ts - firstTs) * (gw - 1) / (duration)); g.drawLine(x, cy - 1, x, cy - gh); ccCnt++; } // Draw the heap limit line (if visible) int ylimit = (heapLimit*1024) * gh / max; if (ylimit < gh) { int yv = cy - ylimit; g.setColor(Color.BLACK); g.drawLine(cx + 1, yv, cx + gw, yv); g.drawString("" + heapLimit + "MB", cx + gw + 5, yv); } // Plot the values (size) Color colFreeSize = new Color(0xc0c080); Color colTotalSize = new Color(0x8080d7); int lastX = -1, lastYF = -1, lastYT = -1; int r = 3; for (GCRecord gc : gcs) { int yf = cy - gc.memFreeSize * (gh - 1) / max; int x = cx + (int)((gc.ts - getFirstTs()) * (gw - 1) / duration); g.setColor(colFreeSize); if (lastX != -1) { g.drawLine(lastX, lastYF, x, yf); } g.fillArc(x - r, yf - r, 2*r+1, 2*r+1, 0, 360); lastYF = yf; if (hasExternal) { int yt = cy - (gc.memFreeSize + gc.memExtSize) * (gh - 1) / max; g.setColor(colTotalSize); if (lastX != -1) { g.drawLine(lastX, lastYT, x, yt); } g.fillArc(x - r, yt - r, 2*r+1, 2*r+1, 0, 360); lastYT = yt; } lastX = x; } // Plot the values (alloc) Color colFreeAlloc = new Color(0x808000); Color colTotalAlloc = new Color(0x0000c0); lastX = -1; lastYF = -1; lastYT = -1; for (GCRecord gc : gcs) { int yf = cy - gc.memFreeAlloc * (gh - 1) / max; int x = cx + (int)((gc.ts - firstTs) * (gw - 1) / (duration)); g.setColor(colFreeAlloc); if (lastX != -1) { g.drawLine(lastX, lastYF, x, yf); } g.fillArc(x - r, yf - r, 2*r+1, 2*r+1, 0, 360); lastYF = yf; if (hasExternal) { int yt = cy - (gc.memFreeAlloc + gc.memExtAlloc) * (gh - 1) / max; g.setColor(colTotalAlloc); if (lastX != -1) { g.drawLine(lastX, lastYT, x, yt); } g.fillArc(x - r, yt - r, 2*r+1, 2*r+1, 0, 360); lastYT = yt; } lastX = x; } // Plot the values (alloc) Color colTotalAllocO = new Color(0xff4040); if (hasExternal) { lastX = -1; lastYF = -1; lastYT = -1; for (GCRecord gc : gcs) { int yt = cy - (gc.memFreeSize + gc.memExtAlloc) * (gh - 1) / max; int x = cx + (int)((gc.ts - firstTs) * (gw - 1) / (duration)); g.setColor(colTotalAllocO); if (lastX != -1) { g.drawLine(lastX, lastYT, x, yt); } g.fillArc(x - r, yt - r, 2*r+1, 2*r+1, 0, 360); lastX = x; lastYT = yt; } } // Draw the legend int yl = h - 10 - fm.getDescent(); String s = "VM Heap (alloc)"; g.setColor(colFreeAlloc); g.drawString(s, w * 1 / 4 - fm.stringWidth(s)/2, yl); if (hasExternal) { s = "VM Heap + External (alloc)"; g.setColor(colTotalAlloc); g.drawString(s, w * 2 / 4 - fm.stringWidth(s)/2, yl); s = "Mem footprint"; g.setColor(colTotalAllocO); g.drawString(s, w * 3 / 4 - fm.stringWidth(s)/2, yl); } yl -= fm.getHeight(); s = "VM Heap (size)"; g.setColor(colFreeSize); g.drawString(s, w * 1 / 4 - fm.stringWidth(s)/2, yl); if (hasExternal) { s = "VM Heap + External (size)"; g.setColor(colTotalSize); g.drawString(s, w * 2 / 4 - fm.stringWidth(s)/2, yl); } if (ccCnt > 0) { // Draw legend for config changes s = "| Config changes"; g.setColor(colConfigChange); g.drawString(s, w * 3 / 4 - fm.stringWidth(s)/2, yl); } // Save the image String fn = "gc_" + mId + "_" + pid + ".png"; try { ImageIO.write(img, "png", new File(br.getBaseDir() + fn)); } catch (IOException e) { e.printStackTrace(); } // Append a link at the end of the system log ch.add(new Img(fn)); // Also insert a link at the beginning of the per-process log ProcessLog pl = getLogOf(br, pid); pl.add(new Img(fn)); // And also add it to the process record if (pr != null) { new Para(pr) .add("Memory usage from GC " + mId + " logs:") .add(new Img(fn)); } return true; }
private boolean generateGCGraph(BugReportModule br, Chapter ch, GCRecords gcs) { int w = 800; int h = 300; int cx = 100; int cy = 250; int gw = 600; int gh = 200; int pid = gcs.get(0).pid; long firstTs = getFirstTs(); long duration = (getLastTs() - firstTs); int heapLimit = 32; if (duration <= 0) return false; // Fetch the heap limit from system properties SysPropsPlugin props = (SysPropsPlugin)br.getPlugin("SysPropsPlugin"); if (props != null) { String s = props.getProp("dalvik.vm.heapsize"); if (s != null) { if (s.endsWith("m")) { s = s.substring(0, s.length() - 1); } try { heapLimit = Integer.parseInt(s); } catch (NumberFormatException nfe) { } } } // Avoid issue when duration is too long long firstGcTs = gcs.get(0).ts; long realDuration = getLastTs() - firstGcTs; if (realDuration * 3 < duration) { // Need to scale it down duration = realDuration; firstTs = firstGcTs; } // Check if external memory tracking is enabled boolean hasExternal = false; for (GCRecord gc : gcs) { if (gc.memExtAlloc >= 0 || gc.memExtSize >= 0) { hasExternal = true; break; } } // Create an empty image BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D)img.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.WHITE); g.fillRect(0, 0, w, h); g.setColor(Color.LIGHT_GRAY); g.drawRect(0, 0, w - 1, h - 1); // Draw the axis int as = 5; g.setColor(Color.BLACK); g.drawLine(cx, cy, cx, cy - gh); g.drawLine(cx, cy, cx + gw, cy); g.drawLine(cx - as, cy - gh + as, cx, cy - gh); g.drawLine(cx + as, cy - gh + as, cx, cy - gh); g.drawLine(cx + gw - as, cy - as, cx + gw, cy); g.drawLine(cx + gw - as, cy + as, cx + gw, cy); // Draw the title FontMetrics fm = g.getFontMetrics(); String procName = ""; ProcessRecord pr = br.getProcessRecord(pid, false, false); if (pr != null) { procName = pr.getName(); } else { procName = Integer.toString(pid); } g.drawString("Memory after GC in process " + procName, 10, 10 + fm.getAscent()); // Draw the duration String dur; if (duration < 5*1000) { dur = String.format("%dms", duration); } else if (duration < 5*60*1000) { dur = String.format("%.1fs", duration / 1000.0f); } else if (duration < 5*60*60*1000) { dur = String.format("%.1fmin", duration / 60000.0f); } else { dur = String.format("%.1fh", duration / 3600000.0f); } dur = "Log length: " + dur; g.drawString(dur, w - 10 - fm.stringWidth(dur), 10 + fm.getAscent()); // Collect the maximum value int max = 0; for (GCRecord gc : gcs) { int total = gc.memExtSize + gc.memFreeSize; if (total > max) { max = total; } } max = max * 110 / 100; // add 10% for better visibility // Draw some guide lines int count = 5; int step = max / count; step = (step + 249) / 250 * 250; Color colGuide = new Color(0xc0c0ff); for (int i = 1; i <= count; i++) { int value = i * step; if (value > max) break; int yv = cy - value * gh / max; g.setColor(colGuide); g.drawLine(cx + 1, yv, cx + gw, yv); g.setColor(Color.BLACK); String s = "" + value + "K"; g.drawString(s, cx - fm.stringWidth(s) - 1, yv); } // Draw the config changes (useful to see the correlation between config changes and memory usage) Color colConfigChange = Color.LIGHT_GRAY; g.setColor(colConfigChange); int ccCnt = 0; for (ConfigChange cc : mConfigChanges) { long ts = cc.ts; if (ts < firstTs) continue; // skip one, this doesn't count int x = cx + (int)((ts - firstTs) * (gw - 1) / (duration)); g.drawLine(x, cy - 1, x, cy - gh); ccCnt++; } // Draw the heap limit line (if visible) int ylimit = (heapLimit*1024) * gh / max; if (ylimit < gh) { int yv = cy - ylimit; g.setColor(Color.BLACK); g.drawLine(cx + 1, yv, cx + gw, yv); g.drawString("" + heapLimit + "MB", cx + gw + 5, yv); } // Plot the values (size) Color colFreeSize = new Color(0xc0c080); Color colTotalSize = new Color(0x8080d7); int lastX = -1, lastYF = -1, lastYT = -1; int r = 3; for (GCRecord gc : gcs) { int yf = cy - gc.memFreeSize * (gh - 1) / max; int x = cx + (int)((gc.ts - getFirstTs()) * (gw - 1) / duration); g.setColor(colFreeSize); if (lastX != -1) { g.drawLine(lastX, lastYF, x, yf); } g.fillArc(x - r, yf - r, 2*r+1, 2*r+1, 0, 360); lastYF = yf; if (hasExternal) { int yt = cy - (gc.memFreeSize + gc.memExtSize) * (gh - 1) / max; g.setColor(colTotalSize); if (lastX != -1) { g.drawLine(lastX, lastYT, x, yt); } g.fillArc(x - r, yt - r, 2*r+1, 2*r+1, 0, 360); lastYT = yt; } lastX = x; } // Plot the values (alloc) Color colFreeAlloc = new Color(0x808000); Color colTotalAlloc = new Color(0x0000c0); lastX = -1; lastYF = -1; lastYT = -1; for (GCRecord gc : gcs) { int yf = cy - gc.memFreeAlloc * (gh - 1) / max; int x = cx + (int)((gc.ts - firstTs) * (gw - 1) / (duration)); g.setColor(colFreeAlloc); if (lastX != -1) { g.drawLine(lastX, lastYF, x, yf); } g.fillArc(x - r, yf - r, 2*r+1, 2*r+1, 0, 360); lastYF = yf; if (hasExternal) { int yt = cy - (gc.memFreeAlloc + gc.memExtAlloc) * (gh - 1) / max; g.setColor(colTotalAlloc); if (lastX != -1) { g.drawLine(lastX, lastYT, x, yt); } g.fillArc(x - r, yt - r, 2*r+1, 2*r+1, 0, 360); lastYT = yt; } lastX = x; } // Plot the values (alloc) Color colTotalAllocO = new Color(0xff4040); if (hasExternal) { lastX = -1; lastYF = -1; lastYT = -1; for (GCRecord gc : gcs) { int yt = cy - (gc.memFreeSize + gc.memExtAlloc) * (gh - 1) / max; int x = cx + (int)((gc.ts - firstTs) * (gw - 1) / (duration)); g.setColor(colTotalAllocO); if (lastX != -1) { g.drawLine(lastX, lastYT, x, yt); } g.fillArc(x - r, yt - r, 2*r+1, 2*r+1, 0, 360); lastX = x; lastYT = yt; } } // Draw the legend int yl = h - 10 - fm.getDescent(); String s = "VM Heap (alloc)"; g.setColor(colFreeAlloc); g.drawString(s, w * 1 / 4 - fm.stringWidth(s)/2, yl); if (hasExternal) { s = "VM Heap + External (alloc)"; g.setColor(colTotalAlloc); g.drawString(s, w * 2 / 4 - fm.stringWidth(s)/2, yl); s = "Mem footprint"; g.setColor(colTotalAllocO); g.drawString(s, w * 3 / 4 - fm.stringWidth(s)/2, yl); } yl -= fm.getHeight(); s = "VM Heap (size)"; g.setColor(colFreeSize); g.drawString(s, w * 1 / 4 - fm.stringWidth(s)/2, yl); if (hasExternal) { s = "VM Heap + External (size)"; g.setColor(colTotalSize); g.drawString(s, w * 2 / 4 - fm.stringWidth(s)/2, yl); } if (ccCnt > 0) { // Draw legend for config changes s = "| Config changes"; g.setColor(colConfigChange); g.drawString(s, w * 3 / 4 - fm.stringWidth(s)/2, yl); } // Save the image String fn = "gc_" + mId + "_" + pid + ".png"; try { ImageIO.write(img, "png", new File(br.getBaseDir() + fn)); } catch (IOException e) { e.printStackTrace(); } // Append a link at the end of the system log ch.add(new Img(fn)); // Also insert a link at the beginning of the per-process log ProcessLog pl = getLogOf(br, pid); pl.add(new Img(fn)); // And also add it to the process record if (pr != null) { new Para(pr).add("Memory usage from GC " + mId + " logs:"); pr.add(new Img(fn)); } return true; }
diff --git a/luaj-vm/src/core/org/luaj/vm/LThread.java b/luaj-vm/src/core/org/luaj/vm/LThread.java index 4b56cbb..2b3ddae 100644 --- a/luaj-vm/src/core/org/luaj/vm/LThread.java +++ b/luaj-vm/src/core/org/luaj/vm/LThread.java @@ -1,168 +1,169 @@ /******************************************************************************* * Copyright (c) 2007 LuaJ. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ package org.luaj.vm; /** * Implementation of lua coroutines using Java Threads */ public class LThread extends LValue implements Runnable { private static final int STATUS_SUSPENDED = 0; private static final int STATUS_RUNNING = 1; private static final int STATUS_NORMAL = 2; private static final int STATUS_DEAD = 3; private static final String[] NAMES = { "suspended", "running", "normal", "dead" }; private int status = STATUS_SUSPENDED; LuaState threadVm; Thread thread; static LThread running; public LThread(LFunction c, LTable env) { threadVm = new LuaState(env); threadVm.pushlvalue(c); } public int luaGetType() { return Lua.LUA_TTHREAD; } public String toJavaString() { return "thread: "+hashCode(); } /** Set the environment if a thread, or closure, and return 1, otherwise return 0 */ public boolean luaSetEnv(LTable t) { threadVm._G = t; return true; } public String getStatus() { return NAMES[status]; } public static LThread getRunning() { return running; } public void run() { synchronized ( this ) { try { threadVm.execute(); } finally { status = STATUS_DEAD; this.notify(); } } } public boolean yield() { synchronized ( this ) { if ( status != STATUS_RUNNING ) threadVm.error(this+" not running"); status = STATUS_SUSPENDED; this.notify(); try { this.wait(); status = STATUS_RUNNING; } catch ( InterruptedException e ) { status = STATUS_DEAD; threadVm.error(this+" "+e); } return false; } } /** This needs to leave any values returned by yield in the coroutine * on the calling vm stack * @param vm * @param nargs */ public void resumeFrom(LuaState vm, int nargs) { synchronized ( this ) { if ( status == STATUS_DEAD ) { vm.resettop(); vm.pushboolean(false); vm.pushstring("cannot resume dead coroutine"); return; } // set prior thread to normal status while we are running LThread prior = running; try { // set our status to running if ( prior != null ) prior.status = STATUS_NORMAL; running = this; status = STATUS_RUNNING; // copy args in if ( thread == null ) { vm.xmove(threadVm, nargs); threadVm.prepStackCall(); thread = new Thread(this); thread.start(); } else { threadVm.resettop(); vm.xmove(threadVm, nargs); } // run this vm until it yields this.notify(); this.wait(); // copy return values from yielding stack state vm.resettop(); - vm.pushboolean(true); if ( threadVm.cc >= 0 ) { + vm.pushboolean(status != STATUS_DEAD); threadVm.xmove(vm, threadVm.gettop() - 1); } else { + vm.pushboolean(true); threadVm.base = 0; threadVm.xmove(vm, threadVm.gettop()); } } catch ( Throwable t ) { status = STATUS_DEAD; vm.resettop(); vm.pushboolean(false); vm.pushstring("thread: "+t); this.notify(); } finally { // previous thread is now running again running = prior; } } } }
false
true
public void resumeFrom(LuaState vm, int nargs) { synchronized ( this ) { if ( status == STATUS_DEAD ) { vm.resettop(); vm.pushboolean(false); vm.pushstring("cannot resume dead coroutine"); return; } // set prior thread to normal status while we are running LThread prior = running; try { // set our status to running if ( prior != null ) prior.status = STATUS_NORMAL; running = this; status = STATUS_RUNNING; // copy args in if ( thread == null ) { vm.xmove(threadVm, nargs); threadVm.prepStackCall(); thread = new Thread(this); thread.start(); } else { threadVm.resettop(); vm.xmove(threadVm, nargs); } // run this vm until it yields this.notify(); this.wait(); // copy return values from yielding stack state vm.resettop(); vm.pushboolean(true); if ( threadVm.cc >= 0 ) { threadVm.xmove(vm, threadVm.gettop() - 1); } else { threadVm.base = 0; threadVm.xmove(vm, threadVm.gettop()); } } catch ( Throwable t ) { status = STATUS_DEAD; vm.resettop(); vm.pushboolean(false); vm.pushstring("thread: "+t); this.notify(); } finally { // previous thread is now running again running = prior; } } }
public void resumeFrom(LuaState vm, int nargs) { synchronized ( this ) { if ( status == STATUS_DEAD ) { vm.resettop(); vm.pushboolean(false); vm.pushstring("cannot resume dead coroutine"); return; } // set prior thread to normal status while we are running LThread prior = running; try { // set our status to running if ( prior != null ) prior.status = STATUS_NORMAL; running = this; status = STATUS_RUNNING; // copy args in if ( thread == null ) { vm.xmove(threadVm, nargs); threadVm.prepStackCall(); thread = new Thread(this); thread.start(); } else { threadVm.resettop(); vm.xmove(threadVm, nargs); } // run this vm until it yields this.notify(); this.wait(); // copy return values from yielding stack state vm.resettop(); if ( threadVm.cc >= 0 ) { vm.pushboolean(status != STATUS_DEAD); threadVm.xmove(vm, threadVm.gettop() - 1); } else { vm.pushboolean(true); threadVm.base = 0; threadVm.xmove(vm, threadVm.gettop()); } } catch ( Throwable t ) { status = STATUS_DEAD; vm.resettop(); vm.pushboolean(false); vm.pushstring("thread: "+t); this.notify(); } finally { // previous thread is now running again running = prior; } } }
diff --git a/dropwizard-extra-core/src/main/java/com/datasift/dropwizard/bundles/GraphiteReportingBundle.java b/dropwizard-extra-core/src/main/java/com/datasift/dropwizard/bundles/GraphiteReportingBundle.java index 669d41b..392f06a 100644 --- a/dropwizard-extra-core/src/main/java/com/datasift/dropwizard/bundles/GraphiteReportingBundle.java +++ b/dropwizard-extra-core/src/main/java/com/datasift/dropwizard/bundles/GraphiteReportingBundle.java @@ -1,56 +1,56 @@ package com.datasift.dropwizard.bundles; import com.datasift.dropwizard.config.GraphiteReportingConfiguration; import com.datasift.dropwizard.health.GraphiteHealthCheck; import com.yammer.dropwizard.ConfiguredBundle; import com.yammer.dropwizard.config.Environment; import com.yammer.dropwizard.logging.Log; import com.yammer.metrics.reporting.GraphiteReporter; import com.yammer.dropwizard.config.Configuration; import com.yammer.dropwizard.Service; import java.util.concurrent.TimeUnit; /** * A {@link ConfiguredBundle} for reporting metrics to a remote Graphite server. * * Includes a HealthCheck to the Graphite instance. * * To use this {@link ConfiguredBundle}, your {@link Configuration} must * implement {@link GraphiteReportingConfiguration}. */ public class GraphiteReportingBundle implements ConfiguredBundle<GraphiteReportingConfiguration> { private final Log log = Log.forClass(this.getClass()); /** * Initializes the Graphite reporter, if enabled. * * @param conf the {@link GraphiteReportingConfiguration} to configure the * {@link GraphiteReporter} with * @param env the {@link Service} environment */ public void initialize(final GraphiteReportingConfiguration conf, final Environment env) { if (conf.getGraphite().getEnabled()) { - log.info("Reporting metrics to Graphite at {}:{}, every {} seconds", + log.info("Reporting metrics to Graphite at {}:{}, every {}", conf.getGraphite().getHost(), conf.getGraphite().getPort(), conf.getGraphite().getFrequency()); GraphiteReporter.enable( conf.getGraphite().getFrequency().toNanoseconds(), TimeUnit.NANOSECONDS, conf.getGraphite().getHost(), conf.getGraphite().getPort(), conf.getGraphite().getPrefix() ); env.addHealthCheck(new GraphiteHealthCheck( conf.getGraphite().getHost(), conf.getGraphite().getPort(), "graphite")); } } }
true
true
public void initialize(final GraphiteReportingConfiguration conf, final Environment env) { if (conf.getGraphite().getEnabled()) { log.info("Reporting metrics to Graphite at {}:{}, every {} seconds", conf.getGraphite().getHost(), conf.getGraphite().getPort(), conf.getGraphite().getFrequency()); GraphiteReporter.enable( conf.getGraphite().getFrequency().toNanoseconds(), TimeUnit.NANOSECONDS, conf.getGraphite().getHost(), conf.getGraphite().getPort(), conf.getGraphite().getPrefix() ); env.addHealthCheck(new GraphiteHealthCheck( conf.getGraphite().getHost(), conf.getGraphite().getPort(), "graphite")); } }
public void initialize(final GraphiteReportingConfiguration conf, final Environment env) { if (conf.getGraphite().getEnabled()) { log.info("Reporting metrics to Graphite at {}:{}, every {}", conf.getGraphite().getHost(), conf.getGraphite().getPort(), conf.getGraphite().getFrequency()); GraphiteReporter.enable( conf.getGraphite().getFrequency().toNanoseconds(), TimeUnit.NANOSECONDS, conf.getGraphite().getHost(), conf.getGraphite().getPort(), conf.getGraphite().getPrefix() ); env.addHealthCheck(new GraphiteHealthCheck( conf.getGraphite().getHost(), conf.getGraphite().getPort(), "graphite")); } }
diff --git a/E-Adventure/src/es/eucm/eadventure/engine/core/control/functionaldata/FunctionalConditions.java b/E-Adventure/src/es/eucm/eadventure/engine/core/control/functionaldata/FunctionalConditions.java index f554f12f..a334917d 100644 --- a/E-Adventure/src/es/eucm/eadventure/engine/core/control/functionaldata/FunctionalConditions.java +++ b/E-Adventure/src/es/eucm/eadventure/engine/core/control/functionaldata/FunctionalConditions.java @@ -1,189 +1,187 @@ /******************************************************************************* * eAdventure (formerly <e-Adventure> and <e-Game>) is a research project of the e-UCM * research group. * * Copyright 2005-2012 e-UCM research group. * * e-UCM is a research group of the Department of Software Engineering * and Artificial Intelligence at the Complutense University of Madrid * (School of Computer Science). * * C Profesor Jose Garcia Santesmases sn, * 28040 Madrid (Madrid), Spain. * * For more info please visit: <http://e-adventure.e-ucm.es> or * <http://www.e-ucm.es> * * **************************************************************************** * This file is part of eAdventure, version 1.5. * * You can access a list of all the contributors to eAdventure at: * http://e-adventure.e-ucm.es/contributors * * **************************************************************************** * eAdventure 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. * * eAdventure 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 Adventure. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package es.eucm.eadventure.engine.core.control.functionaldata; import es.eucm.eadventure.common.data.chapter.conditions.Condition; import es.eucm.eadventure.common.data.chapter.conditions.Conditions; import es.eucm.eadventure.common.data.chapter.conditions.FlagCondition; import es.eucm.eadventure.common.data.chapter.conditions.GlobalState; import es.eucm.eadventure.common.data.chapter.conditions.GlobalStateCondition; import es.eucm.eadventure.common.data.chapter.conditions.VarCondition; import es.eucm.eadventure.engine.core.control.FlagSummary; import es.eucm.eadventure.engine.core.control.Game; import es.eucm.eadventure.engine.core.control.VarSummary; public class FunctionalConditions { private Conditions conditions; public FunctionalConditions( Conditions conditions ) { this.conditions = conditions; } /** * Returns whether all the conditions are ok * * @return true if all the conditions are ok, false otherwise */ public boolean allConditionsOk( ) { boolean conditionsOK = true; conditionsOK = evaluateSimpleConditionsWithAND( ); for( int i = 0; i < conditions.getEitherConditionsBlockCount( ); i++ ) { Conditions eitherCondition = conditions.getEitherBlock( i ); if( conditionsOK ) conditionsOK = new FunctionalConditions( eitherCondition ).evaluateSimpleConditionsWithOR( ); } return conditionsOK; } /** * Returns whether all the conditions are satisfied * * @return true if all the conditions are satisfied, false otherwise */ private boolean evaluateSimpleConditionsWithAND( ) { boolean evaluation = true; FlagSummary flags = Game.getInstance( ).getFlags( ); VarSummary vars = Game.getInstance( ).getVars( ); for( Condition condition : conditions.getSimpleConditions( ) ) { if( evaluation ) { if( condition.getType( ) == Condition.FLAG_CONDITION ) { FlagCondition flagCondition = (FlagCondition) condition; evaluation = flagCondition.isActiveState( ) == flags.isActiveFlag( condition.getId( ) ); } else if( condition.getType( ) == Condition.VAR_CONDITION ) { VarCondition varCondition = (VarCondition) condition; int actualValue = vars.getValue( varCondition.getId( ) ); int state = varCondition.getState( ); int value = varCondition.getValue( ); evaluation = evaluateVarCondition( state, value, actualValue ); } else if( condition.getType( ) == Condition.GLOBAL_STATE_CONDITION ) { String globalStateId = condition.getId( ); GlobalStateCondition gsCondition = (GlobalStateCondition) condition; GlobalState gs = Game.getInstance( ).getCurrentChapterData( ).getGlobalState( globalStateId ); - // the editor doesn't allow to add a global state reference with the same ID in a global state, DOUBLE CHECKED here - if (!gs.getId( ).equals( globalStateId )) - evaluation = (gsCondition.getState( ) == GlobalStateCondition.GS_NOT_SATISFIED) ^ new FunctionalConditions( gs ).allConditionsOk( ); + evaluation = (gsCondition.getState( ) == GlobalStateCondition.GS_NOT_SATISFIED) ^ new FunctionalConditions( gs ).allConditionsOk( ); } } } return evaluation; } /** * Evaluates a var condition according to the state (function to use for * evaluation), value of comparison, and the actual value of the var * * @param state >, * >=, =, !=, < or <= * @param value * The value to compare with * @param actualValue * The actual value assigned to the var so far * @return True if condition is true; false otherwise */ private boolean evaluateVarCondition( int state, int value, int actualValue ) { if( state == VarCondition.VAR_EQUALS ) { return actualValue == value; } else if( state == VarCondition.VAR_NOT_EQUALS ) { return actualValue != value; } else if( state == VarCondition.VAR_GREATER_EQUALS_THAN ) { return actualValue >= value; } else if( state == VarCondition.VAR_GREATER_THAN ) { return actualValue > value; } else if( state == VarCondition.VAR_LESS_EQUALS_THAN ) { return actualValue <= value; } else if( state == VarCondition.VAR_LESS_THAN ) { return actualValue < value; } else return false; } /** * Returns whether at least one condition is satisfied * * @return true if at least one condition is satisfied, false otherwise */ private boolean evaluateSimpleConditionsWithOR( ) { boolean evaluation = false; FlagSummary flags = Game.getInstance( ).getFlags( ); VarSummary vars = Game.getInstance( ).getVars( ); for( Condition condition : conditions.getSimpleConditions( ) ) if( !evaluation ) { if( condition.getType( ) == Condition.FLAG_CONDITION ) { FlagCondition flagCondition = (FlagCondition) condition; evaluation = flagCondition.isActiveState( ) == flags.isActiveFlag( condition.getId( ) ); } else if( condition.getType( ) == Condition.VAR_CONDITION ) { VarCondition varCondition = (VarCondition) condition; int actualValue = vars.getValue( varCondition.getId( ) ); int state = varCondition.getState( ); int value = varCondition.getValue( ); evaluation = evaluateVarCondition( state, value, actualValue ); } else if( condition.getType( ) == Condition.GLOBAL_STATE_CONDITION ) { String globalStateId = condition.getId( ); GlobalStateCondition gsCondition = (GlobalStateCondition) condition; GlobalState gs = Game.getInstance( ).getCurrentChapterData( ).getGlobalState( globalStateId ); evaluation = (gsCondition.getState( ) == GlobalStateCondition.GS_NOT_SATISFIED) ^ new FunctionalConditions( gs ).allConditionsOk( ); } } return evaluation; } }
true
true
private boolean evaluateSimpleConditionsWithAND( ) { boolean evaluation = true; FlagSummary flags = Game.getInstance( ).getFlags( ); VarSummary vars = Game.getInstance( ).getVars( ); for( Condition condition : conditions.getSimpleConditions( ) ) { if( evaluation ) { if( condition.getType( ) == Condition.FLAG_CONDITION ) { FlagCondition flagCondition = (FlagCondition) condition; evaluation = flagCondition.isActiveState( ) == flags.isActiveFlag( condition.getId( ) ); } else if( condition.getType( ) == Condition.VAR_CONDITION ) { VarCondition varCondition = (VarCondition) condition; int actualValue = vars.getValue( varCondition.getId( ) ); int state = varCondition.getState( ); int value = varCondition.getValue( ); evaluation = evaluateVarCondition( state, value, actualValue ); } else if( condition.getType( ) == Condition.GLOBAL_STATE_CONDITION ) { String globalStateId = condition.getId( ); GlobalStateCondition gsCondition = (GlobalStateCondition) condition; GlobalState gs = Game.getInstance( ).getCurrentChapterData( ).getGlobalState( globalStateId ); // the editor doesn't allow to add a global state reference with the same ID in a global state, DOUBLE CHECKED here if (!gs.getId( ).equals( globalStateId )) evaluation = (gsCondition.getState( ) == GlobalStateCondition.GS_NOT_SATISFIED) ^ new FunctionalConditions( gs ).allConditionsOk( ); } } } return evaluation; }
private boolean evaluateSimpleConditionsWithAND( ) { boolean evaluation = true; FlagSummary flags = Game.getInstance( ).getFlags( ); VarSummary vars = Game.getInstance( ).getVars( ); for( Condition condition : conditions.getSimpleConditions( ) ) { if( evaluation ) { if( condition.getType( ) == Condition.FLAG_CONDITION ) { FlagCondition flagCondition = (FlagCondition) condition; evaluation = flagCondition.isActiveState( ) == flags.isActiveFlag( condition.getId( ) ); } else if( condition.getType( ) == Condition.VAR_CONDITION ) { VarCondition varCondition = (VarCondition) condition; int actualValue = vars.getValue( varCondition.getId( ) ); int state = varCondition.getState( ); int value = varCondition.getValue( ); evaluation = evaluateVarCondition( state, value, actualValue ); } else if( condition.getType( ) == Condition.GLOBAL_STATE_CONDITION ) { String globalStateId = condition.getId( ); GlobalStateCondition gsCondition = (GlobalStateCondition) condition; GlobalState gs = Game.getInstance( ).getCurrentChapterData( ).getGlobalState( globalStateId ); evaluation = (gsCondition.getState( ) == GlobalStateCondition.GS_NOT_SATISFIED) ^ new FunctionalConditions( gs ).allConditionsOk( ); } } } return evaluation; }
diff --git a/ps3mediaserver/net/pms/encoders/MPlayerAudio.java b/ps3mediaserver/net/pms/encoders/MPlayerAudio.java index 73b93032..208ca701 100644 --- a/ps3mediaserver/net/pms/encoders/MPlayerAudio.java +++ b/ps3mediaserver/net/pms/encoders/MPlayerAudio.java @@ -1,191 +1,192 @@ /* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2008 A.Brochard * * 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; version 2 * of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.pms.encoders; import java.awt.Font; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.IOException; import java.util.Arrays; import javax.swing.JCheckBox; import javax.swing.JComponent; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.factories.Borders; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import net.pms.PMS; import net.pms.configuration.PmsConfiguration; import net.pms.dlna.DLNAMediaInfo; import net.pms.dlna.DLNAResource; import net.pms.formats.Format; import net.pms.io.OutputParams; import net.pms.io.PipeProcess; import net.pms.io.ProcessWrapper; import net.pms.io.ProcessWrapperImpl; import net.pms.network.HTTPResource; public class MPlayerAudio extends Player { public static final String ID = "mplayeraudio"; private final PmsConfiguration configuration; public MPlayerAudio(PmsConfiguration configuration) { this.configuration = configuration; } @Override public String id() { return ID; } @Override public int purpose() { return AUDIO_SIMPLEFILE_PLAYER; } @Override public String[] args() { return new String[]{}; } @Override public String executable() { return PMS.getConfiguration().getMplayerPath(); } @Override public ProcessWrapper launchTranscode( String fileName, DLNAResource dlna, DLNAMediaInfo media, OutputParams params) throws IOException { if (!(this instanceof MPlayerWebAudio) && !(this instanceof MPlayerWebVideoDump)) { params.waitbeforestart = 2000; } params.manageFastStart(); if (params.mediaRenderer.isTranscodeToMP3()) { FFMpegAudio audio = new FFMpegAudio(configuration); return audio.launchTranscode(fileName, dlna, media, params); } params.maxBufferSize = PMS.getConfiguration().getMaxAudioBuffer(); PipeProcess audioP = new PipeProcess("mplayer_aud" + System.currentTimeMillis()); String mPlayerdefaultAudioArgs[] = new String[]{PMS.getConfiguration().getMplayerPath(), fileName, "-prefer-ipv4", "-nocache", "-af", "channels=2", "-srate", "48000", "-vo", "null", "-ao", "pcm:nowaveheader:fast:file=" + audioP.getInputPipe(), "-quiet", "-format", "s16be"}; if (params.mediaRenderer.isTranscodeToWAV()) { mPlayerdefaultAudioArgs[11] = "pcm:waveheader:fast:file=" + audioP.getInputPipe(); - mPlayerdefaultAudioArgs[11] = "s16le"; + mPlayerdefaultAudioArgs[13] = "-quiet"; + mPlayerdefaultAudioArgs[14] = "-quiet"; } if (params.mediaRenderer.isTranscodeAudioTo441()) { mPlayerdefaultAudioArgs[7] = "44100"; } if (!configuration.isAudioResample()) { mPlayerdefaultAudioArgs[6] = "-quiet"; mPlayerdefaultAudioArgs[7] = "-quiet"; } params.input_pipes[0] = audioP; if (params.timeseek > 0 || params.timeend > 0) { mPlayerdefaultAudioArgs = Arrays.copyOf(mPlayerdefaultAudioArgs, mPlayerdefaultAudioArgs.length + 4); mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 4] = "-ss"; mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 3] = "" + params.timeseek; if (params.timeend > 0) { mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 2] = "-endpos"; mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 1] = "" + params.timeend; } else { mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 2] = "-quiet"; mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 1] = "-quiet"; } } ProcessWrapper mkfifo_process = audioP.getPipeProcess(); mPlayerdefaultAudioArgs = finalizeTranscoderArgs( this, fileName, dlna, media, params, mPlayerdefaultAudioArgs); ProcessWrapperImpl pw = new ProcessWrapperImpl(mPlayerdefaultAudioArgs, params); pw.attachProcess(mkfifo_process); mkfifo_process.runInNewThread(); try { Thread.sleep(100); } catch (InterruptedException e) { } audioP.deleteLater(); pw.runInNewThread(); try { Thread.sleep(100); } catch (InterruptedException e) { } return pw; } @Override public String mimeType() { return HTTPResource.AUDIO_TRANSCODE; } @Override public String name() { return "MPlayer Audio"; } @Override public int type() { return Format.AUDIO; } JCheckBox noresample; @Override public JComponent config() { FormLayout layout = new FormLayout( "left:pref, 0:grow", "p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, 0:grow"); PanelBuilder builder = new PanelBuilder(layout); builder.setBorder(Borders.EMPTY_BORDER); builder.setOpaque(false); CellConstraints cc = new CellConstraints(); JComponent cmp = builder.addSeparator("Audio settings", cc.xyw(2, 1, 1)); cmp = (JComponent) cmp.getComponent(0); cmp.setFont(cmp.getFont().deriveFont(Font.BOLD)); noresample = new JCheckBox("Automatic audio resampling to 44.1 or 48 kHz"); noresample.setContentAreaFilled(false); noresample.setSelected(configuration.isAudioResample()); noresample.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { configuration.setAudioResample(e.getStateChange() == ItemEvent.SELECTED); } }); builder.add(noresample, cc.xy(2, 3)); return builder.getPanel(); } }
true
true
public ProcessWrapper launchTranscode( String fileName, DLNAResource dlna, DLNAMediaInfo media, OutputParams params) throws IOException { if (!(this instanceof MPlayerWebAudio) && !(this instanceof MPlayerWebVideoDump)) { params.waitbeforestart = 2000; } params.manageFastStart(); if (params.mediaRenderer.isTranscodeToMP3()) { FFMpegAudio audio = new FFMpegAudio(configuration); return audio.launchTranscode(fileName, dlna, media, params); } params.maxBufferSize = PMS.getConfiguration().getMaxAudioBuffer(); PipeProcess audioP = new PipeProcess("mplayer_aud" + System.currentTimeMillis()); String mPlayerdefaultAudioArgs[] = new String[]{PMS.getConfiguration().getMplayerPath(), fileName, "-prefer-ipv4", "-nocache", "-af", "channels=2", "-srate", "48000", "-vo", "null", "-ao", "pcm:nowaveheader:fast:file=" + audioP.getInputPipe(), "-quiet", "-format", "s16be"}; if (params.mediaRenderer.isTranscodeToWAV()) { mPlayerdefaultAudioArgs[11] = "pcm:waveheader:fast:file=" + audioP.getInputPipe(); mPlayerdefaultAudioArgs[11] = "s16le"; } if (params.mediaRenderer.isTranscodeAudioTo441()) { mPlayerdefaultAudioArgs[7] = "44100"; } if (!configuration.isAudioResample()) { mPlayerdefaultAudioArgs[6] = "-quiet"; mPlayerdefaultAudioArgs[7] = "-quiet"; } params.input_pipes[0] = audioP; if (params.timeseek > 0 || params.timeend > 0) { mPlayerdefaultAudioArgs = Arrays.copyOf(mPlayerdefaultAudioArgs, mPlayerdefaultAudioArgs.length + 4); mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 4] = "-ss"; mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 3] = "" + params.timeseek; if (params.timeend > 0) { mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 2] = "-endpos"; mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 1] = "" + params.timeend; } else { mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 2] = "-quiet"; mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 1] = "-quiet"; } } ProcessWrapper mkfifo_process = audioP.getPipeProcess(); mPlayerdefaultAudioArgs = finalizeTranscoderArgs( this, fileName, dlna, media, params, mPlayerdefaultAudioArgs); ProcessWrapperImpl pw = new ProcessWrapperImpl(mPlayerdefaultAudioArgs, params); pw.attachProcess(mkfifo_process); mkfifo_process.runInNewThread(); try { Thread.sleep(100); } catch (InterruptedException e) { } audioP.deleteLater(); pw.runInNewThread(); try { Thread.sleep(100); } catch (InterruptedException e) { } return pw; }
public ProcessWrapper launchTranscode( String fileName, DLNAResource dlna, DLNAMediaInfo media, OutputParams params) throws IOException { if (!(this instanceof MPlayerWebAudio) && !(this instanceof MPlayerWebVideoDump)) { params.waitbeforestart = 2000; } params.manageFastStart(); if (params.mediaRenderer.isTranscodeToMP3()) { FFMpegAudio audio = new FFMpegAudio(configuration); return audio.launchTranscode(fileName, dlna, media, params); } params.maxBufferSize = PMS.getConfiguration().getMaxAudioBuffer(); PipeProcess audioP = new PipeProcess("mplayer_aud" + System.currentTimeMillis()); String mPlayerdefaultAudioArgs[] = new String[]{PMS.getConfiguration().getMplayerPath(), fileName, "-prefer-ipv4", "-nocache", "-af", "channels=2", "-srate", "48000", "-vo", "null", "-ao", "pcm:nowaveheader:fast:file=" + audioP.getInputPipe(), "-quiet", "-format", "s16be"}; if (params.mediaRenderer.isTranscodeToWAV()) { mPlayerdefaultAudioArgs[11] = "pcm:waveheader:fast:file=" + audioP.getInputPipe(); mPlayerdefaultAudioArgs[13] = "-quiet"; mPlayerdefaultAudioArgs[14] = "-quiet"; } if (params.mediaRenderer.isTranscodeAudioTo441()) { mPlayerdefaultAudioArgs[7] = "44100"; } if (!configuration.isAudioResample()) { mPlayerdefaultAudioArgs[6] = "-quiet"; mPlayerdefaultAudioArgs[7] = "-quiet"; } params.input_pipes[0] = audioP; if (params.timeseek > 0 || params.timeend > 0) { mPlayerdefaultAudioArgs = Arrays.copyOf(mPlayerdefaultAudioArgs, mPlayerdefaultAudioArgs.length + 4); mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 4] = "-ss"; mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 3] = "" + params.timeseek; if (params.timeend > 0) { mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 2] = "-endpos"; mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 1] = "" + params.timeend; } else { mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 2] = "-quiet"; mPlayerdefaultAudioArgs[mPlayerdefaultAudioArgs.length - 1] = "-quiet"; } } ProcessWrapper mkfifo_process = audioP.getPipeProcess(); mPlayerdefaultAudioArgs = finalizeTranscoderArgs( this, fileName, dlna, media, params, mPlayerdefaultAudioArgs); ProcessWrapperImpl pw = new ProcessWrapperImpl(mPlayerdefaultAudioArgs, params); pw.attachProcess(mkfifo_process); mkfifo_process.runInNewThread(); try { Thread.sleep(100); } catch (InterruptedException e) { } audioP.deleteLater(); pw.runInNewThread(); try { Thread.sleep(100); } catch (InterruptedException e) { } return pw; }
diff --git a/src/main/java/grisu/gricli/command/LocalLoginCommand.java b/src/main/java/grisu/gricli/command/LocalLoginCommand.java index b6a4721..c95227c 100644 --- a/src/main/java/grisu/gricli/command/LocalLoginCommand.java +++ b/src/main/java/grisu/gricli/command/LocalLoginCommand.java @@ -1,37 +1,38 @@ package grisu.gricli.command; import grisu.control.ServiceInterface; import grisu.frontend.control.login.LoginException; import grisu.frontend.control.login.LoginManager; import grisu.gricli.GricliRuntimeException; import grisu.gricli.completors.BackendCompletor; import grisu.gricli.environment.GricliEnvironment; public class LocalLoginCommand implements GricliCommand { public final static String GRICLI_LOGIN_SCRIPT_ENV_NAME = "GRICLI_LOGIN_SCRIPT"; private String siUrl; @SyntaxDescription(command = { "login" }, arguments = { "backend" }) @AutoComplete(completors = { BackendCompletor.class }) public LocalLoginCommand(String siUrl) { this.siUrl = siUrl; } public GricliEnvironment execute(GricliEnvironment env) throws GricliRuntimeException { try { if (siUrl == null) { siUrl = env.getServiceInterfaceUrl(); } - final ServiceInterface serviceInterface = LoginManager.login(siUrl); + final ServiceInterface serviceInterface = LoginManager + .loginCommandline(siUrl); return InteractiveLoginCommand.login(env, serviceInterface); } catch (final LoginException ex) { throw new GricliRuntimeException(ex); } } }
true
true
public GricliEnvironment execute(GricliEnvironment env) throws GricliRuntimeException { try { if (siUrl == null) { siUrl = env.getServiceInterfaceUrl(); } final ServiceInterface serviceInterface = LoginManager.login(siUrl); return InteractiveLoginCommand.login(env, serviceInterface); } catch (final LoginException ex) { throw new GricliRuntimeException(ex); } }
public GricliEnvironment execute(GricliEnvironment env) throws GricliRuntimeException { try { if (siUrl == null) { siUrl = env.getServiceInterfaceUrl(); } final ServiceInterface serviceInterface = LoginManager .loginCommandline(siUrl); return InteractiveLoginCommand.login(env, serviceInterface); } catch (final LoginException ex) { throw new GricliRuntimeException(ex); } }
diff --git a/client/src/main/java/com/nesscomputing/httpclient/response/StreamedJsonContentConverter.java b/client/src/main/java/com/nesscomputing/httpclient/response/StreamedJsonContentConverter.java index a5a2dfa..cebc0d5 100644 --- a/client/src/main/java/com/nesscomputing/httpclient/response/StreamedJsonContentConverter.java +++ b/client/src/main/java/com/nesscomputing/httpclient/response/StreamedJsonContentConverter.java @@ -1,141 +1,144 @@ /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.Map; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Objects; import com.google.common.base.Throwables; import com.nesscomputing.callback.Callback; import com.nesscomputing.callback.CallbackRefusedException; import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.httpclient.HttpClientResponseHandler; import com.nesscomputing.logging.Log; /** * Accepts an incoming JSON data stream and converts it into objects on the fly. The JSON data stream must be structured in a special format: * <pre> * { "results": [ .... stream of data ], * "success": true * } * </pre> * * No other fields must be present in the JSON object besides <tt>results</tt> and <tt>success</tt> and the <tt>success</tt> field must immediately follow * the <tt>results</tt> field to mark its end. */ public class StreamedJsonContentConverter<T> extends AbstractErrorHandlingContentConverter<Void> { private static final Log LOG = Log.findLog(); private static final TypeReference<Map<String, ? extends Object>> JSON_MAP_TYPE_REF = new TypeReference<Map<String, ? extends Object>>() {}; public static StreamedJsonContentConverter<Map<String, ? extends Object>> of(final ObjectMapper mapper, final Callback<Map<String, ? extends Object>> callback) { return new StreamedJsonContentConverter<Map<String, ? extends Object>>(mapper, callback, JSON_MAP_TYPE_REF); } public static HttpClientResponseHandler<Void> handle(final ObjectMapper mapper, final Callback<Map<String, ? extends Object>> callback) { return ContentResponseHandler.forConverter(new StreamedJsonContentConverter<Map<String, ? extends Object>>(mapper, callback, JSON_MAP_TYPE_REF)); } public static <T> HttpClientResponseHandler<Void> handle(final ObjectMapper mapper, final Callback<? super T> callback, final TypeReference<T> typeReference) { return ContentResponseHandler.forConverter(new StreamedJsonContentConverter<T>(mapper, callback, typeReference)); } private final ObjectMapper mapper; private final TypeReference<T> typeRef; private final Callback<? super T> callback; StreamedJsonContentConverter(final ObjectMapper mapper, final Callback<? super T> callback, final TypeReference<T> typeRef) { this.mapper = mapper; this.typeRef = typeRef; this.callback = callback; } @Override public Void convert(final HttpClientResponse response, final InputStream inputStream) throws IOException { switch(response.getStatusCode()) { case 201: case 204: LOG.debug("Return code is %d, finishing.", response.getStatusCode()); return null; case 200: final JsonParser jp = mapper.getFactory().createJsonParser(inputStream); try { expect(jp, jp.nextToken(), JsonToken.START_OBJECT); expect(jp, jp.nextToken(), JsonToken.FIELD_NAME); if (!"results".equals(jp.getCurrentName())) { throw new JsonParseException("expecting results field", jp.getCurrentLocation()); } expect(jp, jp.nextToken(), JsonToken.START_ARRAY); - jp.nextToken(); // readValuesAs must be positioned after the START_ARRAY token, per javadoc. + // As noted in a well-hidden comment in the MappingIterator constructor, + // readValuesAs requires the parser to be positioned after the START_ARRAY + // token with an empty current token + jp.clearCurrentToken(); Iterator<T> iter = jp.readValuesAs(typeRef); while (iter.hasNext()) { try { callback.call(iter.next()); } catch (CallbackRefusedException e) { LOG.debug(e, "callback refused execution, finishing."); return null; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Callback interrupted", e); } catch (Exception e) { Throwables.propagateIfPossible(e, IOException.class); throw new IOException("Callback failure", e); } } if (jp.nextValue() != JsonToken.VALUE_TRUE || !jp.getCurrentName().equals("success")) { throw new IOException("Streamed receive did not terminate normally; inspect server logs for cause."); } return null; } finally { jp.close(); } default: throw throwHttpResponseException(response); } } private void expect(final JsonParser jp, final JsonToken token, final JsonToken expected) throws JsonParseException { if (!Objects.equal(token, expected)) { throw new JsonParseException(String.format("Expected %s, found %s", expected, token), jp.getCurrentLocation()); } } }
true
true
public Void convert(final HttpClientResponse response, final InputStream inputStream) throws IOException { switch(response.getStatusCode()) { case 201: case 204: LOG.debug("Return code is %d, finishing.", response.getStatusCode()); return null; case 200: final JsonParser jp = mapper.getFactory().createJsonParser(inputStream); try { expect(jp, jp.nextToken(), JsonToken.START_OBJECT); expect(jp, jp.nextToken(), JsonToken.FIELD_NAME); if (!"results".equals(jp.getCurrentName())) { throw new JsonParseException("expecting results field", jp.getCurrentLocation()); } expect(jp, jp.nextToken(), JsonToken.START_ARRAY); jp.nextToken(); // readValuesAs must be positioned after the START_ARRAY token, per javadoc. Iterator<T> iter = jp.readValuesAs(typeRef); while (iter.hasNext()) { try { callback.call(iter.next()); } catch (CallbackRefusedException e) { LOG.debug(e, "callback refused execution, finishing."); return null; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Callback interrupted", e); } catch (Exception e) { Throwables.propagateIfPossible(e, IOException.class); throw new IOException("Callback failure", e); } } if (jp.nextValue() != JsonToken.VALUE_TRUE || !jp.getCurrentName().equals("success")) { throw new IOException("Streamed receive did not terminate normally; inspect server logs for cause."); } return null; } finally { jp.close(); } default: throw throwHttpResponseException(response); } }
public Void convert(final HttpClientResponse response, final InputStream inputStream) throws IOException { switch(response.getStatusCode()) { case 201: case 204: LOG.debug("Return code is %d, finishing.", response.getStatusCode()); return null; case 200: final JsonParser jp = mapper.getFactory().createJsonParser(inputStream); try { expect(jp, jp.nextToken(), JsonToken.START_OBJECT); expect(jp, jp.nextToken(), JsonToken.FIELD_NAME); if (!"results".equals(jp.getCurrentName())) { throw new JsonParseException("expecting results field", jp.getCurrentLocation()); } expect(jp, jp.nextToken(), JsonToken.START_ARRAY); // As noted in a well-hidden comment in the MappingIterator constructor, // readValuesAs requires the parser to be positioned after the START_ARRAY // token with an empty current token jp.clearCurrentToken(); Iterator<T> iter = jp.readValuesAs(typeRef); while (iter.hasNext()) { try { callback.call(iter.next()); } catch (CallbackRefusedException e) { LOG.debug(e, "callback refused execution, finishing."); return null; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Callback interrupted", e); } catch (Exception e) { Throwables.propagateIfPossible(e, IOException.class); throw new IOException("Callback failure", e); } } if (jp.nextValue() != JsonToken.VALUE_TRUE || !jp.getCurrentName().equals("success")) { throw new IOException("Streamed receive did not terminate normally; inspect server logs for cause."); } return null; } finally { jp.close(); } default: throw throwHttpResponseException(response); } }
diff --git a/source/de/anomic/plasma/plasmaSearchRankingProcess.java b/source/de/anomic/plasma/plasmaSearchRankingProcess.java index 079845643..3a8cce781 100644 --- a/source/de/anomic/plasma/plasmaSearchRankingProcess.java +++ b/source/de/anomic/plasma/plasmaSearchRankingProcess.java @@ -1,481 +1,483 @@ // plasmaSearchRankingProcess.java // (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany // first published 07.11.2007 on http://yacy.net // // This is a part of YaCy, a peer-to-peer based web search engine // // $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $ // $LastChangedRevision: 1986 $ // $LastChangedBy: orbiter $ // // LICENSE // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package de.anomic.plasma; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import de.anomic.htmlFilter.htmlFilterContentScraper; import de.anomic.index.indexContainer; import de.anomic.index.indexRWIEntry; import de.anomic.index.indexRWIEntryOrder; import de.anomic.index.indexRWIVarEntry; import de.anomic.index.indexURLEntry; import de.anomic.kelondro.kelondroBinSearch; import de.anomic.kelondro.kelondroMScoreCluster; import de.anomic.kelondro.kelondroSortStack; import de.anomic.server.serverCodings; import de.anomic.server.serverFileUtils; import de.anomic.server.serverProfiling; import de.anomic.yacy.yacyURL; public final class plasmaSearchRankingProcess { public static kelondroBinSearch[] ybrTables = null; // block-rank tables private static boolean useYBR = true; private kelondroSortStack<indexRWIVarEntry> stack; private HashMap<String, kelondroSortStack<indexRWIVarEntry>> doubleDomCache; // key = domhash (6 bytes); value = like stack private HashMap<String, String> handover; // key = urlhash, value = urlstring; used for double-check of urls that had been handed over to search process private plasmaSearchQuery query; private int maxentries; private int remote_peerCount, remote_indexCount, remote_resourceSize, local_resourceSize; private indexRWIEntryOrder order; private ConcurrentHashMap<String, Integer> urlhashes; // map for double-check; String/Long relation, addresses ranking number (backreference for deletion) private kelondroMScoreCluster<String> ref; // reference score computation for the commonSense heuristic private int[] flagcount; // flag counter private TreeSet<String> misses; // contains url-hashes that could not been found in the LURL-DB private plasmaWordIndex wordIndex; private HashMap<String, indexContainer>[] localSearchContainerMaps; private int[] domZones; public plasmaSearchRankingProcess(plasmaWordIndex wordIndex, plasmaSearchQuery query, int maxentries, int concurrency) { // we collect the urlhashes and construct a list with urlEntry objects // attention: if minEntries is too high, this method will not terminate within the maxTime // sortorder: 0 = hash, 1 = url, 2 = ranking this.localSearchContainerMaps = null; this.stack = new kelondroSortStack<indexRWIVarEntry>(maxentries); this.doubleDomCache = new HashMap<String, kelondroSortStack<indexRWIVarEntry>>(); this.handover = new HashMap<String, String>(); this.order = (query == null) ? null : new indexRWIEntryOrder(query.ranking); this.query = query; this.maxentries = maxentries; this.remote_peerCount = 0; this.remote_indexCount = 0; this.remote_resourceSize = 0; this.local_resourceSize = 0; this.urlhashes = new ConcurrentHashMap<String, Integer>(0, 0.75f, concurrency); this.ref = new kelondroMScoreCluster<String>(); this.misses = new TreeSet<String>(); this.wordIndex = wordIndex; this.flagcount = new int[32]; for (int i = 0; i < 32; i++) {this.flagcount[i] = 0;} this.domZones = new int[8]; for (int i = 0; i < 8; i++) {this.domZones[i] = 0;} } public long ranking(indexRWIVarEntry word) { return order.cardinal(word); } public int[] zones() { return this.domZones; } public void execQuery() { long timer = System.currentTimeMillis(); this.localSearchContainerMaps = wordIndex.localSearchContainers(query, null); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), plasmaSearchEvent.COLLECTION, this.localSearchContainerMaps[0].size(), System.currentTimeMillis() - timer)); // join and exclude the local result timer = System.currentTimeMillis(); indexContainer index = (this.localSearchContainerMaps == null) ? plasmaWordIndex.emptyContainer(null, 0) : indexContainer.joinExcludeContainers( this.localSearchContainerMaps[0].values(), this.localSearchContainerMaps[1].values(), query.maxDistance); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), plasmaSearchEvent.JOIN, index.size(), System.currentTimeMillis() - timer)); int joincount = index.size(); if ((index == null) || (joincount == 0)) { return; } insertRanked(index, true, index.size()); } public void insertRanked(indexContainer index, boolean local, int fullResource) { // we collect the urlhashes and construct a list with urlEntry objects // attention: if minEntries is too high, this method will not terminate within the maxTime assert (index != null); if (index.size() == 0) return; if (local) { this.local_resourceSize += fullResource; } else { this.remote_resourceSize += fullResource; this.remote_peerCount++; } long timer = System.currentTimeMillis(); // normalize entries ArrayList<indexRWIVarEntry> decodedEntries = this.order.normalizeWith(index); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), plasmaSearchEvent.NORMALIZING, index.size(), System.currentTimeMillis() - timer)); // iterate over normalized entries and select some that are better than currently stored timer = System.currentTimeMillis(); Iterator<indexRWIVarEntry> i = decodedEntries.iterator(); indexRWIVarEntry iEntry; Long r; while (i.hasNext()) { iEntry = i.next(); assert (iEntry.urlHash().length() == index.row().primaryKeyLength); //if (iEntry.urlHash().length() != index.row().primaryKeyLength) continue; // increase flag counts for (int j = 0; j < 32; j++) { if (iEntry.flags().get(j)) {flagcount[j]++;} } // kick out entries that are too bad according to current findings r = new Long(order.cardinal(iEntry)); if ((maxentries >= 0) && (stack.size() >= maxentries) && (stack.bottom(r.longValue()))) continue; // check constraints if (!testFlags(iEntry)) continue; // check document domain if (query.contentdom != plasmaSearchQuery.CONTENTDOM_TEXT) { if ((query.contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) && (!(iEntry.flags().get(plasmaCondenser.flag_cat_hasaudio)))) continue; if ((query.contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) && (!(iEntry.flags().get(plasmaCondenser.flag_cat_hasvideo)))) continue; if ((query.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) && (!(iEntry.flags().get(plasmaCondenser.flag_cat_hasimage)))) continue; if ((query.contentdom == plasmaSearchQuery.CONTENTDOM_APP ) && (!(iEntry.flags().get(plasmaCondenser.flag_cat_hasapp )))) continue; } // check tld domain if (!yacyURL.matchesAnyDomDomain(iEntry.urlHash(), this.query.zonecode)) { // filter out all tld that do not match with wanted tld domain continue; } // count domZones - System.out.println("DEBUG domDomain dom=" + wordIndex.loadedURL.load(iEntry.urlHash, iEntry, 0).comp().url().getHost() + ", zone=" + yacyURL.domDomain(iEntry.urlHash())); + indexURLEntry uentry = wordIndex.loadedURL.load(iEntry.urlHash, iEntry, 0); + yacyURL uurl = (uentry == null) ? null : uentry.comp().url(); + System.out.println("DEBUG domDomain dom=" + ((uurl == null) ? "null" : uurl.getHost()) + ", zone=" + yacyURL.domDomain(iEntry.urlHash())); this.domZones[yacyURL.domDomain(iEntry.urlHash())]++; // insert if ((maxentries < 0) || (stack.size() < maxentries)) { // in case that we don't have enough yet, accept any new entry if (urlhashes.containsKey(iEntry.urlHash())) continue; stack.push(iEntry, r); } else { // if we already have enough entries, insert only such that are necessary to get a better result if (stack.bottom(r.longValue())) { continue; } else { // double-check if (urlhashes.containsKey(iEntry.urlHash())) continue; stack.push(iEntry, r); } } // increase counter for statistics if (!local) this.remote_indexCount++; } //if ((query.neededResults() > 0) && (container.size() > query.neededResults())) remove(true, true); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), plasmaSearchEvent.PRESORT, index.size(), System.currentTimeMillis() - timer)); } private boolean testFlags(indexRWIEntry ientry) { if (query.constraint == null) return true; // test if ientry matches with filter // if all = true: let only entries pass that has all matching bits // if all = false: let all entries pass that has at least one matching bit if (query.allofconstraint) { for (int i = 0; i < 32; i++) { if ((query.constraint.get(i)) && (!ientry.flags().get(i))) return false; } return true; } for (int i = 0; i < 32; i++) { if ((query.constraint.get(i)) && (ientry.flags().get(i))) return true; } return false; } public Map<String, indexContainer>[] searchContainerMaps() { // direct access to the result maps is needed for abstract generation // this is only available if execQuery() was called before return localSearchContainerMaps; } // todo: // - remove redundant urls (sub-path occurred before) // - move up shorter urls // - root-domain guessing to prefer the root domain over other urls if search word appears in domain name private synchronized kelondroSortStack<indexRWIVarEntry>.stackElement bestRWI(boolean skipDoubleDom) { // returns from the current RWI list the best entry and removed this entry from the list kelondroSortStack<indexRWIVarEntry> m; kelondroSortStack<indexRWIVarEntry>.stackElement rwi; while (stack.size() > 0) { rwi = stack.pop(); if (!skipDoubleDom) return rwi; // check doubledom String domhash = rwi.element.urlHash().substring(6); m = this.doubleDomCache.get(domhash); if (m == null) { // first appearance of dom m = new kelondroSortStack<indexRWIVarEntry>(-1); this.doubleDomCache.put(domhash, m); return rwi; } // second appearances of dom m.push(rwi); } // no more entries in sorted RWI entries. Now take Elements from the doubleDomCache // find best entry from all caches Iterator<kelondroSortStack<indexRWIVarEntry>> i = this.doubleDomCache.values().iterator(); kelondroSortStack<indexRWIVarEntry>.stackElement bestEntry = null; kelondroSortStack<indexRWIVarEntry>.stackElement o; while (i.hasNext()) { m = i.next(); if (m.size() == 0) continue; if (bestEntry == null) { bestEntry = m.top(); continue; } o = m.top(); if (o.weight.longValue() < bestEntry.weight.longValue()) { bestEntry = o; } } if (bestEntry == null) return null; // finally remove the best entry from the doubledom cache m = this.doubleDomCache.get(bestEntry.element.urlHash().substring(6)); o = m.pop(); assert o.element.urlHash().equals(bestEntry.element.urlHash()); return bestEntry; } public synchronized indexURLEntry bestURL(boolean skipDoubleDom) { // returns from the current RWI list the best URL entry and removed this entry from the list while ((stack.size() > 0) || (size() > 0)) { kelondroSortStack<indexRWIVarEntry>.stackElement obrwi = bestRWI(skipDoubleDom); indexURLEntry u = wordIndex.loadedURL.load(obrwi.element.urlHash(), obrwi.element, obrwi.weight.longValue()); if (u != null) { indexURLEntry.Components comp = u.comp(); if (comp.url() != null) this.handover.put(u.hash(), comp.url().toNormalform(true, false)); // remember that we handed over this url return u; } misses.add(obrwi.element.urlHash()); } return null; } public synchronized int size() { //assert sortedRWIEntries.size() == urlhashes.size() : "sortedRWIEntries.size() = " + sortedRWIEntries.size() + ", urlhashes.size() = " + urlhashes.size(); int c = stack.size(); Iterator<kelondroSortStack<indexRWIVarEntry>> i = this.doubleDomCache.values().iterator(); while (i.hasNext()) c += i.next().size(); return c; } public int[] flagCount() { return flagcount; } // "results from a total number of <remote_resourceSize + local_resourceSize> known (<local_resourceSize> local, <remote_resourceSize> remote), <remote_indexCount> links from <remote_peerCount> other YaCy peers." public int filteredCount() { // the number of index entries that are considered as result set return this.stack.size(); } public int getRemoteIndexCount() { // the number of result contributions from all the remote peers return this.remote_indexCount; } public int getRemotePeerCount() { // the number of remote peers that have contributed return this.remote_peerCount; } public int getRemoteResourceSize() { // the number of all hits in all the remote peers return this.remote_resourceSize; } public int getLocalResourceSize() { // the number of hits in the local peer (index size, size of the collection in the own index) return this.local_resourceSize; } public indexRWIEntry remove(String urlHash) { kelondroSortStack<indexRWIVarEntry>.stackElement se = stack.remove(urlHash.hashCode()); if (se == null) return null; urlhashes.remove(urlHash); return se.element; } public Iterator<String> miss() { return this.misses.iterator(); } public Set<String> getReferences(int count) { // create a list of words that had been computed by statistics over all // words that appeared in the url or the description of all urls Object[] refs = ref.getScores(count, false, 2, Integer.MAX_VALUE); TreeSet<String> s = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); for (int i = 0; i < refs.length; i++) { s.add((String) refs[i]); } return s; } public void addReferences(String[] words) { String word; for (int i = 0; i < words.length; i++) { word = words[i].toLowerCase(); if ((word.length() > 2) && ("http_html_php_ftp_www_com_org_net_gov_edu_index_home_page_for_usage_the_and_".indexOf(word) < 0) && (!(query.queryHashes.contains(plasmaCondenser.word2hash(word))))) ref.incScore(word); } } protected void addReferences(plasmaSearchEvent.ResultEntry resultEntry) { // take out relevant information for reference computation if ((resultEntry.url() == null) || (resultEntry.title() == null)) return; String[] urlcomps = htmlFilterContentScraper.urlComps(resultEntry.url().toNormalform(true, true)); // word components of the url String[] descrcomps = resultEntry.title().toLowerCase().split(htmlFilterContentScraper.splitrex); // words in the description // add references addReferences(urlcomps); addReferences(descrcomps); } public indexRWIEntryOrder getOrder() { return this.order; } public static void loadYBR(File rankingPath, int count) { // load ranking tables if (rankingPath.exists()) { ybrTables = new kelondroBinSearch[count]; String ybrName; File f; try { for (int i = 0; i < count; i++) { ybrName = "YBR-4-" + serverCodings.encodeHex(i, 2) + ".idx"; f = new File(rankingPath, ybrName); if (f.exists()) { ybrTables[i] = new kelondroBinSearch(serverFileUtils.read(f), 6); } else { ybrTables[i] = null; } } } catch (IOException e) { ybrTables = null; } } else { ybrTables = null; } } public static boolean canUseYBR() { return ybrTables != null; } public static boolean isUsingYBR() { return useYBR; } public static void switchYBR(boolean usage) { useYBR = usage; } public static int ybr(String urlHash) { // returns the YBR value in a range of 0..15, where 0 means best ranking and 15 means worst ranking if (ybrTables == null) return 15; if (!(useYBR)) return 15; final String domHash = urlHash.substring(6); for (int i = 0; i < ybrTables.length; i++) { if ((ybrTables[i] != null) && (ybrTables[i].contains(domHash.getBytes()))) { //System.out.println("YBR FOUND: " + urlHash + " (" + i + ")"); return i; } } //System.out.println("NOT FOUND: " + urlHash); return 15; } public long postRanking( Set<String> topwords, plasmaSearchEvent.ResultEntry rentry, int position) { long r = (255 - position) << 8; // for media search: prefer pages with many links if (query.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) r += rentry.limage() << query.ranking.coeff_cathasimage; if (query.contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) r += rentry.laudio() << query.ranking.coeff_cathasaudio; if (query.contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) r += rentry.lvideo() << query.ranking.coeff_cathasvideo; if (query.contentdom == plasmaSearchQuery.CONTENTDOM_APP ) r += rentry.lapp() << query.ranking.coeff_cathasapp; // prefer hit with 'prefer' pattern if (rentry.url().toNormalform(true, true).matches(query.prefer)) r += 256 << query.ranking.coeff_prefer; if (rentry.title().matches(query.prefer)) r += 256 << query.ranking.coeff_prefer; // apply 'common-sense' heuristic using references String urlstring = rentry.url().toNormalform(true, true); String[] urlcomps = htmlFilterContentScraper.urlComps(urlstring); String[] descrcomps = rentry.title().toLowerCase().split(htmlFilterContentScraper.splitrex); for (int j = 0; j < urlcomps.length; j++) { if (topwords.contains(urlcomps[j])) r += Math.max(1, 256 - urlstring.length()) << query.ranking.coeff_urlcompintoplist; } for (int j = 0; j < descrcomps.length; j++) { if (topwords.contains(descrcomps[j])) r += Math.max(1, 256 - rentry.title().length()) << query.ranking.coeff_descrcompintoplist; } // apply query-in-result matching Set<String> urlcomph = plasmaCondenser.words2hashSet(urlcomps); Set<String> descrcomph = plasmaCondenser.words2hashSet(descrcomps); Iterator<String> shi = query.queryHashes.iterator(); String queryhash; while (shi.hasNext()) { queryhash = shi.next(); if (urlcomph.contains(queryhash)) r += 256 << query.ranking.coeff_appurl; if (descrcomph.contains(queryhash)) r += 256 << query.ranking.coeff_app_dc_title; } return r; } }
true
true
public void insertRanked(indexContainer index, boolean local, int fullResource) { // we collect the urlhashes and construct a list with urlEntry objects // attention: if minEntries is too high, this method will not terminate within the maxTime assert (index != null); if (index.size() == 0) return; if (local) { this.local_resourceSize += fullResource; } else { this.remote_resourceSize += fullResource; this.remote_peerCount++; } long timer = System.currentTimeMillis(); // normalize entries ArrayList<indexRWIVarEntry> decodedEntries = this.order.normalizeWith(index); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), plasmaSearchEvent.NORMALIZING, index.size(), System.currentTimeMillis() - timer)); // iterate over normalized entries and select some that are better than currently stored timer = System.currentTimeMillis(); Iterator<indexRWIVarEntry> i = decodedEntries.iterator(); indexRWIVarEntry iEntry; Long r; while (i.hasNext()) { iEntry = i.next(); assert (iEntry.urlHash().length() == index.row().primaryKeyLength); //if (iEntry.urlHash().length() != index.row().primaryKeyLength) continue; // increase flag counts for (int j = 0; j < 32; j++) { if (iEntry.flags().get(j)) {flagcount[j]++;} } // kick out entries that are too bad according to current findings r = new Long(order.cardinal(iEntry)); if ((maxentries >= 0) && (stack.size() >= maxentries) && (stack.bottom(r.longValue()))) continue; // check constraints if (!testFlags(iEntry)) continue; // check document domain if (query.contentdom != plasmaSearchQuery.CONTENTDOM_TEXT) { if ((query.contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) && (!(iEntry.flags().get(plasmaCondenser.flag_cat_hasaudio)))) continue; if ((query.contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) && (!(iEntry.flags().get(plasmaCondenser.flag_cat_hasvideo)))) continue; if ((query.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) && (!(iEntry.flags().get(plasmaCondenser.flag_cat_hasimage)))) continue; if ((query.contentdom == plasmaSearchQuery.CONTENTDOM_APP ) && (!(iEntry.flags().get(plasmaCondenser.flag_cat_hasapp )))) continue; } // check tld domain if (!yacyURL.matchesAnyDomDomain(iEntry.urlHash(), this.query.zonecode)) { // filter out all tld that do not match with wanted tld domain continue; } // count domZones System.out.println("DEBUG domDomain dom=" + wordIndex.loadedURL.load(iEntry.urlHash, iEntry, 0).comp().url().getHost() + ", zone=" + yacyURL.domDomain(iEntry.urlHash())); this.domZones[yacyURL.domDomain(iEntry.urlHash())]++; // insert if ((maxentries < 0) || (stack.size() < maxentries)) { // in case that we don't have enough yet, accept any new entry if (urlhashes.containsKey(iEntry.urlHash())) continue; stack.push(iEntry, r); } else { // if we already have enough entries, insert only such that are necessary to get a better result if (stack.bottom(r.longValue())) { continue; } else { // double-check if (urlhashes.containsKey(iEntry.urlHash())) continue; stack.push(iEntry, r); } } // increase counter for statistics if (!local) this.remote_indexCount++; } //if ((query.neededResults() > 0) && (container.size() > query.neededResults())) remove(true, true); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), plasmaSearchEvent.PRESORT, index.size(), System.currentTimeMillis() - timer)); }
public void insertRanked(indexContainer index, boolean local, int fullResource) { // we collect the urlhashes and construct a list with urlEntry objects // attention: if minEntries is too high, this method will not terminate within the maxTime assert (index != null); if (index.size() == 0) return; if (local) { this.local_resourceSize += fullResource; } else { this.remote_resourceSize += fullResource; this.remote_peerCount++; } long timer = System.currentTimeMillis(); // normalize entries ArrayList<indexRWIVarEntry> decodedEntries = this.order.normalizeWith(index); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), plasmaSearchEvent.NORMALIZING, index.size(), System.currentTimeMillis() - timer)); // iterate over normalized entries and select some that are better than currently stored timer = System.currentTimeMillis(); Iterator<indexRWIVarEntry> i = decodedEntries.iterator(); indexRWIVarEntry iEntry; Long r; while (i.hasNext()) { iEntry = i.next(); assert (iEntry.urlHash().length() == index.row().primaryKeyLength); //if (iEntry.urlHash().length() != index.row().primaryKeyLength) continue; // increase flag counts for (int j = 0; j < 32; j++) { if (iEntry.flags().get(j)) {flagcount[j]++;} } // kick out entries that are too bad according to current findings r = new Long(order.cardinal(iEntry)); if ((maxentries >= 0) && (stack.size() >= maxentries) && (stack.bottom(r.longValue()))) continue; // check constraints if (!testFlags(iEntry)) continue; // check document domain if (query.contentdom != plasmaSearchQuery.CONTENTDOM_TEXT) { if ((query.contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) && (!(iEntry.flags().get(plasmaCondenser.flag_cat_hasaudio)))) continue; if ((query.contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) && (!(iEntry.flags().get(plasmaCondenser.flag_cat_hasvideo)))) continue; if ((query.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) && (!(iEntry.flags().get(plasmaCondenser.flag_cat_hasimage)))) continue; if ((query.contentdom == plasmaSearchQuery.CONTENTDOM_APP ) && (!(iEntry.flags().get(plasmaCondenser.flag_cat_hasapp )))) continue; } // check tld domain if (!yacyURL.matchesAnyDomDomain(iEntry.urlHash(), this.query.zonecode)) { // filter out all tld that do not match with wanted tld domain continue; } // count domZones indexURLEntry uentry = wordIndex.loadedURL.load(iEntry.urlHash, iEntry, 0); yacyURL uurl = (uentry == null) ? null : uentry.comp().url(); System.out.println("DEBUG domDomain dom=" + ((uurl == null) ? "null" : uurl.getHost()) + ", zone=" + yacyURL.domDomain(iEntry.urlHash())); this.domZones[yacyURL.domDomain(iEntry.urlHash())]++; // insert if ((maxentries < 0) || (stack.size() < maxentries)) { // in case that we don't have enough yet, accept any new entry if (urlhashes.containsKey(iEntry.urlHash())) continue; stack.push(iEntry, r); } else { // if we already have enough entries, insert only such that are necessary to get a better result if (stack.bottom(r.longValue())) { continue; } else { // double-check if (urlhashes.containsKey(iEntry.urlHash())) continue; stack.push(iEntry, r); } } // increase counter for statistics if (!local) this.remote_indexCount++; } //if ((query.neededResults() > 0) && (container.size() > query.neededResults())) remove(true, true); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(query.id(true), plasmaSearchEvent.PRESORT, index.size(), System.currentTimeMillis() - timer)); }
diff --git a/src/main/java/com/bennight/serializers/SimpleFeatureTest.java b/src/main/java/com/bennight/serializers/SimpleFeatureTest.java index 076f1ef..283a961 100644 --- a/src/main/java/com/bennight/serializers/SimpleFeatureTest.java +++ b/src/main/java/com/bennight/serializers/SimpleFeatureTest.java @@ -1,48 +1,48 @@ package com.bennight.serializers; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import org.geotools.data.DataUtilities; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import com.bennight.ShapefileReader; public class SimpleFeatureTest extends AbstractSerializer { @Override public List<byte[]> Serialize(List<SimpleFeature> features) { StringBuilder sb = new StringBuilder(); for (SimpleFeature f : features){ - //sb.append(DataUtilities.encodeFeature(f)); - sb.append("c_03de13.1=MULTIPOLYGON (((-171.04048645299997 -11.082452137999951, -171.03939819299998 -11.083986281999955, -171.04257634399997 -11.08686948299993, -171.04260253899997 -11.086890220999976, -171.04408264199998 -11.087923049999972, -171.04589843799997 -11.089185714999928, -171.04949855299998 -11.088085467999974, -171.05088806199998 -11.086385726999936, -171.05091240799996 -11.086359097999946, -171.05190946399998 -11.08454626899993, -171.05198669399996 -11.084383964999972, -171.05068969699997 -11.081686973999979, -171.04788002399997 -11.080834331999938, -171.04739379899996 -11.080690383999979, -171.04675375999997 -11.080580699999928, -171.04499816899997 -11.080288886999938, -171.04491414599997 -11.080302390999975, -171.04159602699997 -11.080888646999938, -171.04048645299997 -11.082452137999951), (-171.04824829099996 -11.084536551999975, -171.04669189499998 -11.087289809999959, -171.04508972199997 -11.084585189999927, -171.04525756799998 -11.084311484999944, -171.04551696799996 -11.083907126999975, -171.04577636699997 -11.083460807999927, -171.04620361299996 -11.082786559999931, -171.04663085899998 -11.083086966999929, -171.047134399 -11.08342552199997, -171.04840087899998 -11.08428478199994, -171.04824829099996 -11.084536551999975)))|1|AS|PPG|Swains Island|60040|S||-171.045984785|-11.0843655158|0.0440795005116|6.71191815609E-5"); + sb.append(DataUtilities.encodeFeature(f)); + //sb.append("c_03de13.1=MULTIPOLYGON (((-171.04048645299997 -11.082452137999951, -171.03939819299998 -11.083986281999955, -171.04257634399997 -11.08686948299993, -171.04260253899997 -11.086890220999976, -171.04408264199998 -11.087923049999972, -171.04589843799997 -11.089185714999928, -171.04949855299998 -11.088085467999974, -171.05088806199998 -11.086385726999936, -171.05091240799996 -11.086359097999946, -171.05190946399998 -11.08454626899993, -171.05198669399996 -11.084383964999972, -171.05068969699997 -11.081686973999979, -171.04788002399997 -11.080834331999938, -171.04739379899996 -11.080690383999979, -171.04675375999997 -11.080580699999928, -171.04499816899997 -11.080288886999938, -171.04491414599997 -11.080302390999975, -171.04159602699997 -11.080888646999938, -171.04048645299997 -11.082452137999951), (-171.04824829099996 -11.084536551999975, -171.04669189499998 -11.087289809999959, -171.04508972199997 -11.084585189999927, -171.04525756799998 -11.084311484999944, -171.04551696799996 -11.083907126999975, -171.04577636699997 -11.083460807999927, -171.04620361299996 -11.082786559999931, -171.04663085899998 -11.083086966999929, -171.047134399 -11.08342552199997, -171.04840087899998 -11.08428478199994, -171.04824829099996 -11.084536551999975)))|1|AS|PPG|Swains Island|60040|S||-171.045984785|-11.0843655158|0.0440795005116|6.71191815609E-5"); //System.out.println(sb.toString()); sb.append("\r\n"); } List<byte[]> serializedData = new ArrayList<byte[]>(); serializedData.add(sb.toString().getBytes(StandardCharsets.UTF_8)); return serializedData; } @Override public void Deserialize(List<byte[]> serializedData) { List<SimpleFeature> features = new ArrayList<SimpleFeature>(); for (String line : (new String(serializedData.get(0), StandardCharsets.UTF_8).split("\r\n"))){ features.add(DataUtilities.createFeature(ShapefileReader.FeatureType, line)); } //System.out.println(features.size()); } public String GetSerializerName() { return "GeoTools Simple Feature"; } }
true
true
public List<byte[]> Serialize(List<SimpleFeature> features) { StringBuilder sb = new StringBuilder(); for (SimpleFeature f : features){ //sb.append(DataUtilities.encodeFeature(f)); sb.append("c_03de13.1=MULTIPOLYGON (((-171.04048645299997 -11.082452137999951, -171.03939819299998 -11.083986281999955, -171.04257634399997 -11.08686948299993, -171.04260253899997 -11.086890220999976, -171.04408264199998 -11.087923049999972, -171.04589843799997 -11.089185714999928, -171.04949855299998 -11.088085467999974, -171.05088806199998 -11.086385726999936, -171.05091240799996 -11.086359097999946, -171.05190946399998 -11.08454626899993, -171.05198669399996 -11.084383964999972, -171.05068969699997 -11.081686973999979, -171.04788002399997 -11.080834331999938, -171.04739379899996 -11.080690383999979, -171.04675375999997 -11.080580699999928, -171.04499816899997 -11.080288886999938, -171.04491414599997 -11.080302390999975, -171.04159602699997 -11.080888646999938, -171.04048645299997 -11.082452137999951), (-171.04824829099996 -11.084536551999975, -171.04669189499998 -11.087289809999959, -171.04508972199997 -11.084585189999927, -171.04525756799998 -11.084311484999944, -171.04551696799996 -11.083907126999975, -171.04577636699997 -11.083460807999927, -171.04620361299996 -11.082786559999931, -171.04663085899998 -11.083086966999929, -171.047134399 -11.08342552199997, -171.04840087899998 -11.08428478199994, -171.04824829099996 -11.084536551999975)))|1|AS|PPG|Swains Island|60040|S||-171.045984785|-11.0843655158|0.0440795005116|6.71191815609E-5"); //System.out.println(sb.toString()); sb.append("\r\n"); } List<byte[]> serializedData = new ArrayList<byte[]>(); serializedData.add(sb.toString().getBytes(StandardCharsets.UTF_8)); return serializedData; }
public List<byte[]> Serialize(List<SimpleFeature> features) { StringBuilder sb = new StringBuilder(); for (SimpleFeature f : features){ sb.append(DataUtilities.encodeFeature(f)); //sb.append("c_03de13.1=MULTIPOLYGON (((-171.04048645299997 -11.082452137999951, -171.03939819299998 -11.083986281999955, -171.04257634399997 -11.08686948299993, -171.04260253899997 -11.086890220999976, -171.04408264199998 -11.087923049999972, -171.04589843799997 -11.089185714999928, -171.04949855299998 -11.088085467999974, -171.05088806199998 -11.086385726999936, -171.05091240799996 -11.086359097999946, -171.05190946399998 -11.08454626899993, -171.05198669399996 -11.084383964999972, -171.05068969699997 -11.081686973999979, -171.04788002399997 -11.080834331999938, -171.04739379899996 -11.080690383999979, -171.04675375999997 -11.080580699999928, -171.04499816899997 -11.080288886999938, -171.04491414599997 -11.080302390999975, -171.04159602699997 -11.080888646999938, -171.04048645299997 -11.082452137999951), (-171.04824829099996 -11.084536551999975, -171.04669189499998 -11.087289809999959, -171.04508972199997 -11.084585189999927, -171.04525756799998 -11.084311484999944, -171.04551696799996 -11.083907126999975, -171.04577636699997 -11.083460807999927, -171.04620361299996 -11.082786559999931, -171.04663085899998 -11.083086966999929, -171.047134399 -11.08342552199997, -171.04840087899998 -11.08428478199994, -171.04824829099996 -11.084536551999975)))|1|AS|PPG|Swains Island|60040|S||-171.045984785|-11.0843655158|0.0440795005116|6.71191815609E-5"); //System.out.println(sb.toString()); sb.append("\r\n"); } List<byte[]> serializedData = new ArrayList<byte[]>(); serializedData.add(sb.toString().getBytes(StandardCharsets.UTF_8)); return serializedData; }
diff --git a/src/org/hyperic/hq/hqapi1/tools/Command.java b/src/org/hyperic/hq/hqapi1/tools/Command.java index 371634f..f343f84 100644 --- a/src/org/hyperic/hq/hqapi1/tools/Command.java +++ b/src/org/hyperic/hq/hqapi1/tools/Command.java @@ -1,183 +1,183 @@ package org.hyperic.hq.hqapi1.tools; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.apache.log4j.PropertyConfigurator; import org.hyperic.hq.hqapi1.HQApi; import org.hyperic.hq.hqapi1.types.Response; import org.hyperic.hq.hqapi1.types.ResponseStatus; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public abstract class Command { static final String OPT_HOST = "host"; static final String OPT_PORT = "port"; static final String OPT_USER = "user"; static final String OPT_PASS = "password"; static final String[] OPT_SECURE = {"s", "secure"}; static final String[] OPT_HELP = {"h","help"}; static final String OPT_FILE = "file"; // Ripped out from PluginMain.java private static final String[][] LOG_PROPS = { { "log4j.appender.R", "org.apache.log4j.ConsoleAppender" }, { "log4j.appender.R.layout.ConversionPattern", "%-5p [%t] [%c{1}] %m%n" }, { "log4j.appender.R.layout", "org.apache.log4j.PatternLayout" } }; private static void configureLogging(String level) { Properties props = new Properties(); props.setProperty("log4j.rootLogger", level.toUpperCase() + ", R"); props.setProperty("log4j.logger.httpclient.wire", level.toUpperCase()); props.setProperty("log4j.logger.org.apache.commons.httpclient", level.toUpperCase()); for (String[] PROPS : LOG_PROPS) { props.setProperty(PROPS[0], PROPS[1]); } props.putAll(System.getProperties()); PropertyConfigurator.configure(props); } static { // Quiet all logging configureLogging("fatal"); } static OptionParser getOptionParser() { OptionParser parser = new OptionParser(); parser.accepts(OPT_HOST, "The HQ server host"). withRequiredArg().ofType(String.class); parser.accepts(OPT_PORT, "The HQ server port. Defaults to 7080"). withOptionalArg().ofType(Integer.class); parser.accepts(OPT_USER, "The user to connect as"). withRequiredArg().ofType(String.class); parser.accepts(OPT_PASS, "The password for the given user"). withRequiredArg().ofType(String.class); parser.acceptsAll(Arrays.asList(OPT_SECURE), "Connect using SSL"); parser.acceptsAll(Arrays.asList(OPT_HELP), "Show this message"); parser.accepts(OPT_FILE, "If specified, use the given file for " + "commands that take XML input. If " + "not specified, stdin will be used."). withRequiredArg().ofType(String.class); return parser; } protected OptionSet getOptions(OptionParser p, String[] args) throws IOException { OptionSet o = p.parse(args); if (o.has(OPT_HELP[0]) || o.has(OPT_HELP[1])) { p.printHelpOn(System.err); System.exit(0); } return o; } private Properties getClientProperties() { Properties props = new Properties(); String home = System.getProperty("user.home"); File hq = new File(home, ".hq"); File clientProperties = new File(hq, "client.properties"); if (clientProperties.exists()) { props = new Properties(); try { props.load(new FileInputStream(clientProperties)); } catch (IOException e) { return props; } } return props; } protected InputStream getInputStream(OptionSet s) throws Exception { String file = (String)s.valueOf(OPT_FILE); if (file == null) { return System.in; } else { File f = new File(file); if (!f.exists()) { throw new Exception("Input file " + file + " does not exist."); } return new FileInputStream(f); } } protected HQApi getApi(OptionSet s) { Properties clientProps = getClientProperties(); String host = (String)s.valueOf(OPT_HOST); if (host == null) { host = clientProps.getProperty(OPT_HOST); } Integer port; if (s.hasArgument(OPT_PORT)) { port = (Integer)s.valueOf(OPT_PORT); } else { port = Integer.parseInt(clientProps.getProperty(OPT_PORT, "7080")); } String user = (String)s.valueOf(OPT_USER); if (user == null) { user = clientProps.getProperty(OPT_USER); } String password = (String)s.valueOf(OPT_PASS); if (password == null) { password = clientProps.getProperty(OPT_PASS); } - Boolean secure = s.hasArgument(OPT_SECURE[0]) || + Boolean secure = s.has(OPT_SECURE[0]) || Boolean.valueOf(clientProps.getProperty(OPT_SECURE[1], "false")); return new HQApi(host, port, secure, user, password); } protected Object getRequired(OptionSet s, String opt) { Object o = s.valueOf(opt); if (o == null) { System.err.println("Required argument " + opt + " not given."); System.exit(-1); } return o; } protected void checkSuccess(Response r) { if (r.getStatus() != ResponseStatus.SUCCESS) { System.err.println("Error running command: " + r.getError().getReasonText()); System.exit(-1); } } /** * Trim the first argument from an array returning the resulting elements. * * @param args The argument array to trim. * @return The trimmed array as defined as Array[1..len] */ protected static String[] trim(String[] args) { String[] cmdArgs = new String[args.length -1]; System.arraycopy(args, 1, cmdArgs, 0, args.length -1); return cmdArgs; } protected abstract void handleCommand(String[] args) throws Exception; }
true
true
protected HQApi getApi(OptionSet s) { Properties clientProps = getClientProperties(); String host = (String)s.valueOf(OPT_HOST); if (host == null) { host = clientProps.getProperty(OPT_HOST); } Integer port; if (s.hasArgument(OPT_PORT)) { port = (Integer)s.valueOf(OPT_PORT); } else { port = Integer.parseInt(clientProps.getProperty(OPT_PORT, "7080")); } String user = (String)s.valueOf(OPT_USER); if (user == null) { user = clientProps.getProperty(OPT_USER); } String password = (String)s.valueOf(OPT_PASS); if (password == null) { password = clientProps.getProperty(OPT_PASS); } Boolean secure = s.hasArgument(OPT_SECURE[0]) || Boolean.valueOf(clientProps.getProperty(OPT_SECURE[1], "false")); return new HQApi(host, port, secure, user, password); }
protected HQApi getApi(OptionSet s) { Properties clientProps = getClientProperties(); String host = (String)s.valueOf(OPT_HOST); if (host == null) { host = clientProps.getProperty(OPT_HOST); } Integer port; if (s.hasArgument(OPT_PORT)) { port = (Integer)s.valueOf(OPT_PORT); } else { port = Integer.parseInt(clientProps.getProperty(OPT_PORT, "7080")); } String user = (String)s.valueOf(OPT_USER); if (user == null) { user = clientProps.getProperty(OPT_USER); } String password = (String)s.valueOf(OPT_PASS); if (password == null) { password = clientProps.getProperty(OPT_PASS); } Boolean secure = s.has(OPT_SECURE[0]) || Boolean.valueOf(clientProps.getProperty(OPT_SECURE[1], "false")); return new HQApi(host, port, secure, user, password); }
diff --git a/ev/evplugin/imageset/EvImageJAI.java b/ev/evplugin/imageset/EvImageJAI.java index ebab50ab..0f8ee0ab 100755 --- a/ev/evplugin/imageset/EvImageJAI.java +++ b/ev/evplugin/imageset/EvImageJAI.java @@ -1,173 +1,173 @@ package evplugin.imageset; import javax.imageio.*; //import javax.vecmath.Vector2d; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; import com.sun.media.jai.codec.*; import java.io.*; import java.awt.image.*; import evplugin.ev.*; //static int getNumDirectories(SeekableStream stream) /** * Loader of images from single slice images using JAI * @author Johan Henriksson */ public abstract class EvImageJAI extends EvImage { private String filename; private int slice; /** * Load a single-slice image */ public EvImageJAI(String filename) { this.filename=filename; this.slice=-1; } /** * Load a slice in a stack */ public EvImageJAI(String filename, int slice) { this.filename=filename; this.slice=slice; } /** * Get name of file */ public String jaiFileName() { return filename; /* if(slice==-1) return filename; else return filename+":"+slice; */ } /** * Get slice number of -1 if it is the entire file */ public int jaiSlice() { return slice; } /** * Load the image */ public BufferedImage loadJavaImage() { try { File file=new File(filename); if(!file.exists()) return null; else { String fname=file.getName(); fname=fname.substring(fname.lastIndexOf(".")+1); if(slice==-1 && (fname.equals("tif") || fname.equals("tiff"))) //ImageIO failed on a .tif { SeekableStream s = new FileSeekableStream(file); TIFFDecodeParam param = null; ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param); // Log.printDebug("Number of images in this TIFF: " + dec.getNumPages()); // System.out.println("w"+ir.getWidth()+" h"+ir.getHeight()+" b"+ir.getSampleModel().getNumBands()); Raster ir=dec.decodeAsRaster(); int type=ir.getSampleModel().getDataType(); if(type==0) type=BufferedImage.TYPE_BYTE_GRAY;//? BufferedImage bim=new BufferedImage(ir.getWidth(),ir.getHeight(),type); WritableRaster wr=bim.getRaster(); wr.setRect(ir); return bim; } else if(slice==-1) { //Single-slice image - System.out.println(".. "+ImageIO.read(file)+" "+file.getAbsolutePath()); +// System.out.println(".. "+ImageIO.read(file)+" "+file.getAbsolutePath()); return ImageIO.read(file); } else { //Multi-slice image //Only one type supported right now: tiff stacks. so assume this is the type SeekableStream s = new FileSeekableStream(file); TIFFDecodeParam param = null; ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param); Log.printDebug("Number of images in this TIFF: " + dec.getNumPages()); Raster ir=dec.decodeAsRaster(); BufferedImage bim=new BufferedImage(ir.getWidth(),ir.getHeight(),ir.getSampleModel().getDataType()); WritableRaster wr=bim.getRaster(); wr.setRect(ir); return bim; } } } catch(Exception e) { Log.printError("Failed to read image "+filename,e); return null; } } //A lot of work is needed here.... public void saveImage() throws Exception { saveImage(im, new File(filename), 99); } /** * Save an image to disk */ private static void saveImage(BufferedImage im, File toFile, float quality) throws Exception { String fileEnding=getFileEnding(toFile.getName()); if(fileEnding.equals("jpg") || fileEnding.equals("jpeg")) { FileOutputStream toStream = new FileOutputStream(toFile); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(toStream); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(im); param.setQuality(quality, false); encoder.setJPEGEncodeParam(param); encoder.encode(im); } else { ImageIO.write(im, fileEnding, toFile); } } /** * Get file extension */ private static String getFileEnding(String s) { String fileEnding=s; fileEnding=fileEnding.substring(fileEnding.lastIndexOf('.')+1); return fileEnding; } }
true
true
public BufferedImage loadJavaImage() { try { File file=new File(filename); if(!file.exists()) return null; else { String fname=file.getName(); fname=fname.substring(fname.lastIndexOf(".")+1); if(slice==-1 && (fname.equals("tif") || fname.equals("tiff"))) //ImageIO failed on a .tif { SeekableStream s = new FileSeekableStream(file); TIFFDecodeParam param = null; ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param); // Log.printDebug("Number of images in this TIFF: " + dec.getNumPages()); // System.out.println("w"+ir.getWidth()+" h"+ir.getHeight()+" b"+ir.getSampleModel().getNumBands()); Raster ir=dec.decodeAsRaster(); int type=ir.getSampleModel().getDataType(); if(type==0) type=BufferedImage.TYPE_BYTE_GRAY;//? BufferedImage bim=new BufferedImage(ir.getWidth(),ir.getHeight(),type); WritableRaster wr=bim.getRaster(); wr.setRect(ir); return bim; } else if(slice==-1) { //Single-slice image System.out.println(".. "+ImageIO.read(file)+" "+file.getAbsolutePath()); return ImageIO.read(file); } else { //Multi-slice image //Only one type supported right now: tiff stacks. so assume this is the type SeekableStream s = new FileSeekableStream(file); TIFFDecodeParam param = null; ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param); Log.printDebug("Number of images in this TIFF: " + dec.getNumPages()); Raster ir=dec.decodeAsRaster(); BufferedImage bim=new BufferedImage(ir.getWidth(),ir.getHeight(),ir.getSampleModel().getDataType()); WritableRaster wr=bim.getRaster(); wr.setRect(ir); return bim; } } } catch(Exception e) { Log.printError("Failed to read image "+filename,e); return null; } }
public BufferedImage loadJavaImage() { try { File file=new File(filename); if(!file.exists()) return null; else { String fname=file.getName(); fname=fname.substring(fname.lastIndexOf(".")+1); if(slice==-1 && (fname.equals("tif") || fname.equals("tiff"))) //ImageIO failed on a .tif { SeekableStream s = new FileSeekableStream(file); TIFFDecodeParam param = null; ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param); // Log.printDebug("Number of images in this TIFF: " + dec.getNumPages()); // System.out.println("w"+ir.getWidth()+" h"+ir.getHeight()+" b"+ir.getSampleModel().getNumBands()); Raster ir=dec.decodeAsRaster(); int type=ir.getSampleModel().getDataType(); if(type==0) type=BufferedImage.TYPE_BYTE_GRAY;//? BufferedImage bim=new BufferedImage(ir.getWidth(),ir.getHeight(),type); WritableRaster wr=bim.getRaster(); wr.setRect(ir); return bim; } else if(slice==-1) { //Single-slice image // System.out.println(".. "+ImageIO.read(file)+" "+file.getAbsolutePath()); return ImageIO.read(file); } else { //Multi-slice image //Only one type supported right now: tiff stacks. so assume this is the type SeekableStream s = new FileSeekableStream(file); TIFFDecodeParam param = null; ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param); Log.printDebug("Number of images in this TIFF: " + dec.getNumPages()); Raster ir=dec.decodeAsRaster(); BufferedImage bim=new BufferedImage(ir.getWidth(),ir.getHeight(),ir.getSampleModel().getDataType()); WritableRaster wr=bim.getRaster(); wr.setRect(ir); return bim; } } } catch(Exception e) { Log.printError("Failed to read image "+filename,e); return null; } }
diff --git a/src/sphinx4/edu/cmu/sphinx/util/props/test/ConfigurationManagerTest.java b/src/sphinx4/edu/cmu/sphinx/util/props/test/ConfigurationManagerTest.java index ebe8a257..ec51898c 100644 --- a/src/sphinx4/edu/cmu/sphinx/util/props/test/ConfigurationManagerTest.java +++ b/src/sphinx4/edu/cmu/sphinx/util/props/test/ConfigurationManagerTest.java @@ -1,120 +1,120 @@ package edu.cmu.sphinx.util.props.test; import edu.cmu.sphinx.util.props.*; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Some unit tests, which ensure a proper implementation of configuration management. * * @author Holger Brandl */ public class ConfigurationManagerTest { @Test public void testDynamicConfCreation() throws PropertyException, InstantiationException { ConfigurationManager cm = new ConfigurationManager(); String instanceName = "docu"; Map<String, Object> props = new HashMap<String, Object>(); props.put(DummyComp.PROP_FRONTEND, new DummyFrontEnd()); cm.addConfigurable(DummyComp.class, instanceName, props); Assert.assertTrue(cm.getPropertySheet(instanceName) != null); Assert.assertTrue(cm.lookup(instanceName) != null); Assert.assertTrue(cm.lookup(instanceName) instanceof DummyComp); } @Test public void testSerialization() throws IOException, PropertyException { File configFile = new File("../../sphinx4/tests/other/testconfig.sxl"); ConfigurationManager cm = new ConfigurationManager(configFile.toURI().toURL()); File tmpFile = File.createTempFile("ConfigurationManager", ".tmp.xml"); tmpFile.deleteOnExit(); System.out.println(ConfigurationManagerUtils.toXML(cm)); ConfigurationManagerUtils.save(cm, tmpFile); // now reload it ConfigurationManager cmReloaded = new ConfigurationManager(tmpFile.toURI().toURL()); Assert.assertTrue("deserialzed cm doesn't equal its original", cmReloaded.equals(cm)); } @Test public void testDynamicConfiguruationChange() throws IOException, PropertyException, InstantiationException { File configFile = new File("../../sphinx4/tests/other/testconfig.sxl"); ConfigurationManager cm = new ConfigurationManager(configFile.toURI().toURL()); Assert.assertTrue(cm.getInstanceNames(DummyFrontEndProcessor.class).isEmpty()); PropertySheet propSheet = cm.getPropertySheet("duco"); propSheet.setDouble("alpha", 11); DummyComp duco = (DummyComp) cm.lookup("duco"); Assert.assertTrue(cm.getInstanceNames(DummyFrontEndProcessor.class).size() == 1); // IMPORTANT because we assume the configurable to be instantiated first at // lookup there is no need to call newProperties here // duco.newProperties(propSheet); Assert.assertTrue(duco.getAlpha() == 11); } @Test public void testSerializeDynamicConfiguration() throws PropertyException, InstantiationException { ConfigurationManager cm = new ConfigurationManager(); String frontEndName = "myFrontEnd"; cm.addConfigurable(DummyFrontEnd.class, frontEndName); PropertySheet propSheet = cm.getPropertySheet(frontEndName); propSheet.setComponentList("dataProcs", Arrays.asList("fooBar"), Arrays.<Configurable>asList(new AnotherDummyProcessor())); String xmlString = ConfigurationManagerUtils.toXML(cm); System.out.println(xmlString); Assert.assertTrue(xmlString.contains(frontEndName)); Assert.assertTrue(xmlString.contains("fooBar")); // because it is already there: test whether dynamic list changing really works DummyFrontEnd frontEnd = (DummyFrontEnd) cm.lookup(frontEndName); Assert.assertTrue(frontEnd.getDataProcs().size() == 1); Assert.assertTrue(frontEnd.getDataProcs().get(0) instanceof AnotherDummyProcessor); } @Test public void testXmlExtendedConfiguration() { - ConfigurationManager cm = new ConfigurationManager("../../sphinx4/tests/other/extendconfig.sxl"); + ConfigurationManager cm = new ConfigurationManager("../tests/other/extendconfig.sxl"); String instanceName = "duco"; Assert.assertTrue(cm.getPropertySheet(instanceName) != null); Assert.assertTrue(cm.lookup(instanceName) != null); Assert.assertTrue(cm.lookup(instanceName) instanceof DummyComp); DummyComp docu = (DummyComp) cm.lookup(instanceName); // test the parameters were sucessfully overridden Assert.assertTrue(docu.getFrontEnd().getDataProcs().isEmpty()); Assert.assertTrue(docu.getBeamWidth() == 4711); // test the the non-overridden properties of the parent-configuration were preserved Assert.assertNotNull((DummyProcessor) cm.lookup("processor")); // test the global properties: Assert.assertTrue("-5".equals(cm.getGlobalProperties().get("myalpha").getValue())); // overridden property Assert.assertEquals("opencards", cm.getGlobalProperties().get("hiddenproductad").getValue()); // preserved property } }
true
true
public void testXmlExtendedConfiguration() { ConfigurationManager cm = new ConfigurationManager("../../sphinx4/tests/other/extendconfig.sxl"); String instanceName = "duco"; Assert.assertTrue(cm.getPropertySheet(instanceName) != null); Assert.assertTrue(cm.lookup(instanceName) != null); Assert.assertTrue(cm.lookup(instanceName) instanceof DummyComp); DummyComp docu = (DummyComp) cm.lookup(instanceName); // test the parameters were sucessfully overridden Assert.assertTrue(docu.getFrontEnd().getDataProcs().isEmpty()); Assert.assertTrue(docu.getBeamWidth() == 4711); // test the the non-overridden properties of the parent-configuration were preserved Assert.assertNotNull((DummyProcessor) cm.lookup("processor")); // test the global properties: Assert.assertTrue("-5".equals(cm.getGlobalProperties().get("myalpha").getValue())); // overridden property Assert.assertEquals("opencards", cm.getGlobalProperties().get("hiddenproductad").getValue()); // preserved property }
public void testXmlExtendedConfiguration() { ConfigurationManager cm = new ConfigurationManager("../tests/other/extendconfig.sxl"); String instanceName = "duco"; Assert.assertTrue(cm.getPropertySheet(instanceName) != null); Assert.assertTrue(cm.lookup(instanceName) != null); Assert.assertTrue(cm.lookup(instanceName) instanceof DummyComp); DummyComp docu = (DummyComp) cm.lookup(instanceName); // test the parameters were sucessfully overridden Assert.assertTrue(docu.getFrontEnd().getDataProcs().isEmpty()); Assert.assertTrue(docu.getBeamWidth() == 4711); // test the the non-overridden properties of the parent-configuration were preserved Assert.assertNotNull((DummyProcessor) cm.lookup("processor")); // test the global properties: Assert.assertTrue("-5".equals(cm.getGlobalProperties().get("myalpha").getValue())); // overridden property Assert.assertEquals("opencards", cm.getGlobalProperties().get("hiddenproductad").getValue()); // preserved property }